Skip to contentSkip to conversation

7.3.7-rc1 review

PATCH In review Greg Kroah-Hartman 5 participants 1,010 messages Nov 25 Page 7 of 9

Subsystems (3)
lore
Share & tools
lore
author maintainer
#700 lore raw

PATCH 699/1005 ext4: use sb_find_get_block_nonatomic() in ext4_get_inode_loc_noio()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Christian Brauner <[email protected]>

commit d25c14b2d79e4e8292b19041efd1aae4057bf383 upstream.

ext4_get_inode_loc_noio() looks the inode table block up with sb_find_get_block(). That's the atomic lookup. It serializes against try_to_free_buffers() with i_private_lock instead of the folio lock and gives up if the folio is being migrated. So it can report the block as not cached while it is.

For ext4_fc_snapshot_inode() that only means falling back to a full commit. But ext4_sync_inode_metadata() is going to use ext4_get_inode_loc_noio() to find the inode block that fsync() has to write out and there a dirty block must not be skipped.

ext4_fc_snapshot_inode() is the only caller and it can sleep. It runs under jbd2_journal_lock_updates() and allocates the snapshot with GFP_NOFS. So use sb_find_get_block_nonatomic() which takes the folio lock and waits for the migration instead.

---
 fs/ext4/inode.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
fs/ext4/inode.c +3 -2
@@ -5060,7 +5060,8 @@ int ext4_get_inode_loc(struct inode *ino
 /*
  * ext4_get_inode_loc_noio() is a best-effort variant of ext4_get_inode_loc().
  * It looks up the inode table block in the buffer cache and returns -EAGAIN if
- * the block is not present or not uptodate, without starting any I/O.
+ * the block is not present or not uptodate, without starting any I/O. It may
+ * sleep on the folio lock of the block.
  */
 int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc)
 {
@@ -5096,7 +5097,7 @@ int ext4_get_inode_loc_noio(struct inode
 	}
 	block += inode_offset / inodes_per_block;
 
-	bh = sb_find_get_block(sb, block);
+	bh = sb_find_get_block_nonatomic(sb, block);
 	if (!bh)
 		return -EAGAIN;
 	if (!ext4_buffer_uptodate(bh)) {
author maintainer
#701 lore raw

PATCH 700/1005 ext4: dont read the inode block in ext4_sync_inode_metadata()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Christian Brauner <[email protected]>

commit 2ca2e88b106175c1037939de52cb28e4cb545b9e upstream.

Without a journal ext4_sync_inode_metadata() looks the inode table block up with __ext4_get_inode_loc_noinmem() which reads it from disk, with readahead of the inode table on top, if it isn't cached. But a block that isn't cached is neither dirty nor under writeback, so there's nothing to write or to wait for.

That read is also something we can't afford once inode eviction calls ->sync_inode_metadata() from reclaim. So look the block up with ext4_get_inode_loc_noio() instead and treat -EAGAIN as nothing to do.

Note that ext4_get_inode_loc_noio() also returns -EAGAIN for a block that isn't uptodate. Such a block is being read or failed to be read and can't be dirty either. A block whose write failed still counts as uptodate for ext4_buffer_uptodate() so the write error still gets reported.

---
 fs/ext4/inode.c |   12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)
fs/ext4/inode.c +7 -5
@@ -5922,22 +5922,24 @@ int ext4_sync_inode_metadata(struct inod
 	if (WARN_ON_ONCE(EXT4_SB(inode->i_sb)->s_journal))
 		return -EFSCORRUPTED;
 
-	err = __ext4_get_inode_loc_noinmem(inode, &iloc);
-	if (err)
-		return err;
 	mmb = READ_ONCE(EXT4_I(inode)->i_metadata_bhs);
 	if (mmb) {
 		err = mmb_sync(mmb);
 		if (err)
-			goto out;
+			return err;
 	}
+	/* A block that isn't cached is neither dirty nor under writeback. */
+	err = ext4_get_inode_loc_noio(inode, &iloc);
+	if (err == -EAGAIN)
+		return 0;
+	if (err)
+		return err;
 	sync_dirty_buffer(iloc.bh);
 	if (buffer_write_io_error(iloc.bh)) {
 		ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
 				       "IO error syncing inode");
 		err = -EIO;
 	}
-out:
 	brelse(iloc.bh);
 	return err;
 }
author maintainer
#702 lore raw

PATCH 701/1005 fs/adfs: bound directory entry name length in adfs_fplus_getnext()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: HyeongJun An <[email protected]>

commit ebf5025b0d989f95542fc9da899b7de2fec499f2 upstream.

adfs_fplus_getnext() reads the per-entry name length bigdirobnamelen straight from the on-disk big directory and passes it to adfs_dir_copyfrom() as the copy length into obj->name[], a fixed ADFS_MAX_NAME_LEN (260) byte buffer. adfs_dir_copyfrom() only bounds the copy against the number of directory buffers, not the size of the destination, so a crafted image with bigdirobnamelen larger than the buffer overflows the stack-allocated object_info::name that adfs_fplus_iterate() passes in.

adfs_object_fixup() may additionally append a four byte ",xyz" filetype suffix, so the accepted length must also leave room for that.

The old-style directory parser (dir_f.c) already clamps names to ADFS_F_NAME_LEN, and adfs_fplus_validate_header() validates the header name fields, but the per-entry name length in the big directory format was never checked. Reject over-long entries, using -EIO as elsewhere in this file for a corrupt big directory.

---
 fs/adfs/dir_fplus.c |    2 ++
 1 file changed, 2 insertions(+)
fs/adfs/dir_fplus.c +2 -0
@@ -192,6 +192,8 @@ adfs_fplus_getnext(struct adfs_dir *dir,
 	obj->indaddr  = le32_to_cpu(bde.bigdirindaddr);
 	obj->attr     = le32_to_cpu(bde.bigdirattr);
 	obj->name_len = le32_to_cpu(bde.bigdirobnamelen);
+	if (obj->name_len > ADFS_MAX_NAME_LEN - 4)	/* leave room for ,xyz suffix */
+		return -EIO;
 
 	offset = adfs_fplus_offset(h, le32_to_cpu(h->bigdirentries));
 	offset += le32_to_cpu(bde.bigdirobnameptr);
author maintainer
#703 lore raw

PATCH 702/1005 fs/proc: fix the write length returned by proc_sys_call_handler()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Cheng Yongkang <[email protected]>

commit fbdc020ee1b82079102e493aaa7200de5f497a38 upstream.

proc_sys_call_handler() reads the write length from iov_iter_count() and copies that many bytes from the iterator into kbuf. A cgroup/sysctl BPF program can replace the new value through bpf_sysctl_set_new_value() and update count to the length of the replacement value. The handler then returns that adjusted count as the number of bytes written, even though the iterator originally held a different number of bytes.

If the replacement value is longer than the original input, ->write_iter() reports more bytes than the iterator held. splice(2) passes that value to iter_file_splice_write(), which subtracts it from the pipe length and walks past the pipe head:

Splice Exceeded! ret=7 tot=1 left=0

  Oops: general protection fault
  RIP: 0010:iter_file_splice_write+0xb6f/0x1170

The write path consumes at most the original iterator length in copy_from_iter_full() before the BPF hook runs. Return the smaller of the adjusted and original counts on the write path, so an expanded BPF value cannot exceed the iterator while a handler that reports a shorter parsed length still produces a short write. The read path keeps using the adjusted count for copy_to_iter().

---
 fs/proc/proc_sysctl.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/proc/proc_sysctl.c +4 -1
@@ -557,6 +557,8 @@ static ssize_t proc_sys_call_handler(str
 	struct ctl_table_header *head = grab_header(inode);
 	const struct ctl_table *table = PROC_I(inode)->sysctl_entry;
 	size_t count = iov_iter_count(iter);
+	/* ->write_iter() must never report more than the iterator held */
+	size_t orig_count = count;
 	char *kbuf;
 	ssize_t error;
 
@@ -607,7 +609,8 @@ static ssize_t proc_sys_call_handler(str
 			goto out_free_buf;
 	}
 
-	error = count;
+	/* the write path consumed at most the original iterator length */
+	error = write ? min(count, orig_count) : count;
 out_free_buf:
 	kvfree(kbuf);
 out:
author maintainer
#704 lore raw

PATCH 703/1005 fs/splice: clamp an over-reported write_iter result

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Cheng Yongkang <[email protected]>

commit 2d956723e82cddae8ff8e9da99a666217b02065f upstream.

iter_file_splice_write() builds a bvec iterator of at most sd.total_len - left bytes and passes it to ->write_iter(). It then subtracts the returned length from sd.total_len and walks the pipe buffers by that length. A ->write_iter() implementation that reports more bytes than the iterator held makes sd.total_len underflow and the dismissal loop advance pipe->tail past pipe->head, releasing a zeroed pipe buffer:

Splice Exceeded! ret=7 tot=1 left=0

  Oops: general protection fault
  RIP: 0010:iter_file_splice_write+0xb6f/0x1170

Commit a3de58b12ce0 ("netfs: Fix unbuffered write error handling") added the warning for this condition but only reports it. Clamp the return value to the size of the iterator that was actually handed to ->write_iter(), so the pipe accounting stays consistent even when a producer violates the iterator contract.

---
 fs/splice.c |    9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
fs/splice.c +6 -3
@@ -737,9 +737,12 @@ iter_file_splice_write(struct pipe_inode
 		sd.pos = kiocb.ki_pos;
 		if (ret <= 0)
 			break;
-		WARN_ONCE(ret > sd.total_len - left,
-			  "Splice Exceeded! ret=%zd tot=%zu left=%zu\n",
-			  ret, sd.total_len, left);
+		if (unlikely(ret > sd.total_len - left)) {
+			WARN_ONCE(1,
+				  "Splice Exceeded! ret=%zd tot=%zu left=%zu\n",
+				  ret, sd.total_len, left);
+			ret = sd.total_len - left;
+		}
 
 		sd.num_spliced += ret;
 		sd.total_len -= ret;
author maintainer
#705 lore raw

PATCH 704/1005 fs: dont strand I_METADATA_WRITEBACK inodes outside the LRU

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Christian Brauner <[email protected]>

commit 9b4b26d110f32008134750f82c98e621f2e4758f upstream.

Since commit c474bc56b6d1 ("fs: Provide way for filesystem to wait for metadata writeback") ext2, ext4 without a journal, fat, udf and minix set I_METADATA_WRITEBACK on an inode whose metadata was copied into a buffer that might not have reached the disk yet. Only data integrity writeback, i.e. fsync() and friends, clears it again. The flusher and sync(2) leave it alone.

inode_lru_isolate() treats every state bit other than I_REFERENCED as a reason not to reclaim the inode right now. It takes the inode off the LRU and relies on iput(), writeback completion or the removal of the last page from the page cache to put it back once the reason is gone.

But I_METADATA_WRITEBACK doesn't go away on its own. iput() puts the inode back on the LRU with the bit still set and the next scan takes it off again. So neither memory pressure nor drop_caches can free these inodes. Only fsync() and friends or unmounting the filesystem get rid of them.

On ext4 without a journal ext4_mark_iloc_dirty() sets the bit on every ext4_mark_inode_dirty(), so even an atime update is enough. An unprivileged user creating or touching lots of files grows the inode cache without bound until the OOM killer comes along.

The inode can't just be thrown away though. An fsync() after the inode was read back in wouldn't know that its metadata still has to be written out. So let the shrinker reclaim inodes with I_METADATA_WRITEBACK like any other clean inode and make evict() write out what the bit tracks unless the inode is being deleted. Since the previous patch the bit covers the tracked metadata buffers as well, and since the lookup patches ->sync_inode_metadata() doesn't read anything from disk for that. It writes and waits for whatever is still dirty or under writeback. The mmb_sync() calls in ->evict_inode() are redundant with that and the following patches drop them.

Handing these inodes to a work item that syncs them and puts them back on the LRU would work too. But that's a second inode reclaim offload mechanism next to the deferred inode reclaim that is being worked on, and it needs a reference on the inode which leaks into remount, freeze and umount.

For stable this needs the previous patches as well. Without the lookup changes evict() ends up reading inode blocks from disk with __GFP_NOFAIL allocations from reclaim. v7.3 also still has bfs which sets I_METADATA_WRITEBACK too and reads the inode block in bfs_sync_inode_metadata(), so the backport needs the cache-only lookup for bfs as well.

---
 fs/inode.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
fs/inode.c +12 -1
index 9cbcb0de7dfc..de207f2f95a9 100644
@@ -817,6 +817,14 @@ static void evict(struct inode *inode)
 	inode_wait_for_writeback(inode);
 	spin_unlock(&inode->i_lock);
 
+	/*
+	 * fsync() can't find what I_METADATA_WRITEBACK tracks anymore once the
+	 * inode is gone, so write it out unless the inode is being deleted.
+	 */
+	if (inode->i_nlink &&
+	    (inode_state_read_once(inode) & I_METADATA_WRITEBACK))
+		sync_inode_metadata(inode, 1);
+
 	if (op->evict_inode) {
 		op->evict_inode(inode);
 	} else {
@@ -952,9 +960,12 @@ static enum lru_status inode_lru_isolate(struct list_head *item,
 	 * they're already on the LRU, and this can make them
 	 * unreclaimable for a while. Remove them lazily here; iput,
 	 * sync, or the last page cache deletion will requeue them.
+	 * Nothing requeues them for I_METADATA_WRITEBACK, evict() writes
+	 * that out instead.
 	 */
 	if (icount_read(inode) ||
-	    (inode_state_read(inode) & ~I_REFERENCED) ||
+	    (inode_state_read(inode) &
+	     ~(I_REFERENCED | I_METADATA_WRITEBACK)) ||
 	    !mapping_shrinkable(&inode->i_data)) {
 		list_lru_isolate(lru, &inode->i_lru);
 		spin_unlock(&inode->i_lock);
Signature · 1 line
2.56.1
author maintainer
#706 lore raw

PATCH 705/1005 arm64/gcs: Ignore attempts to change GCS mode during signal return

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mark Brown <[email protected]>

commit d395db3dcd4c590d26a2f3d581d8d5b7ddbfa478 upstream.

If userspace tries to update the GCS mode as part of signal return then we update the thread state but don't update GCSCRE0_EL1, meaning the change does not take effect. We may also get issues for other tasks on context switch since we suppress writes of the register if the two tasks have the same mode.

Since no currently known userspace tries to use this functionality close this by ignoring any attempt to change the mode through signal return. The GCS mode for the current thread can be changed using the prctl() interface and will be preserved on signal return, allowing updates to the mode from the signal handler.

---
 Documentation/arch/arm64/gcs.rst |   13 ++++---------
 arch/arm64/kernel/signal.c       |   22 +---------------------
 2 files changed, 5 insertions(+), 30 deletions(-)
Documentation/arch/arm64/gcs.rst +4 -9
@@ -179,9 +179,8 @@ intended to be exhaustive.
 
 When returning from a signal handler:
 
-* If there is a gcs_context record in the signal frame then the GCS flags
-  and GCSPR_EL0 will be restored from that context prior to further
-  validation.
+* If there is a gcs_context record in the signal frame then GCSPR_EL0
+  will be restored from that context prior to further validation.
 
 * If there is no gcs_context record in the signal frame then the GCS
   configuration will be unchanged.
@@ -190,12 +189,8 @@ When returning from a signal handler:
   point to a valid GCS signal cap record, this will be popped from the
   GCS prior to signal return.
 
-* If the GCS configuration is locked when returning from a signal then any
-  attempt to change the GCS configuration will be treated as an error.  This
-  is true even if GCS was not enabled prior to signal entry.
-
-* GCS may be disabled via signal return but any attempt to enable GCS via
-  signal return will be rejected.
+* The features_enabled in the signal return context will be ignored; any
+  changes made using the prctl() in the signal handler will be preserved.
 
 
 6.  ptrace extensions
arch/arm64/kernel/signal.c +1 -21
@@ -741,36 +741,16 @@ static int preserve_gcs_context(struct g
 
 static int restore_gcs_context(struct user_ctxs *user)
 {
-	u64 gcspr, enabled;
+	u64 gcspr;
 	int err = 0;
 
 	if (user->gcs_size != sizeof(*user->gcs))
 		return -EINVAL;
 
 	__get_user_error(gcspr, &user->gcs->gcspr, err);
-	__get_user_error(enabled, &user->gcs->features_enabled, err);
 	if (err)
 		return err;
 
-	/* Don't allow unknown modes */
-	if (enabled & ~PR_SHADOW_STACK_SUPPORTED_STATUS_MASK)
-		return -EINVAL;
-
-	err = gcs_check_locked(current, enabled);
-	if (err != 0)
-		return err;
-
-	/* Don't allow enabling */
-	if (!task_gcs_el0_enabled(current) &&
-	    (enabled & PR_SHADOW_STACK_ENABLE))
-		return -EINVAL;
-
-	/* If we are disabling disable everything */
-	if (!(enabled & PR_SHADOW_STACK_ENABLE))
-		enabled = 0;
-
-	current->thread.gcs_el0_mode = enabled;
-
 	/*
 	 * We let userspace set GCSPR_EL0 to anything here, we will
 	 * validate later in gcs_restore_signal().
author maintainer
#707 lore raw

PATCH 706/1005 arm64: errata: Extend the workaround for broken AMEVCNTR01 counter

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Beata Michalska <[email protected]>

commit 139a9b7d5a07a570d5f636db02105025ece99e16 upstream.

The erratum causing significant inaccuracies in the AMU CNT_CYCLES counter due to WFI/WFE has been identified in additional microarchitectures.
Extend the existing workaround to cover these implementations, which are affected by the following errata:

- ARM Cortex-A725 erratum 3821522 (SDEN-2832921)
- ARM Cortex-A720 erratum 4689339 (SDEN-2439421)
- ARM Cortex-A720AE erratum 4689340 (SDEN-3090091)
- ARM Neoverse N3 erratum 4689341 (SDEN-3050973)
- ARM C1-Pro erratum 4689344 (SDEN-3273080)

---
 Documentation/arch/arm64/silicon-errata.rst |    8 ++++++++
 arch/arm64/Kconfig                          |   12 +++++++++---
 arch/arm64/kernel/cpu_errata.c              |    8 ++++++++
 3 files changed, 25 insertions(+), 3 deletions(-)
Documentation/arch/arm64/silicon-errata.rst +8 -0
@@ -172,6 +172,10 @@ stable kernels.
 +----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A720     | #3456091        | ARM64_ERRATUM_3194386       |
 +----------------+-----------------+-----------------+-----------------------------+
+| ARM            | Cortex-A720     | #4689339        | ARM64_ERRATUM_3821522       |
++----------------+-----------------+-----------------+-----------------------------+
+| ARM            | Cortex-A720AE   | #4689340        | ARM64_ERRATUM_3821522       |
++----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A725     | #3456106        | ARM64_ERRATUM_3194386       |
 +----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A725     | #3821522        | ARM64_ERRATUM_3821522       |
@@ -230,6 +234,8 @@ stable kernels.
 +----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Neoverse-N3     | #3456111        | ARM64_ERRATUM_3194386       |
 +----------------+-----------------+-----------------+-----------------------------+
+| ARM            | Neoverse-N3     | #4689341        | ARM64_ERRATUM_3821522       |
++----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Neoverse-V1     | #1619801        | N/A                         |
 +----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Neoverse-V1     | #3324341        | ARM64_ERRATUM_3194386       |
@@ -254,6 +260,8 @@ stable kernels.
 +----------------+-----------------+-----------------+-----------------------------+
 | ARM            | C1-Pro          | #4193714        | ARM64_ERRATUM_4193714       |
 +----------------+-----------------+-----------------+-----------------------------+
+| ARM            | C1-Pro          | #4689344        | ARM64_ERRATUM_3821522       |
++----------------+-----------------+-----------------+-----------------------------+
 | ARM            | C1-Ultra        | #3683289        | N/A                         |
 +----------------+-----------------+-----------------+-----------------------------+
 | ARM            | C1-Ultra        | #4193780        | ARM64_ERRATUM_4118414       |
arch/arm64/Kconfig +9 -3
@@ -1083,14 +1083,20 @@ config ARM64_ERRATUM_2645198
 	  If unsure, say Y.
 
 config ARM64_ERRATUM_3821522
-	bool "Cortex-A725: 3821522: workaround for possible CNT_CYCLES increment error due to WFE/WFI"
+	bool "Cortex-*/Neoverse-*/C1-*: workaround for possible CNT_CYCLES increment error due to WFE/WFI"
 	depends on ARM64_AMU_EXTN
 	select ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT
 	default y
 	help
-	  This option adds the workaround for ARM Cortex-A725 erratum 3821522.
+	  This option adds the workaround for the following errata:
 
-	  On affected A725 cores, the CNT_CYCLES event may incur a significant
+	  * ARM Cortex-A725 erratum 3821522
+	  * ARM Cortex-A720 erratum 4689339
+	  * ARM Cortex-A720AE erratum 4689340
+	  * ARM Neoverse N3 erratum 4689341
+	  * ARM C1-Pro erratum 4689344
+
+	  On affected cores, the CNT_CYCLES event may incur a significant
 	  increment error when entering and subsequently exiting WFx.
 	  As a result, the CNT_CYCLES may diverge from the system counter
 	  frequency at which it is expected to increment.
arch/arm64/kernel/cpu_errata.c +8 -0
@@ -391,8 +391,16 @@ static const struct midr_range workaroun
 	MIDR_RANGE(MIDR_CORTEX_A510, 0, 0, 1, 1),
 #endif
 #ifdef CONFIG_ARM64_ERRATUM_3821522
+	/* Cortex-A720 r0p0 - r0p2 */
+	MIDR_RANGE(MIDR_CORTEX_A720, 0, 0, 0, 2),
+	/* Cortex-A720AE r0p0 - r0p1 */
+	MIDR_RANGE(MIDR_CORTEX_A720AE, 0, 0, 0, 1),
 	/* Cortex-A725 r0p0 - r0p2 */
 	MIDR_RANGE(MIDR_CORTEX_A725, 0, 0, 0, 2),
+	/* Neoverse N3 r0p0 - r0p1 */
+	MIDR_RANGE(MIDR_NEOVERSE_N3, 0, 0, 0, 1),
+	/* C1-Pro r0p0 - r1p3 */
+	MIDR_RANGE(MIDR_C1_PRO, 0, 0, 1, 3),
 #endif
 	{}
 };
author maintainer
#708 lore raw

PATCH 707/1005 arm64: errata: Add Cortex-A715/A720 AMU core counter workaround

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Beata Michalska <[email protected]>

commit be777145858218f591b4d9d19f3d40d3ecea9de3 upstream.

On Cortex-A715 (erratum 2738462) and Cortex-A720 (erratum 2738461), the AMEVCNTR00 counter may continue incrementing while the core remains in WFE with the clocks being enabled. The resulting core cycle count may become unreliable.

Add a workaround that effectively treats the AMU counter as unavailable.

---
 Documentation/arch/arm64/silicon-errata.rst |    4 +++
 arch/arm64/Kconfig                          |   32 ++++++++++++++++++++++++++++
 arch/arm64/kernel/cpu_errata.c              |   20 +++++++++++++++++
 arch/arm64/kernel/cpufeature.c              |    3 +-
 arch/arm64/kernel/topology.c                |    3 +-
 arch/arm64/tools/cpucaps                    |    1 
 6 files changed, 61 insertions(+), 2 deletions(-)
Documentation/arch/arm64/silicon-errata.rst +4 -0
@@ -168,8 +168,12 @@ stable kernels.
 +----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A715     | #2645198        | ARM64_ERRATUM_2645198       |
 +----------------+-----------------+-----------------+-----------------------------+
+| ARM            | Cortex-A715     | #2738462        | ARM64_ERRATUM_2738461       |
++----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A715     | #3456084        | ARM64_ERRATUM_3194386       |
 +----------------+-----------------+-----------------+-----------------------------+
+| ARM            | Cortex-A720     | #2738461        | ARM64_ERRATUM_2738461       |
++----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A720     | #3456091        | ARM64_ERRATUM_3194386       |
 +----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A720     | #4689339        | ARM64_ERRATUM_3821522       |
arch/arm64/Kconfig +32 -0
@@ -1048,6 +1048,38 @@ config ARM64_WORKAROUND_BROKEN_AMU_CONST
 	# making it unreliable. As a result, AMU users should treat it as
 	# unavailable rather than relying on misleading counter values.
 
+config ARM64_WORKAROUND_BROKEN_AMU_CORECNT
+	bool
+	# Targeting errata affecting AMEVCNTR00, the AMU core cycle counter.
+	# On affected CPUs the counter may continue incrementing while core
+	# remains in WFE with the clocks enabled.
+	# This may lead to readings of said counter being unreliable.
+	# How much though depends on the sampling intervals.
+
+config ARM64_ERRATUM_2738461
+	bool "Cortex-A715/Cortex-A720: workaround for AMEVCNTR00 incrementing incorrectly"
+	depends on ARM64_AMU_EXTN
+	select ARM64_WORKAROUND_BROKEN_AMU_CORECNT
+	default y
+	help
+	  This option adds the workaround for the following errata:
+
+	  * ARM Cortex-A715 erratum 2738462
+	  * ARM Cortex-A720 erratum 2738461
+
+	  On affected cores the AMEVCNTR00 counter (AMU core frequency cycles
+	  counter) may continue incrementing while the core remains in WFE
+	  with the clocks being enabled.
+	  This may result in inaccurate counter readings, with the magnitude
+	  of the discrepancy depending on the sampling interval.
+
+	  With this workaround, reads of the affected counter return 0 in
+	  the relevant paths. This causes users of the counter to treat it
+	  as unavailable and is functionally equivalent to firmware disabling
+	  the affected counter.
+
+	  If unsure, say Y.
+
 config ARM64_ERRATUM_2457168
 	bool "Cortex-A510: 2457168: workaround for AMEVCNTR01 incrementing incorrectly"
 	depends on ARM64_AMU_EXTN
arch/arm64/kernel/cpu_errata.c +20 -0
@@ -406,6 +406,18 @@ static const struct midr_range workaroun
 };
 #endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT */
 
+#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT
+static const struct midr_range workaround_amu_corecnt_list[] = {
+#ifdef CONFIG_ARM64_ERRATUM_2738461
+	/* Cortex-A715 r0p0 - r1p3 */
+	MIDR_RANGE(MIDR_CORTEX_A715, 0, 0, 1, 3),
+	/* Cortex-A720 r0p0 - r0p1 */
+	MIDR_RANGE(MIDR_CORTEX_A720, 0, 0, 0, 1),
+#endif
+	{}
+};
+#endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT */
+
 #ifdef CONFIG_CAVIUM_ERRATUM_23154
 static const struct midr_range cavium_erratum_23154_cpus[] = {
 	MIDR_ALL_VERSIONS(MIDR_THUNDERX),
@@ -949,6 +961,14 @@ const struct arm64_cpu_capabilities arm6
 		CAP_MIDR_RANGE_LIST(workaround_amu_constcnt_list)
 	},
 #endif
+#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT
+	{
+		.desc = "Broken AMU AMEVCNTR00 (core cycle counter)",
+		.capability = ARM64_WORKAROUND_BROKEN_AMU_CORECNT,
+		.type = ARM64_CPUCAP_WEAK_LOCAL_CPU_FEATURE,
+		CAP_MIDR_RANGE_LIST(workaround_amu_corecnt_list)
+	},
+#endif
 #ifdef CONFIG_ARM64_ERRATUM_2038923
 	{
 		.desc = "ARM erratum 2038923",
arch/arm64/kernel/cpufeature.c +2 -1
@@ -2089,7 +2089,8 @@ static void cpu_amu_enable(struct arm64_
 		cpumask_set_cpu(smp_processor_id(), &amu_cpus);
 
 		/* 0 reference values signal broken/disabled counters */
-		if (!this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT))
+		if (!this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT) &&
+		    !this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CORECNT))
 			update_freq_counters_refs();
 	}
 }
arch/arm64/kernel/topology.c +2 -1
@@ -389,7 +389,8 @@ static void cpu_read_corecnt(void *val)
 	 * counter read is properly handled as an error case by the users of the
 	 * counter.
 	 */
-	*(u64 *)val = read_corecnt();
+	*(u64 *)val = this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CORECNT) ?
+		      0UL : read_corecnt();
 }
 
 static void cpu_read_constcnt(void *val)
arch/arm64/tools/cpucaps +1 -0
@@ -132,3 +132,4 @@ WORKAROUND_SPECULATIVE_AT
 WORKAROUND_SPECULATIVE_SSBS
 WORKAROUND_SPECULATIVE_UNPRIV_LOAD
 WORKAROUND_BROKEN_AMU_CONSTCNT
+WORKAROUND_BROKEN_AMU_CORECNT
author maintainer
#709 lore raw

PATCH 708/1005 arm64: hugetlb: Prevent write fault livelocks on stale TLB entries

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Chris Down <[email protected]>

commit 3c47ec82540ce89a6fdfd5e0e6d79f35892adfa4 upstream.

In Meta production, we have had tasks get stuck in a fault loop while using hugetlb on arm64. During my investigations I found that affected tasks share a private hugetlb page.

Looking at the stuck task states, I found the following ordering:

CPU0 CPU1
---- ----
read page
[read only entry cached in TLB]
write page hugetlb_fault()
hugetlb_wp()
[reuse folio] set_huge_ptep_maybe_writable()
set_huge_ptep_writable()
[flush local TLB only]

write page using stale entry
hugetlb_fault()
huge_ptep_set_access_flags()
[entry already writable, no flush]
retry write using stale entry
[fault indefinitely. well, that's not ideal!]

The reason is that when a write fault makes a non-contiguous hugetlb entry writable, it only invalidates the local TLB. However, another CPU can keep the old read-only entry, so its write will fault even though the page table already permits it. hugetlb_fault() then finds nothing to change and leaves the stale entry in place, so the same write keeps going round in circles.

This is particularly bad because, if the kernel is copying to user memory, the retry stays inside the kernel and the task can't act on the pending signal.

It can even remain unkillable while holding locks across the copy, resulting in further failures. For example, a read into a hugetlb buffer can hold the pipe mutex and block other users of the pipe until the loop ends, causing cascading lockups across the machine.

To fix this, when a write fault finds nothing to change in a non-contiguous hugetlb entry, let's invalidate the local entry.

Fixes cb1fa2e99955 ("arm64, tlbflush: don't TLBI broadcast if page reused in write fault")
---
 arch/arm64/mm/hugetlbpage.c |   21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)
arch/arm64/mm/hugetlbpage.c +18 -3
@@ -429,9 +429,24 @@ int huge_ptep_set_access_flags(struct vm
 	VM_WARN_ON(!pte_present(pte));
 	ncontig = num_contig_ptes(huge_page_size(hstate_vma(vma)), &pgsize);
 
-	if (!pte_cont(pte))
-		return __ptep_set_access_flags_anysz(vma, addr, ptep, pte,
-						     dirty, pgsize);
+	if (!pte_cont(pte)) {
+		if (__ptep_set_access_flags_anysz(vma, addr, ptep, pte,
+						  dirty, pgsize))
+			return 1;
+
+		/*
+		 * Another CPU may have made the entry writable without
+		 * invalidating our stale read-only TLB entry. To avoid
+		 * indefinitely faulting on this entry, flush it.
+		 */
+		if (dirty)
+			__flush_hugetlb_tlb_range(vma, addr, addr + pgsize,
+						  pgsize,
+						  TLBF_NOWALKCACHE |
+						  TLBF_NOBROADCAST |
+						  TLBF_NONOTIFY);
+		return 0;
+	}
 
 	if (!__cont_access_flags_changed(ptep, pte, ncontig))
 		return 0;
author maintainer
#710 lore raw

PATCH 709/1005 arm64: kexec_file: Do not use CMA for images with a non-zero text_offset

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jinjie Ruan <[email protected]>

commit 18f2d01bfce99a885511c451cba95234eea190bc upstream.

image_load() adds text_offset to kernel_segment->mem and subtracts it from kernel_segment->memsz. For CMA backed segments this breaks the load path: the payload is copied to page_address(cma), which is the CMA base, while image->start is set to the adjusted address, so kexec jumps into the middle of the kernel. kimage_map_segment() has the same mismatch when a segment has been moved.

The adjusted memsz also breaks the release path: the CMA pages are freed using segment->memsz >> PAGE_SHIFT, which is fewer than were allocated, leaking the tail of the allocation.

Both problems are specific to CMA segments, which are accessed through page_address(cma) and ignore segment->mem. The normal load path uses segment->mem, so the text_offset adjustment stays consistent there. Keep honoring text_offset, but load such images from regular memory by setting image->no_cma: they lose the CMA contiguous allocation, but keep working.

---
 arch/arm64/kernel/kexec_image.c |    7 +++++++
 1 file changed, 7 insertions(+)
arch/arm64/kernel/kexec_image.c +7 -0
@@ -82,6 +82,13 @@ static void *image_load(struct kimage *i
 	kbuf.mem = KEXEC_BUF_MEM_UNKNOWN;
 	kbuf.memsz = le64_to_cpu(h->image_size);
 	text_offset = le64_to_cpu(h->text_offset);
+	/*
+	 * A CMA segment is loaded and mapped through page_address(cma), which
+	 * is the CMA base and cannot represent the text_offset adjustment
+	 * below.  Load images with a non-zero text_offset from normal memory.
+	 */
+	if (text_offset)
+		image->no_cma = true;
 	kbuf.buf_align = MIN_KIMG_ALIGN;
 
 	/* Adjust kernel segment with TEXT_OFFSET */
author maintainer
#711 lore raw

PATCH 710/1005 arm64: ptrace: dont warn on missing siginfo in a group-stop

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Gongyi <[email protected]>

commit 5306f124f3171289b2ef5bac1e08aad175f66d1e upstream.

PTRACE_ATTACH to a group-stopped child can enter do_jobctl_trap(), which calls ptrace_stop() without siginfo. If the tracer writes NT_ARM_SYSTEM_CALL, system_call_set() can change syscallno from NO_SYSCALL before update_syscall_orig_x0_after_ptrace() checks last_siginfo. WARN_ON_ONCE(!info) then fires for a valid ptrace stop.

Keep the early return when siginfo is absent, but remove the warning. This leaves orig_x0 untouched at a non-seized group-stop and preserves the existing syscall-exit-stop handling.

Fixes 88b839ce497c ("arm64: ptrace: Keep 'orig_x0' in-sync with x0 on syscall entry")
[[email protected]: modified comment as per Will's suggestion]
---
 arch/arm64/kernel/ptrace.c |    8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
arch/arm64/kernel/ptrace.c +6 -2
@@ -573,8 +573,12 @@ static void update_syscall_orig_x0_after
 	if (regs->syscallno == NO_SYSCALL)
 		return;
 
-	/* We should only be called when target is in a ptrace stop */
-	if (WARN_ON_ONCE(!info))
+	/*
+	 * For exit-stops, info is always non-NULL, but that's not true for other
+	 * stops such as non-seized group-stops. In those cases, just return early
+	 * as there's no need to update orig_x0 anyway.
+	 */
+	if (!info)
 		return;
 
 	/*
author maintainer
#712 lore raw

PATCH 711/1005 arm64: suspend: Save POR_EL0 over suspend

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mark Brown <[email protected]>

commit 2386c3dcf13e39d7576eae821af66537332c02de upstream.

POR_EL0 is a live EL0 register on systems with S1POE but it is not saved and restored by cpu_do_suspend()/cpu_do_resume(). This means that the task that initiated suspend can return to userspace with an UNKNOWN value. Fix this by saving and restoring the value over suspend.

This increases the size of struct cpu_suspend_ctx.

Fixes bf83dae90fbc ("arm64: enable the Permission Overlay Extension for EL0")
---
 arch/arm64/include/asm/suspend.h |    2 +-
 arch/arm64/mm/proc.S             |    8 ++++++++
 2 files changed, 9 insertions(+), 1 deletion(-)
arch/arm64/include/asm/suspend.h +1 -1
@@ -2,7 +2,7 @@
 #ifndef __ASM_SUSPEND_H
 #define __ASM_SUSPEND_H
 
-#define NR_CTX_REGS 15
+#define NR_CTX_REGS 16
 #define NR_CALLEE_SAVED_REGS 12
 
 /*
arch/arm64/mm/proc.S +8 -0
@@ -118,6 +118,10 @@ alternative_if ARM64_SME
 	mrs_s	x2, SYS_TPIDR2_EL0
 	str	x2, [x0, #112]
 alternative_else_nop_endif
+alternative_if ARM64_HAS_S1POE
+	mrs	x2, REG_POR_EL0
+	str	x2, [x0, #120]
+alternative_else_nop_endif
 	ret
 SYM_FUNC_END(cpu_do_suspend)
 
@@ -160,6 +164,10 @@ alternative_if ARM64_SME
 	ldr	x2, [x0, #112]
 	msr_s	SYS_TPIDR2_EL0, x2
 alternative_else_nop_endif
+alternative_if ARM64_HAS_S1POE
+	ldr	x2, [x0, #120]
+	msr	REG_POR_EL0, x2
+alternative_else_nop_endif
 
 	msr	sctlr_el1, x12
 	set_this_cpu_offset x13
author maintainer
#713 lore raw

PATCH 712/1005 arm64: suspend: Save GCS state over suspend

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mark Brown <[email protected]>

commit 7ca488055c69eed71219546deb805811854aca35 upstream.

GCSCRE0_EL1 and GCSPR_EL0 are live registers for EL0 on systems with GCS but are not saved and restored by cpu_do_suspend()/cpu_do_resume(). This means that the task that initiated suspend can return to userspace with UNKNOWN or incorrect values for GCSPR_EL0 and GCSCRE0_EL1 (many fields in GCSCRE0_EL1 reset to 0). This will in turn lead to ongoing corruption, including not restoring mode until a task with a different GCS mode is run. Fix this by saving and restoring the values over suspend.

This increases the size of struct cpu_suspend_ctx by 16 bytes.

Fixes 5d8b172e7005 ("arm64: Add Kconfig for Guarded Control Stack (GCS)")
---
 arch/arm64/include/asm/suspend.h |    2 +-
 arch/arm64/mm/proc.S             |   12 ++++++++++++
 2 files changed, 13 insertions(+), 1 deletion(-)
arch/arm64/include/asm/suspend.h +1 -1
@@ -2,7 +2,7 @@
 #ifndef __ASM_SUSPEND_H
 #define __ASM_SUSPEND_H
 
-#define NR_CTX_REGS 16
+#define NR_CTX_REGS 18
 #define NR_CALLEE_SAVED_REGS 12
 
 /*
arch/arm64/mm/proc.S +12 -0
@@ -122,6 +122,12 @@ alternative_if ARM64_HAS_S1POE
 	mrs	x2, REG_POR_EL0
 	str	x2, [x0, #120]
 alternative_else_nop_endif
+alternative_if ARM64_HAS_GCS
+	mrs	x2, REG_GCSPR_EL0
+	str	x2, [x0, #128]
+	mrs	x2, REG_GCSCRE0_EL1
+	str	x2, [x0, #136]
+alternative_else_nop_endif
 	ret
 SYM_FUNC_END(cpu_do_suspend)
 
@@ -168,6 +174,12 @@ alternative_if ARM64_HAS_S1POE
 	ldr	x2, [x0, #120]
 	msr	REG_POR_EL0, x2
 alternative_else_nop_endif
+alternative_if ARM64_HAS_GCS
+	ldr	x2, [x0, #128]
+	msr	REG_GCSPR_EL0, x2
+	ldr	x2, [x0, #136]
+	msr	REG_GCSCRE0_EL1, x2
+alternative_else_nop_endif
 
 	msr	sctlr_el1, x12
 	set_this_cpu_offset x13
author maintainer
#714 lore raw

PATCH 713/1005 arm64: suspend: Only track cpuidle context for idle tasks

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Uladzislau Zhauniarovich <[email protected]>

commit ad3fc05c7e65009355effeea06aa629a687acef2 upstream.

Commit 19235e472798 ("cpuidle, arm64: Fix the ARM64 cpuidle logic") moved the calls to ct_cpuidle_enter() and ct_cpuidle_exit() into cpu_suspend() so that arm64 cpuidle could keep RCU watching longer and manage context tracking internally. However, cpu_suspend() is called not only by cpuidle via psci_cpu_suspend_enter() (which runs in the context of the idle task), but also during system suspend via psci_system_suspend_enter() (which runs in the context of the task initiating suspend, such as a process writing to /sys/power/state).

When entering system suspend, current is a non-idle task. Calling ct_cpuidle_enter() invokes ct_kernel_exit() from kernel space (!user) on a non-idle task. With CONFIG_RCU_EQS_DEBUG enabled, this violates context tracking invariants and triggers a warning:

WARNING: kernel/context_tracking.c:120 at ct_kernel_exit+0x1b4/0x1f4
kernel/context_tracking.c:118
Call trace:
 ct_kernel_exit+0x1b4/0x1f4 kernel/context_tracking.c:118
 ct_idle_enter+0x20/0x34 kernel/context_tracking.c:299
 ct_cpuidle_enter include/linux/cpuidle.h:134 [inline]
 cpu_suspend+0x264/0x474 arch/arm64/kernel/suspend.c:136
 psci_system_suspend_enter+0x4c/0x80 drivers/firmware/psci/psci.c:544
 suspend_enter kernel/power/suspend.c:468 [inline]
 suspend_devices_and_enter+0x88c/0xd0c kernel/power/suspend.c:533
 enter_state kernel/power/suspend.c:618 [inline]
 pm_suspend+0x498/0x698 kernel/power/suspend.c:644
 state_store+0x14c/0x1fc kernel/power/main.c:819
 kobj_attr_store+0x6c/0x90 lib/kobject.c:842
 sysfs_kf_write+0xe0/0x108 fs/sysfs/file.c:145
 kernfs_fop_write_iter+0x260/0x3b8 fs/kernfs/file.c:345
 vfs_write+0x51c/0xa0c fs/read_write.c:687
 ksys_write+0x12c/0x228 fs/read_write.c:739

A corresponding warning is subsequently triggered in ct_kernel_enter() via ct_cpuidle_exit() upon resume.

Fix this by checking is_idle_task(current) in cpu_suspend() and only invoking ct_cpuidle_enter() and ct_cpuidle_exit() when executing in the context of an idle task.

---
 arch/arm64/kernel/suspend.c |   11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
arch/arm64/kernel/suspend.c +8 -3
@@ -5,6 +5,7 @@
 #include <linux/uaccess.h>
 #include <linux/pgtable.h>
 #include <linux/cpuidle.h>
+#include <linux/sched.h>
 #include <asm/alternative.h>
 #include <asm/cacheflush.h>
 #include <asm/cpufeature.h>
@@ -99,6 +100,7 @@ int cpu_suspend(unsigned long arg, int (
 	int ret = 0;
 	unsigned long flags;
 	struct sleep_stack_data state;
+	bool idle = is_idle_task(current);
 
 	/*
 	 * Some portions of CPU state (e.g. PSTATE.{PAN,DIT}) are initialized
@@ -133,7 +135,8 @@ int cpu_suspend(unsigned long arg, int (
 	 */
 	pause_graph_tracing();
 
-	ct_cpuidle_enter();
+	if (idle)
+		ct_cpuidle_enter();
 
 	if (__cpu_suspend_enter(&state)) {
 		/* Call the suspend finisher */
@@ -149,9 +152,11 @@ int cpu_suspend(unsigned long arg, int (
 		if (!ret)
 			ret = -EOPNOTSUPP;
 
-		ct_cpuidle_exit();
+		if (idle)
+			ct_cpuidle_exit();
 	} else {
-		ct_cpuidle_exit();
+		if (idle)
+			ct_cpuidle_exit();
 		__cpu_suspend_exit();
 	}
 
author maintainer
#715 lore raw

PATCH 714/1005 cpufreq: acpi-cpufreq: fix P-state index mismatch in extract_io()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Li RongQing <[email protected]>

commit 6bc092a0fc4d331a4adbbb664078af149c580834 upstream.

When policy->freq_table is built in acpi_cpufreq_cpu_init(), entries that are not lower in frequency than the previous one are skipped. For each remaining entry, freq_table[].driver_data stores the original ACPI P-state index, so the index space of freq_table no longer matches perf->states[].

extract_io() currently walks perf->states[] with index i and uses the same i to index policy->freq_table[i]. When duplicate frequencies exist, this can associate a P-state status with the frequency of a different P-state. It can also access an invalid or sentinel entry in freq_table when the number of entries in perf->states[] is greater than the number of entries remaining in the frequency table.

extract_io() is used on ACPI_ADR_SPACE_SYSTEM_IO platforms by the frequency verification path, which is enabled by the acpi_pstate_strict module parameter. With the mismatched lookup, check_freqs() can fail to match the frequency of the P-state that drv_write() has already programmed. It then sleeps through all 100 iterations - at least ~1 ms of usleep_range() plus 100 cross-CPU calls and I/O port reads, all with policy->rwsem held, and .target_index() returns -EAGAIN, leaving perf->state at its previous value while the hardware is running at the newly requested P-state.

The cpufreq core consequently keeps policy->cur at the old frequency. Since __cpufreq_driver_target() returns early when the requested frequency equals policy->cur, the driver is not called again for that frequency and the control register is not rewritten. The hardware can therefore remain at a frequency that differs from the frequency known to the cpufreq core.

Fix this by iterating over policy->freq_table and using pos->driver_data as the original ACPI P-state index when accessing perf->states[], as extract_msr() already does.

Fixes fe27cb358835 ("[CPUFREQ][2/8] acpi: reorganize code to make MSR support addition easier")
Cc All applicable <[email protected]>
---
 drivers/cpufreq/acpi-cpufreq.c |    9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
drivers/cpufreq/acpi-cpufreq.c +4 -5
@@ -197,14 +197,13 @@ static unsigned extract_io(struct cpufre
 {
 	struct acpi_cpufreq_data *data = policy->driver_data;
 	struct acpi_processor_performance *perf;
-	int i;
+	struct cpufreq_frequency_table *pos;
 
 	perf = to_perf_data(data);
 
-	for (i = 0; i < perf->state_count; i++) {
-		if (value == perf->states[i].status)
-			return policy->freq_table[i].frequency;
-	}
+	cpufreq_for_each_entry(pos, policy->freq_table)
+		if (value == perf->states[pos->driver_data].status)
+			return pos->frequency;
 	return 0;
 }
 
author maintainer
#716 lore raw

PATCH 715/1005 cpufreq: Improve suspend-resume synchronization

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rafael J. Wysocki <[email protected]>

commit eee2a44e4e2b41c0699919a550d41cc38daa4f42 upstream.

The suspend-resume synchronization in the cpufreq core is not perfect because the global cpufreq_suspended variable is set at the end of cpufreq_suspend() after stopping governors for all of the active policies, so the governor .limits() callback may run via cpufreq_governor_limits() after stopping the governor and before setting cpufreq_suspended which is questionable. Likewise, the governor .limits() callback may run between clearing cpufreq_suspended in cpufreq_resume() and starting the governor.

Address this by adding a per-policy "suspended" flag that is always read under the policy rwsem and is updated under it when the governor is stopped in cpufreq_suspend() and when the governor is restarted in cpufreq_resume().

Also make cpufreq_resume() use the cpus_read_lock guard to reflect what is done in cpufreq_suspend() and call cpufreq_exit_governor() for policies that were suspended during a system suspend transition and are inactive during the subsequent system resume (to avoid leaking an inactive policy with a stopped governor that has not exited yet).

Fixes 8e30444e1530 ("cpufreq: fix cpufreq suspend/resume for intel_pstate")
Fixes b1b12babe3b7 ("cpufreq: update 'cpufreq_suspended' after stopping governors")
Cc All applicable <[email protected]>
---
 drivers/cpufreq/cpufreq.c |   86 +++++++++++++++++++++++++++++++++-------------
 include/linux/cpufreq.h   |    3 +
 2 files changed, 66 insertions(+), 23 deletions(-)
drivers/cpufreq/cpufreq.c +63 -23
@@ -35,6 +35,9 @@
 static LIST_HEAD(cpufreq_policy_list);
 
 /* Macros to iterate over CPU policies */
+#define for_each_policy(__policy)	\
+	list_for_each_entry(__policy, &cpufreq_policy_list, policy_list)
+
 #define for_each_suitable_policy(__policy, __active)			 \
 	list_for_each_entry(__policy, &cpufreq_policy_list, policy_list) \
 		if ((__active) == !policy_is_inactive(__policy))
@@ -1960,6 +1963,14 @@ int cpufreq_generic_suspend(struct cpufr
 }
 EXPORT_SYMBOL(cpufreq_generic_suspend);
 
+static void cpufreq_suspend_policy(struct cpufreq_policy *policy)
+{
+	guard(cpufreq_policy_write)(policy);
+
+	cpufreq_stop_governor(policy);
+	policy->suspended = true;
+}
+
 /**
  * cpufreq_suspend() - Suspend CPUFreq governors.
  *
@@ -1982,11 +1993,8 @@ void cpufreq_suspend(void)
 	pr_debug("%s: Suspending Governors\n", __func__);
 
 	for_each_active_policy(policy) {
-		if (has_target()) {
-			scoped_guard(cpufreq_policy_write, policy) {
-				cpufreq_stop_governor(policy);
-			}
-		}
+		if (has_target())
+			cpufreq_suspend_policy(policy);
 
 		if (cpufreq_driver->suspend && cpufreq_driver->suspend(policy))
 			pr_err("%s: Failed to suspend driver: %s\n", __func__,
@@ -1998,6 +2006,32 @@ suspend:
 	cpus_read_unlock();
 }
 
+static void cpufreq_resume_policy(struct cpufreq_policy *policy, bool start)
+{
+	guard(cpufreq_policy_write)(policy);
+
+	if (!policy->suspended)
+		return;
+
+	policy->suspended = false;
+
+	if (policy_is_inactive(policy)) {
+		/*
+		 * The policy was active when it was suspended, so its governor
+		 * is still there.  Let the governor go.
+		 */
+		cpufreq_exit_governor(policy);
+		return;
+	}
+
+	if (!start)
+		return;
+
+	if (cpufreq_start_governor(policy))
+		pr_err("%s: Failed to start governor for CPU%u's policy\n",
+		       __func__, policy->cpu);
+}
+
 /**
  * cpufreq_resume() - Resume CPUFreq governors.
  *
@@ -2007,11 +2041,12 @@ suspend:
 void cpufreq_resume(void)
 {
 	struct cpufreq_policy *policy;
-	int ret;
 
 	if (!cpufreq_driver)
 		return;
 
+	guard(cpus_read_lock)();
+
 	if (unlikely(!cpufreq_suspended))
 		return;
 
@@ -2022,19 +2057,18 @@ void cpufreq_resume(void)
 
 	pr_debug("%s: Resuming Governors\n", __func__);
 
-	for_each_active_policy(policy) {
-		if (cpufreq_driver->resume && cpufreq_driver->resume(policy)) {
-			pr_err("%s: Failed to resume driver: %s\n", __func__,
-				cpufreq_driver->name);
-		} else if (has_target()) {
-			scoped_guard(cpufreq_policy_write, policy) {
-				ret = cpufreq_start_governor(policy);
-			}
+	for_each_policy(policy) {
+		int ret = 0;
 
+		if (cpufreq_driver->resume && !policy_is_inactive(policy)) {
+			ret = cpufreq_driver->resume(policy);
 			if (ret)
-				pr_err("%s: Failed to start governor for CPU%u's policy\n",
-				       __func__, policy->cpu);
+				pr_err("%s: Failed to resume driver: %s\n", __func__,
+				       cpufreq_driver->name);
 		}
+
+		if (has_target())
+			cpufreq_resume_policy(policy, ret == 0);
 	}
 }
 
@@ -2416,12 +2450,17 @@ __weak struct cpufreq_governor *cpufreq_
 	return NULL;
 }
 
+static bool cpufreq_is_suspended(struct cpufreq_policy *policy)
+{
+	return cpufreq_suspended || policy->suspended;
+}
+
 static int cpufreq_init_governor(struct cpufreq_policy *policy)
 {
 	int ret;
 
-	/* Don't start any governor operations if we are entering suspend */
-	if (cpufreq_suspended)
+	/* Don't start any governor operations for suspended policies. */
+	if (cpufreq_is_suspended(policy))
 		return 0;
 	/*
 	 * Governor might not be initiated here if ACPI _PPC changed
@@ -2464,7 +2503,7 @@ static int cpufreq_init_governor(struct
 
 static void cpufreq_exit_governor(struct cpufreq_policy *policy)
 {
-	if (cpufreq_suspended || !policy->governor)
+	if (cpufreq_is_suspended(policy) || !policy->governor)
 		return;
 
 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
@@ -2479,7 +2518,7 @@ int cpufreq_start_governor(struct cpufre
 {
 	int ret;
 
-	if (cpufreq_suspended)
+	if (cpufreq_is_suspended(policy))
 		return 0;
 
 	if (!policy->governor)
@@ -2503,7 +2542,7 @@ int cpufreq_start_governor(struct cpufre
 
 void cpufreq_stop_governor(struct cpufreq_policy *policy)
 {
-	if (cpufreq_suspended || !policy->governor)
+	if (cpufreq_is_suspended(policy) || !policy->governor)
 		return;
 
 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
@@ -2514,7 +2553,7 @@ void cpufreq_stop_governor(struct cpufre
 
 static void cpufreq_governor_limits(struct cpufreq_policy *policy)
 {
-	if (cpufreq_suspended || !policy->governor)
+	if (cpufreq_is_suspended(policy) || !policy->governor)
 		return;
 
 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
@@ -2751,7 +2790,8 @@ static void cpufreq_policy_refresh(struc
 	 * -> ask driver for current freq and notify governors about a change
 	 */
 	if (cpufreq_driver->get && has_target() &&
-	    (cpufreq_suspended || WARN_ON(!cpufreq_verify_current_freq(policy, false))))
+	    (cpufreq_is_suspended(policy) ||
+	     WARN_ON(!cpufreq_verify_current_freq(policy, false))))
 		return;
 
 	refresh_frequency_limits(policy);
include/linux/cpufreq.h +3 -0
@@ -149,6 +149,9 @@ struct cpufreq_policy {
 	/* Pending policy->min/max update for the driver */
 	bool			update_limits;
 
+	/* The policy has been suspended. */
+	bool			suspended;
+
 	 /* Cached frequency lookup from cpufreq_driver_resolve_freq. */
 	unsigned int cached_target_freq;
 	unsigned int cached_resolved_idx;
author maintainer
#717 lore raw

PATCH 716/1005 cpufreq: intel_pstate: Clear last written P-state value on suspend

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rafael J. Wysocki <[email protected]>

commit 02e77af824d5be3a94fdd885835a352f90d24c5c upstream.

Preserving cpu->pstate.current_pstate across system suspend-resume cycles, when running in the passive mode with HWP disabled, is a mistake because its value from before system suspend may become stale after the subsequent system resume and in some cases it prevents MSR_IA32_PERF_CTL from being updated properly after system resume [1].

Address this by clearing cpu->pstate.current_pstate after the governor has been stopped during system suspend.

Fixes 001c76f05b01 ("cpufreq: intel_pstate: Generic governors support")
Fixes 4adcf2e5829f ("cpufreq: intel_pstate: Add ->offline and ->online callbacks")
Cc All applicable <[email protected]> # 342d3a73c5db cpufreq: Force passing target frequency to driver during resume
---
 drivers/cpufreq/intel_pstate.c |   14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/cpufreq/intel_pstate.c +13 -1
@@ -3389,10 +3389,11 @@ static void intel_cpufreq_cpu_exit(struc
 
 static int intel_cpufreq_suspend(struct cpufreq_policy *policy)
 {
+	struct cpudata *cpu = all_cpu_data[policy->cpu];
+
 	intel_pstate_suspend(policy);
 
 	if (hwp_active) {
-		struct cpudata *cpu = all_cpu_data[policy->cpu];
 		u64 value = READ_ONCE(cpu->hwp_req_cached);
 
 		/*
@@ -3403,6 +3404,17 @@ static int intel_cpufreq_suspend(struct
 		value &= ~HWP_DESIRED_PERF(~0L);
 		wrmsrq_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value);
 		WRITE_ONCE(cpu->hwp_req_cached, value);
+	} else {
+		/*
+		 * Invalidate the cached P-state value that may be stale when
+		 * the governor is started again during resume and may prevent
+		 * MSR_IA32_PERF_CTL from being updated.
+		 *
+		 * This does not require synchronization because the core
+		 * prevents frequency updates for suspended policies from
+		 * occurring.
+		 */
+		cpu->pstate.current_pstate = 0;
 	}
 
 	return 0;
author maintainer
#718 lore raw

PATCH 717/1005 cpufreq: intel_pstate: Use rdmsrq_safe() to read MSR_MISC_PWR_MGMT

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Li Zhaoxin <[email protected]>

commit 2c0e6f2858d235c99f7ba4621bd176cd67226f00 upstream.

Commit ed7cad0504e3 ("cpufreq: intel_pstate: Relocate platform preference check") moved the intel_pstate_platform_pwr_mgmt_exists() call to the beginning of intel_pstate_init(), right after the vendor check, so it now runs before "no_load" (intel_pstate=disable) and the other checks.

MSR_MISC_PWR_MGMT is model-specific and KVM does not emulate it. In a KVM guest using a CPU model listed in intel_pstate_cpu_oob_ids[] (for example "-cpu host" on Emerald Rapids), reading it raises #GP and the unchecked rdmsrq() emits a warning with a call trace on every boot, even with intel_pstate=disable:

unchecked MSR access error: RDMSR from 0x1aa at rIP: 0xffffffffa4009342 (native_read_msr+0x2/0x50)

  Call Trace:
   <TASK>
   intel_pstate_platform_pwr_mgmt_exists+0x3b/0x220
   intel_pstate_init+0x1e/0x500
   do_one_initcall+0x59/0x350
   ...

Before that commit, such guests typically returned from intel_pstate_init() earlier, either because of intel_pstate=disable or because intel_pstate_msrs_not_valid() failed on the zero ratios that KVM reports in MSR_PLATFORM_INFO by default, so the MSR was not read.

Use rdmsrq_safe() and treat a failing read as "no OOB mode". The exception fixup already zeroes the result of a failed unchecked read, so apart from the warning going away there is no functional change.

Fixes ed7cad0504e3 ("cpufreq: intel_pstate: Relocate platform preference check")
Cc All applicable <[email protected]>
---
 drivers/cpufreq/intel_pstate.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/cpufreq/intel_pstate.c +2 -2
@@ -3661,12 +3661,12 @@ static struct acpi_platform_list plat_in
 static bool __init intel_pstate_platform_pwr_mgmt_exists(void)
 {
 	const struct x86_cpu_id *id;
-	u64 misc_pwr;
+	u64 misc_pwr = 0;
 	int idx;
 
 	id = x86_match_cpu(intel_pstate_cpu_oob_ids);
 	if (id) {
-		rdmsrq(MSR_MISC_PWR_MGMT, misc_pwr);
+		rdmsrq_safe(MSR_MISC_PWR_MGMT, &misc_pwr);
 		if (misc_pwr & BITMASK_OOB) {
 			pr_debug("Bit 8 or 18 in the MISC_PWR_MGMT MSR set\n");
 			pr_debug("P states are controlled in Out of Band mode by the firmware/hardware\n");
author maintainer
#719 lore raw

PATCH 718/1005 cpufreq: Force passing target frequency to driver during resume

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rafael J. Wysocki <[email protected]>

commit 342d3a73c5dbc2f1cd0c5142e2d11bda4dc54cd7 upstream.

The policy->cur value preserved across a system suspend-resume cycle may become stale in some cases and it may prevent the CPU performance scaling logic from being updated due to the target_freq == policy->cur check in __cpufreq_driver_target() [1].

To address this, adjust the existing mechanism to force the invocation of the driver .target() callback in __cpufreq_driver_target() and make cpufreq_resume_policy() use it.

This involves renaming update_limits in struct cpufreq_policy to force_target and moving the driver CPUFREQ_NEED_UPDATE_LIMITS flag check from __cpufreq_driver_target() to cpufreq_set_policy(), where it is used as a condition for setting policy->force_target.

In cpufreq_resume_policy(), policy->force_target is set for drivers that implement the .target() callback, but don't implement the .get() one, which is the case when the driver callback needs to run if policy->cur becomes stale while suspended.

---
 drivers/cpufreq/cpufreq.c |   33 +++++++++++++++++++++------------
 include/linux/cpufreq.h   |    4 ++--
 2 files changed, 23 insertions(+), 14 deletions(-)
drivers/cpufreq/cpufreq.c +21 -12
@@ -2027,6 +2027,15 @@ static void cpufreq_resume_policy(struct
 	if (!start)
 		return;
 
+	/*
+	 * Force executing the driver .target() callback, if present, in the
+	 * next invocation of __cpufreq_driver_target() in case policy->cur has
+	 * become stale while suspended, but do it only for drivers without a
+	 * .get() callback for which cpufreq_verify_current_freq() is a NOP.
+	 */
+	if (cpufreq_driver->target && !cpufreq_driver->get)
+		policy->force_target = true;
+
 	if (cpufreq_start_governor(policy))
 		pr_err("%s: Failed to start governor for CPU%u's policy\n",
 		       __func__, policy->cpu);
@@ -2404,17 +2413,14 @@ int __cpufreq_driver_target(struct cpufr
 		policy->cpu, policy->cur, target_freq, old_target_freq, relation);
 
 	/*
-	 * This might look like a redundant call as we are checking it again
-	 * after finding index. But it is left intentionally for cases where
-	 * exactly same freq is called again and so we can save on few function
-	 * calls.
+	 * Unless invoking the target callback is forced, skip the update if the
+	 * frequency is not really changing.
 	 */
-	if (target_freq == policy->cur) {
-		if (!(cpufreq_driver->flags & CPUFREQ_NEED_UPDATE_LIMITS) ||
-		    !policy->update_limits)
-			return 0;
-
-		policy->update_limits = false;
+	if (policy->force_target) {
+		/* Avoid forcing the driver callback unnecessarily next time. */
+		policy->force_target = false;
+	} else if (target_freq == policy->cur) {
+		return 0;
 	}
 
 	if (cpufreq_driver->target) {
@@ -2673,6 +2679,7 @@ static int cpufreq_set_policy(struct cpu
 			      struct cpufreq_governor *new_gov,
 			      unsigned int new_pol)
 {
+	bool need_update_limits = cpufreq_driver->flags & CPUFREQ_NEED_UPDATE_LIMITS;
 	struct cpufreq_policy_data new_data;
 	struct cpufreq_governor *old_gov;
 	unsigned int freq;
@@ -2712,7 +2719,8 @@ static int cpufreq_set_policy(struct cpu
 			      CPUFREQ_RELATION_H);
 	if (freq != policy->max) {
 		WRITE_ONCE(policy->max, freq);
-		policy->update_limits = true;
+		if (need_update_limits)
+			policy->force_target = true;
 	}
 
 	freq = __resolve_freq(policy, new_data.min, new_data.min, new_data.max,
@@ -2720,7 +2728,8 @@ static int cpufreq_set_policy(struct cpu
 	freq = min(freq, policy->max);
 	if (freq != policy->min) {
 		WRITE_ONCE(policy->min, freq);
-		policy->update_limits = true;
+		if (need_update_limits)
+			policy->force_target = true;
 	}
 
 	trace_cpu_frequency_limits(policy);
include/linux/cpufreq.h +2 -2
@@ -146,8 +146,8 @@ struct cpufreq_policy {
 	/* Per policy boost supported flag. */
 	bool			boost_supported;
 
-	/* Pending policy->min/max update for the driver */
-	bool			update_limits;
+	/* Force passing target frequency to the driver. */
+	bool			force_target;
 
 	/* The policy has been suspended. */
 	bool			suspended;
author maintainer
#720 lore raw

PATCH 719/1005 cpufreq: Cache post-resolution target frequency in __resolve_freq()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rafael J. Wysocki <[email protected]>

commit 166207cac45191637c47a457a5c16ca6b6773a16 upstream.

get_next_freq() in the schedutil governor returns the resolved frequency from cpufreq_driver_resolve_freq(), and that resolved value is then passed to cpufreq_driver_fast_switch(). The only reader of cached_target_freq, acpi_cpufreq_fast_switch(), compares it with the post-resolution target frequency, but it holds the pre-resolution clamped frequency, so any request that falls between table entries misses the cache and falls back to a table scan.

Address this by making __resolve_freq() store the post-resolution frequency in cached_target_freq.

---
 drivers/cpufreq/cpufreq.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/cpufreq/cpufreq.c +2 -2
@@ -488,8 +488,8 @@ static unsigned int __resolve_freq(struc
 
 	idx = cpufreq_frequency_table_target(policy, target_freq, min, max, relation);
 	policy->cached_resolved_idx = idx;
-	policy->cached_target_freq = target_freq;
-	return policy->freq_table[idx].frequency;
+	policy->cached_target_freq = policy->freq_table[idx].frequency;
+	return policy->cached_target_freq;
 }
 
 /**
author maintainer
#721 lore raw

PATCH 720/1005 cpufreq: Fix updates of cached resolved frequency and index

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rafael J. Wysocki <[email protected]>

commit 75120f31aed010c326b28d7c80d22314df34d9a8 upstream.

The cached resolved frequency and index, cached_target_freq and cached_resolved_idx, respectively, may be updated concurrently if cpufreq_driver_resolve_freq() is called by the schedutil governor while cpufreq_set_policy() is running for the same policy. Those concurrent updates are not synchronized in any way and the values written by cpufreq_set_policy(), if it wins the race, may confuse drivers using those policy fields [1].

To address this, use the observation that the only place where cached_target_freq and cached_resolved_idx need to be updated is cpufreq_driver_resolve_freq() because the only legitimate users of them are .fast_switch() driver callbacks. Although cached_resolved_idx is also used in __cpufreq_driver_target(), that is in fact unnecessary and it is better to use a local variable for storing the frequency table index in that function.

Accordingly, rearrange __resolve_freq() and its callers so that cached_target_freq and cached_resolved_idx are only updated in cpufreq_driver_resolve_freq().

The cached_target_freq initialization in cpufreq_set_policy() is still needed, but move it after stopping the old governor and before starting the new one to avoid racing with cpufreq_driver_resolve_freq().

Fixes f9ccdec24d91 ("cpufreq: Reuse cpufreq_driver_resolve_freq() in __cpufreq_driver_target()")
Fixes 151717690694 ("cpufreq: Make policy min/max hard requirements")
Cc All applicable <[email protected]> # 342d3a73c5db cpufreq: Force passing target frequency to driver during resume
Cc All applicable <[email protected]> # 166207cac451 cpufreq: Cache post-resolution target frequency in __resolve_freq()
---
 drivers/cpufreq/cpufreq.c |   31 ++++++++++++++++++++-----------
 1 file changed, 20 insertions(+), 11 deletions(-)
drivers/cpufreq/cpufreq.c +20 -11
@@ -477,7 +477,7 @@ EXPORT_SYMBOL_GPL(cpufreq_disable_fast_s
 static unsigned int __resolve_freq(struct cpufreq_policy *policy,
 				   unsigned int target_freq,
 				   unsigned int min, unsigned int max,
-				   unsigned int relation)
+				   unsigned int relation, unsigned int *idx_p)
 {
 	unsigned int idx;
 
@@ -487,9 +487,10 @@ static unsigned int __resolve_freq(struc
 		return target_freq;
 
 	idx = cpufreq_frequency_table_target(policy, target_freq, min, max, relation);
-	policy->cached_resolved_idx = idx;
-	policy->cached_target_freq = policy->freq_table[idx].frequency;
-	return policy->cached_target_freq;
+	if (idx_p)
+		*idx_p = idx;
+
+	return policy->freq_table[idx].frequency;
 }
 
 /**
@@ -520,7 +521,10 @@ unsigned int cpufreq_driver_resolve_freq
 	if (unlikely(min > max))
 		min = max;
 
-	return __resolve_freq(policy, target_freq, min, max, CPUFREQ_RELATION_LE);
+	policy->cached_target_freq = __resolve_freq(policy, target_freq, min, max,
+						    CPUFREQ_RELATION_LE,
+						    &policy->cached_resolved_idx);
+	return policy->cached_target_freq;
 }
 EXPORT_SYMBOL_GPL(cpufreq_driver_resolve_freq);
 
@@ -2402,12 +2406,13 @@ int __cpufreq_driver_target(struct cpufr
 			    unsigned int relation)
 {
 	unsigned int old_target_freq = target_freq;
+	unsigned int idx = 0;
 
 	if (cpufreq_disabled())
 		return -ENODEV;
 
 	target_freq = __resolve_freq(policy, target_freq, policy->min,
-				     policy->max, relation);
+				     policy->max, relation, &idx);
 
 	pr_debug("CPU %u: cur %u kHz -> target %u kHz (req %u kHz, rel %u)\n",
 		policy->cpu, policy->cur, target_freq, old_target_freq, relation);
@@ -2437,7 +2442,7 @@ int __cpufreq_driver_target(struct cpufr
 	if (!cpufreq_driver->target_index)
 		return -EINVAL;
 
-	return __target_index(policy, policy->cached_resolved_idx);
+	return __target_index(policy, idx);
 }
 EXPORT_SYMBOL_GPL(__cpufreq_driver_target);
 
@@ -2716,7 +2721,7 @@ static int cpufreq_set_policy(struct cpu
 	 * concurrently by cpufreq_driver_resolve_freq() during the update.
 	 */
 	freq = __resolve_freq(policy, new_data.max, new_data.min, new_data.max,
-			      CPUFREQ_RELATION_H);
+			      CPUFREQ_RELATION_H, NULL);
 	if (freq != policy->max) {
 		WRITE_ONCE(policy->max, freq);
 		if (need_update_limits)
@@ -2724,7 +2729,7 @@ static int cpufreq_set_policy(struct cpu
 	}
 
 	freq = __resolve_freq(policy, new_data.min, new_data.min, new_data.max,
-			      CPUFREQ_RELATION_L);
+			      CPUFREQ_RELATION_L, NULL);
 	freq = min(freq, policy->max);
 	if (freq != policy->min) {
 		WRITE_ONCE(policy->min, freq);
@@ -2736,8 +2741,6 @@ static int cpufreq_set_policy(struct cpu
 
 	cpufreq_update_pressure(policy);
 
-	policy->cached_target_freq = UINT_MAX;
-
 	pr_debug("new min and max freqs are %u - %u kHz\n",
 		 policy->min, policy->max);
 
@@ -2763,6 +2766,12 @@ static int cpufreq_set_policy(struct cpu
 		cpufreq_exit_governor(policy);
 	}
 
+	/*
+	 * Initialize cached_target_freq while no governor is running to avoid
+	 * racing with cpufreq_driver_resolve_freq(), which updates it.
+	 */
+	policy->cached_target_freq = UINT_MAX;
+
 	/* start new governor */
 	policy->governor = new_gov;
 	ret = cpufreq_init_governor(policy);
author maintainer
#722 lore raw

PATCH 721/1005 software node: only let the owner release a managed node

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Bartosz Golaszewski <[email protected]>

commit f8623ce596492d2e96ca57eeec992938d3d79f00 upstream.

device_create_managed_software_node() creates a node whose lifetime is tied to the device it was created for. software_node_notify_remove() is called for every device that has the node as its fwnode (primary OR secondary) and, if the node is managed, unconditionally detaches it from that device and drops the creation reference.

This breaks when the node is shared with another device. Example: the i2c-designware copies the parent's fwnode to the adapter's struct device. When the adapter is deleted, it releases the reference that belongs to the owner and the latter ends up with a dangling pointer.

Record the device's "manager" and only perform the actual release when notify is called for that "owner" device.

Note that it was never the intention that managed software nodes would be shared, but descendants reusing ancestor firmware nodes is not uncommon and such use is hard to predict when allocating software nodes.

[ johan: drop temporary variable; skip clearing owner field;
mention reuse not intended in commit message ]

---
 drivers/base/swnode.c |    7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/base/swnode.c +4 -3
@@ -29,6 +29,8 @@ struct swnode {
 	struct fwnode_handle fwnode;
 	const struct software_node *node;
 	int id;
+	/* Device the managed node's lifetime is tied to. */
+	struct device *owner;
 
 	/* hierarchy */
 	struct ida child_ids;
@@ -37,7 +39,6 @@ struct swnode {
 	struct swnode *parent;
 
 	unsigned int allocated:1;
-	unsigned int managed:1;
 };
 
 static DEFINE_IDA(swnode_root_ids);
@@ -1145,7 +1146,7 @@ int device_create_managed_software_node(
 	if (IS_ERR(fwnode))
 		return PTR_ERR(fwnode);
 
-	to_swnode(fwnode)->managed = true;
+	to_swnode(fwnode)->owner = dev;
 	set_secondary_fwnode(dev, fwnode);
 
 	if (device_is_registered(dev))
@@ -1208,7 +1209,7 @@ void software_node_notify_remove(struct
 
 	swnode_put(swnode);
 
-	if (swnode->managed) {
+	if (swnode->owner == dev) {
 		set_secondary_fwnode(dev, NULL);
 		swnode_put(swnode);
 	}
author maintainer
#723 lore raw

PATCH 722/1005 SUNRPC: Fix TCP-with-TLS transport class identification

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Avi Weiss <[email protected]>

commit 0502c7e7f171a8c9c892bdef89e6aa6f44d7b2a3 upstream.

xs_setup_tcp_tls() assigns the ordinary TCP transport class to a TCP-with-TLS transport. When rpc_clnt_add_xprt() is called with an unspecified transport type, it inherits the class identifier and can create an unencrypted TCP transport.

Looks like a copy-paste error from the commit 3 years ago.

NFSv4 trunk discovery uses an unspecified transport type when adding server-advertised addresses. If the additional transport passes server-identity validation, it can be admitted to the client's transport switch.

An isolated loopback test reproduced plaintext application RPC transmission for TLS- and mTLS-configured clients, including an unpinned TLS-client RPC that selected the added transport.

Assign the TCP-with-TLS class instead. With the fix, the plaintext-only test peer receives TLS negotiation probes but no application payloads.

Fixes 75eb6af7acdf ("SUNRPC: Add a TCP-with-TLS RPC transport class")
---
 net/sunrpc/xprtsock.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/sunrpc/xprtsock.c +1 -1
@@ -3525,7 +3525,7 @@ static struct rpc_xprt *xs_setup_tcp_tls
 	transport = container_of(xprt, struct sock_xprt, xprt);
 
 	xprt->prot = IPPROTO_TCP;
-	xprt->xprt_class = &xs_tcp_transport;
+	xprt->xprt_class = &xs_tcp_tls_transport;
 	xprt->max_payload = RPC_MAX_FRAGMENT_SIZE;
 
 	xprt->bind_timeout = XS_BIND_TO;
author maintainer
#724 lore raw

PATCH 723/1005 timekeeping: Read getboottime64() offsets under the sequence counter

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hungyu Lin <[email protected]>

commit 385b5ec1f31dd39297578eed42be74b07ae74017 upstream.

getboottime64() computes the wall-clock boot timestamp from offs_real minus offs_boot without checking tk_core.seq. A concurrent timekeeping update can leave the reader with an inconsistent pair of offsets or, on 32-bit systems, a torn 64-bit offset, producing an incorrect boot timestamp.

Read both offsets under tk_core.seq and retry if an update overlaps the sample. Convert the resulting local value to a timespec64 afterward.

---
 kernel/time/timekeeping.c |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
kernel/time/timekeeping.c +7 -1
@@ -2698,7 +2698,13 @@ void update_wall_time(void)
 void getboottime64(struct timespec64 *ts)
 {
 	struct timekeeper *tk = &tk_core.timekeeper;
-	ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
+	unsigned int seq;
+	ktime_t t;
+
+	do {
+		seq = read_seqcount_begin(&tk_core.seq);
+		t = ktime_sub(tk->offs_real, tk->offs_boot);
+	} while (read_seqcount_retry(&tk_core.seq, seq));
 
 	*ts = ktime_to_timespec64(t);
 }
author maintainer
#725 lore raw

PATCH 724/1005 timekeeping: Reject cross timestamps for invalid AUX clocks

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Avi Weiss <[email protected]>

commit 67f1969e29b692ab3cfcc97ba175b9109212de00 upstream.

get_device_system_crosststamp() accepts AUX clock IDs even when the corresponding timekeeper is disabled. A never-enabled AUX timekeeper has no initialized clocksource, and a previously enabled one can retain stale timekeeping data.

Return -ENODEV before calling the device timestamp callback when the selected timekeeper is invalid.

Fixes 9aebde8af6fe ("timekeeping: Add support for AUX clock cross timestamping")
---
 kernel/time/timekeeping.c |    3 +++
 1 file changed, 3 insertions(+)
kernel/time/timekeeping.c +3 -0
@@ -1598,6 +1598,9 @@ int get_device_system_crosststamp(int (*
 
 	do {
 		seq = read_seqcount_begin(&tkd->seq);
+		if (!tk->clock_valid)
+			return -ENODEV;
+
 		/*
 		 * Try to synchronously capture device time and a system
 		 * counter value calling back into the device driver
author maintainer
#726 lore raw

PATCH 725/1005 timekeeping: Refresh auxiliary base before offset validation

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Avi Weiss <[email protected]>

commit c1b96ba87e3caaa701d6dba254e58db7cc3c99be upstream.

timekeeping_forward_now() can advance an auxiliary timekeeper across a second boundary without refreshing tkr_mono.base. The negative-time check in __timekeeping_inject_offset() then uses the stale base and rejects valid ADJ_SETOFFSET adjustments with -EINVAL.

Refresh the derived timekeeper data before calculating the current auxiliary time, as aux_clock_set() already does.

On 7.4-rc1, a valid negative adjustment fails at the first second rollover. The patched kernel accepts all 12 tested rollover adjustments and continues to reject invalid negative offsets.

Fixes 2c8aea59c206 ("timekeeping: Add auxiliary clock support to __timekeeping_inject_offset()")
---
 kernel/time/timekeeping.c |    1 +
 1 file changed, 1 insertion(+)
kernel/time/timekeeping.c +1 -0
@@ -1776,6 +1776,7 @@ static int __timekeeping_inject_offset(s
 		struct tk_read_base *tkr_mono = &tks->tkr_mono;
 		ktime_t now, offs;
 
+		tk_update_ktime_data(tks);
 		/* Get the current time */
 		now = ktime_add_ns(tkr_mono->base, timekeeping_get_ns(tkr_mono));
 		/* Add the relative offset change */
author maintainer
#727 lore raw

PATCH 726/1005 tpm: acpi: Fix memory leak at tpm_read_log_acpi() error path

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Takashi Iwai <[email protected]>

commit 03fcb358249dc715124b3616f814ea0ecc6ec36c upstream.

When devm_add_action() returns an error, tpm_read_log_acpi() clears log->bios_event_log unnecessarily to NULL before calling tpm_bios_log_free(), and it would lead to a memory leak of the allocated log buffer.

Fix it by simply jumping to the err.

---
 drivers/char/tpm/eventlog/acpi.c |    4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/char/tpm/eventlog/acpi.c +1 -3
@@ -167,10 +167,8 @@ int tpm_read_log_acpi(struct tpm_chip *c
 	}
 
 	ret = devm_add_action(&chip->dev, tpm_bios_log_free, log->bios_event_log);
-	if (ret) {
-		log->bios_event_log = NULL;
+	if (ret)
 		goto err;
-	}
 
 	return format;
 
author maintainer
#728 lore raw

PATCH 727/1005 tpm: Check return value of crypto_kpp_set_secret()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Eric Biggers <[email protected]>

commit 8cff8f1c89d33e55c9af82177b14f6f9f6a899fe upstream.

crypto_kpp_set_secret() can fail, for example if the kernel is booted with fips=1 and the broken-by-design FIPS RNG used for ECC private key generation doesn't feel like generating random bytes at the moment. Check for error, cancelling the TPM session creation rather than proceeding with a zero or uninitialized private key.

---
 drivers/char/tpm/tpm2-sessions.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm2-sessions.c +3 -1
@@ -527,7 +527,9 @@ static int tpm_buf_append_salt(struct tp
 	}
 	crypto_ecdh_encode_key(encoded_key, buf_len, &p);
 	/* this generates a random private key */
-	crypto_kpp_set_secret(kpp, encoded_key, buf_len);
+	rc = crypto_kpp_set_secret(kpp, encoded_key, buf_len);
+	if (rc)
+		goto err_free_kpp;
 
 	/* salt is now the public point of this private key */
 	req = kpp_request_alloc(kpp, GFP_KERNEL);
author maintainer
#729 lore raw

PATCH 728/1005 tpm: eventlog: check the payload size before reading tag events

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Guanglei Zhu <[email protected]>

commit 0a385f668ba77d29ae167c1668fd452418ebc9d6 upstream.

The EVENT_TAG branch of get_event_name() casts the event payload to struct tcpa_pc_event and reads from it:

	pc_event = (struct tcpa_pc_event *)event_entry;

	switch (do_endian_conversion(pc_event->event_id)) {
	...
		for (i = 0; i < 20; i++)
			d_len += sprintf(&data[2*i], "%02x",
					pc_event->event_data[i]);

The log iterators only verify that the event header plus the declared event_size stays within the log buffer; they do not require the payload of an EVENT_TAG entry to be large enough for the fields the branch reads. A truncated entry makes the branch read up to 20 bytes of event_data[] past the end of the entry, and, for the last entry in the log, past the end of the buffer itself.

The legacy PC Client spec defines the EV_EVENT_TAG payload as a TCPA_PC_EVENT - event_id, event_size and event-type-specific data - so a conformant entry carries the 8-byte header and the hash-type ids carry a full digest. The log itself, however, is an ACPI table the firmware leaves in memory: the TPM never measures the log, so the kernel cannot tell a conformant log from a corrupted one. The iterators already work on that assumption - they stop once the declared event_size runs past the buffer end - and the readers should apply the same rule to what they take off the payload.

Skip entries whose payload cannot even hold the event id, and skip the 20-byte digest dump when the payload cannot hold the full tcpa_pc_event header plus the digest, so the branch never reads beyond the entry it is formatting.

Fixes 55a82ab3181b ("[PATCH] tpm: add bios measurement log")
---
 drivers/char/tpm/eventlog/tpm1.c |    7 +++++++
 1 file changed, 7 insertions(+)
drivers/char/tpm/eventlog/tpm1.c +7 -0
@@ -178,6 +178,10 @@ static int get_event_name(char *dest, st
 		}
 		break;
 	case EVENT_TAG:
+		if (do_endian_conversion(event->event_size) <
+		    sizeof(pc_event->event_id))
+			break;
+
 		pc_event = (struct tcpa_pc_event *)event_entry;
 
 		/* ToDo Row data -> Base64 */
@@ -203,6 +207,9 @@ static int get_event_name(char *dest, st
 			name = tcpa_pc_event_id_strings[do_endian_conversion
 							(pc_event->event_id)];
 			n_len = strlen(name);
+			if (do_endian_conversion(event->event_size) <
+			    sizeof(struct tcpa_pc_event) + 20)
+				break;
 			for (i = 0; i < 20; i++)
 				d_len += sprintf(&data[2*i], "%02x",
 						pc_event->event_data[i]);
author maintainer
#730 lore raw

PATCH 729/1005 tpm: flush timeout work outside buffer_mutex to avoid deadlock

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hyunjung Ko <[email protected]>

commit c22052a012698ce56d599d75b669d55778521c7c upstream.

tpm_common_read() calls flush_work(&priv->timeout_work) under priv->buffer_mutex, but tpm_timeout_work() also takes buffer_mutex, so a running timeout work deadlocks the flush. Flush after unlocking; the timer is deleted under the lock, so no new work can be queued.

---
 drivers/char/tpm/tpm-dev-common.c |   12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm-dev-common.c +11 -1
@@ -132,6 +132,7 @@ ssize_t tpm_common_read(struct file *fil
 {
 	struct file_priv *priv = file->private_data;
 	ssize_t ret_size = 0;
+	bool flush = false;
 	int rc;
 
 	if (!size)
@@ -164,9 +165,18 @@ out:
 	if (!priv->response_length) {
 		*off = 0;
 		timer_delete_sync(&priv->user_read_timer);
-		flush_work(&priv->timeout_work);
+		flush = true;
 	}
 	mutex_unlock(&priv->buffer_mutex);
+
+	/*
+	 * tpm_timeout_work() takes buffer_mutex, so flush it after dropping
+	 * the mutex to avoid a deadlock; the timer is deleted above, so no new
+	 * timeout work can be queued once the mutex is released.
+	 */
+	if (flush)
+		flush_work(&priv->timeout_work);
+
 	return ret_size;
 }
 
author maintainer
#731 lore raw

PATCH 730/1005 spi: axi-spi-engine: Start the program length at zero

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Kees Cook <[email protected]>

commit 2a490521d74ac76e5eb3c9a69d928a4c76dd3f78 upstream.

spi_engine_optimize_message() allocates the program with kzalloc_flex(), which sets the __counted_by() counter "length" to the allocated size when the compiler supports __builtin_counted_by_ref(). The program is then filled by spi_engine_program_add_cmd(), which increments "length" and stores at length - 1, expecting it to start at zero as it did when the program came from kzalloc().

Reset "length" after the allocation, since it is a "usage" counter, not a "total allocation" counter.

Build tested ARCH=x86_64 defconfig with CONFIG_SPI_AXI_SPI_ENGINE=m and W=1, with GCC 16.2.0.

---
 drivers/spi/spi-axi-spi-engine.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/spi/spi-axi-spi-engine.c +2 -0
index ead5b295e680..9cfee409f15c 100644
@@ -818,6 +818,8 @@ static int spi_engine_optimize_message(struct spi_message *msg)
 	p = kzalloc_flex(*p, instructions, p_dry.length + 1);
 	if (!p)
 		return -ENOMEM;
+	/* spi_engine_program_add_cmd() counts the instructions as it adds them. */
+	p->length = 0;
 
 	spi_engine_compile_message(msg, false, p);
 
Signature · 1 line
2.56.1
author maintainer
#732 lore raw

PATCH 731/1005 spi: tegra210-quad: Track DMA mapping state

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Vishwaroop A <[email protected]>

commit 7b9e6f7bc13c0259b192d0a964e802d4ad53b8b8 upstream.

tegra_qspi_dma_unmap_xfer() assumes a streaming mapping is always outstanding and recomputes its length from the live tqspi->curr_dma_words. Nothing records whether tegra_qspi_dma_map_xfer() mapped anything, so neither assumption holds.

For a multi-chunk transfer, handle_dma_based_xfer() unmaps the chunk that just completed, recalculates the parameters for the next chunk, which overwrites curr_dma_words, and re-arms the hardware. If tegra_qspi_start_dma_based_transfer() then fails at its tegra_qspi_dma_map_xfer() call, nothing is mapped. That early return also sits above the smp_store_release() that clears tqspi->trans_status, so the previous chunk's QSPI_RDY survives, and the re-arm's return value is never checked, so handle_dma_based_xfer() returns IRQ_HANDLED without completing the transfer.

The caller times out, tegra_qspi_handle_timeout() sees the stale QSPI_RDY, concludes the transfer completed and calls handle_dma_based_xfer() again. No DMA completion arrives, so num_errors is incremented and tegra_qspi_dma_unmap_xfer() runs with nothing mapped. t->tx_dma then holds either the DMA_MAPPING_ERROR sentinel or, if the RX mapping was the one that failed, the preceding chunk's address that has already been released. Behind an IOMMU the latter frees an IOVA that may since have been reallocated.

Record whether a mapping is outstanding and the length that was mapped, and return early from tegra_qspi_dma_unmap_xfer() when there is nothing to release. is_dma_mapped is only updated under tqspi->lock, or on the timeout path after synchronize_irq() and cancel_work_sync() have quiesced the ISR and the bottom half.

Also skip releasing the TX mapping on the RX failure path unless a TX mapping was created; t->tx_dma is uninitialised when t->tx_buf is NULL.

Fixes 921fc1838fb0 ("spi: tegra210-quad: Add support for Tegra210 QSPI controller")
---
 drivers/spi/spi-tegra210-quad.c |   31 +++++++++++++++++++++++++------
 1 file changed, 25 insertions(+), 6 deletions(-)
drivers/spi/spi-tegra210-quad.c +25 -6
@@ -215,6 +215,17 @@ struct tegra_qspi {
 	bool					is_packed;
 	bool					use_dma;
 
+	/*
+	 * Set while a streaming mapping created by
+	 * tegra_qspi_dma_map_xfer() is outstanding, together with the
+	 * length that was handed to dma_map_single(). is_curr_dma_xfer
+	 * only records that the last armed chunk took the DMA path,
+	 * which is not the same thing: a chunk whose mapping failed
+	 * leaves the DMA path flagged with nothing mapped.
+	 */
+	bool					is_dma_mapped;
+	unsigned int				dma_map_len;
+
 	u32					command1_reg;
 	u32					dma_control_reg;
 	u32					def_command1_reg;
@@ -584,24 +595,32 @@ static int tegra_qspi_dma_map_xfer(struc
 	if (t->rx_buf) {
 		t->rx_dma = dma_map_single(tqspi->rx_dma_dev, (void *)rx_buf, len, DMA_FROM_DEVICE);
 		if (dma_mapping_error(tqspi->rx_dma_dev, t->rx_dma)) {
-			dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, len, DMA_TO_DEVICE);
+			if (t->tx_buf)
+				dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma,
+						 len, DMA_TO_DEVICE);
 			return -ENOMEM;
 		}
 	}
 
+	tqspi->dma_map_len = len;
+	tqspi->is_dma_mapped = true;
+
 	return 0;
 }
 
 static void tegra_qspi_dma_unmap_xfer(struct tegra_qspi *tqspi, struct spi_transfer *t)
 {
-	unsigned int len;
-
-	len = DIV_ROUND_UP(tqspi->curr_dma_words * tqspi->bytes_per_word, 4) * 4;
+	if (!tqspi->is_dma_mapped)
+		return;
 
 	if (t->tx_buf)
-		dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, len, DMA_TO_DEVICE);
+		dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma,
+				 tqspi->dma_map_len, DMA_TO_DEVICE);
 	if (t->rx_buf)
-		dma_unmap_single(tqspi->rx_dma_dev, t->rx_dma, len, DMA_FROM_DEVICE);
+		dma_unmap_single(tqspi->rx_dma_dev, t->rx_dma,
+				 tqspi->dma_map_len, DMA_FROM_DEVICE);
+
+	tqspi->is_dma_mapped = false;
 }
 
 static int tegra_qspi_start_dma_based_transfer(struct tegra_qspi *tqspi, struct spi_transfer *t)
author maintainer
#733 lore raw

PATCH 732/1005 spi: tegra210-quad: Unmap DMA buffers on transfer timeout

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Vishwaroop A <[email protected]>

commit d04ad85dd8015713b0b2531b5b934fe67828d741 upstream.

tegra_qspi_start_dma_based_transfer() maps the client TX/RX buffers with dma_map_single() via tegra_qspi_dma_map_xfer(). The matching unmap only happens in handle_dma_based_xfer(), which runs from the interrupt bottom half.

When wait_for_completion_timeout() expires and tegra_qspi_handle_timeout() cannot establish that the hardware finished, it returns an error without the bottom half ever having run. Both transfer paths then abort the transfer with tegra_qspi_dma_stop(), reset the controller and clear curr_xfer, but never unmap the buffers. Every genuine transfer timeout therefore leaks the streaming DMA mappings for that chunk, which gradually exhausts the IOVA space on systems with an IOMMU in front of QSPI.

Unmap the transfer after stopping DMA on both timeout error paths. The unmap is placed after tegra_qspi_dma_stop() so the DMA engine is quiesced before the mappings go away.

The recovery paths that do reach handle_dma_based_xfer() unmap there themselves. The preceding patch makes tegra_qspi_dma_unmap_xfer() a no-op once the mapping is released, so this cleanup cannot unmap twice or run against a chunk that was never mapped.

Fixes 921fc1838fb0 ("spi: tegra210-quad: Add support for Tegra210 QSPI controller")
Cc [email protected] # with "spi: tegra210-quad: Track DMA mapping state"
---
 drivers/spi/spi-tegra210-quad.c |   10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
drivers/spi/spi-tegra210-quad.c +7 -3
@@ -1262,10 +1262,12 @@ static int tegra_qspi_combined_seq_xfer(
 					dev_err(tqspi->dev, "transfer timeout\n");
 
 					/* Abort transfer by resetting pio/dma bit */
-					if (tqspi->is_curr_dma_xfer)
+					if (tqspi->is_curr_dma_xfer) {
 						tegra_qspi_dma_stop(tqspi);
-					else
+						tegra_qspi_dma_unmap_xfer(tqspi, xfer);
+					} else {
 						tegra_qspi_pio_stop(tqspi);
+					}
 
 					/* Reset controller if timeout happens */
 					tegra_qspi_reset(tqspi);
@@ -1379,8 +1381,10 @@ static int tegra_qspi_non_combined_seq_x
 				WARN_ON(1);
 				dev_err(tqspi->dev, "transfer timeout\n");
 
-				if (tqspi->is_curr_dma_xfer)
+				if (tqspi->is_curr_dma_xfer) {
 					tegra_qspi_dma_stop(tqspi);
+					tegra_qspi_dma_unmap_xfer(tqspi, xfer);
+				}
 
 				tegra_qspi_handle_error(tqspi);
 				ret = -EIO;
author maintainer
#734 lore raw

PATCH 733/1005 watchdog: gunyah_wdt: Re-enable the watchdog on resume

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Stanislav Aleksandrov <[email protected]>

commit f0dfc756bb46235068279755249131c2a7130111 upstream.

gunyah_wdt_suspend() disables an active watchdog, and gunyah_wdt_resume() enables it again with gunyah_wdt_start(). start() first disables the watchdog, which fails with -EINVAL when it is already disabled. start() ignores that only while the watchdog is inactive, but on resume it is still active for the watchdog core, so start() returns before it enables the watchdog:

gunyah-wdt gunyah-wdt: gunyah_wdt_start: Failed to stop gunyah wdt -22

So after every system suspend, the watchdog is left disabled.

Move setting the timeout and enabling the watchdog into gunyah_wdt_enable(), and call it on resume, where the watchdog is already disabled.

Tested on the Samsung Galaxy XR (Qualcomm Halliday) with s2idle and deep suspend.

---
 drivers/watchdog/gunyah_wdt.c | 27 +++++++++++++++++----------
 1 file changed, 17 insertions(+), 10 deletions(-)
drivers/watchdog/gunyah_wdt.c +17 -10
index e3c2a2131624..35958594e17c 100644
@@ -62,19 +62,12 @@ static int gunyah_wdt_call(unsigned long func_id, unsigned long arg1,
 	return gunyah_error_remap(res.a0);
 }
 
-static int gunyah_wdt_start(struct watchdog_device *wdd)
+static int gunyah_wdt_enable(struct watchdog_device *wdd)
 {
-	unsigned int timeout_ms;
+	unsigned int timeout_ms = wdd->timeout * 1000;
 	struct device *dev = wdd->parent;
 	int ret;
 
-	ret = gunyah_wdt_call(GUNYAH_WDT_CONTROL, WDT_CTRL_DISABLE, 0);
-	if (ret && watchdog_active(wdd)) {
-		dev_err(dev, "%s: Failed to stop gunyah wdt %d\n", __func__, ret);
-		return ret;
-	}
-
-	timeout_ms = wdd->timeout * 1000;
 	ret = gunyah_wdt_call(GUNYAH_WDT_SET_TIME, timeout_ms, timeout_ms);
 	if (ret) {
 		dev_err(dev, "%s: Failed to set timeout for gunyah wdt %d\n",
@@ -89,6 +82,20 @@ static int gunyah_wdt_start(struct watchdog_device *wdd)
 	return ret;
 }
 
+static int gunyah_wdt_start(struct watchdog_device *wdd)
+{
+	struct device *dev = wdd->parent;
+	int ret;
+
+	ret = gunyah_wdt_call(GUNYAH_WDT_CONTROL, WDT_CTRL_DISABLE, 0);
+	if (ret && watchdog_active(wdd)) {
+		dev_err(dev, "%s: Failed to stop gunyah wdt %d\n", __func__, ret);
+		return ret;
+	}
+
+	return gunyah_wdt_enable(wdd);
+}
+
 static int gunyah_wdt_stop(struct watchdog_device *wdd)
 {
 	return gunyah_wdt_call(GUNYAH_WDT_CONTROL, WDT_CTRL_DISABLE, 0);
@@ -224,7 +231,7 @@ static int gunyah_wdt_resume(struct device *dev)
 	struct watchdog_device *wdd = dev_get_drvdata(dev);
 
 	if (watchdog_active(wdd))
-		gunyah_wdt_start(wdd);
+		gunyah_wdt_enable(wdd);
 
 	return 0;
 }
Signature · 1 line
2.56.1
author maintainer
#735 lore raw

PATCH 734/1005 watchdog: npcm: fix clock prepare leak when setting timeout on a running watchdog

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Feng <[email protected]>

commit 57c7cbe21acc77291ec0fbdd4bd72aa259cf4986 upstream.

npcm_wdt_start() unconditionally prepares and enables the watchdog clock, and npcm_wdt_stop() is the only place that disables it. npcm_wdt_set_timeout() calls npcm_wdt_start() again whenever the watchdog is already active, so every WDIOC_SETTIMEOUT ioctl issued while the watchdog is running takes one extra clock prepare/enable reference that is never dropped.

Split the register programming out of npcm_wdt_start() into a __npcm_wdt_start() helper that assumes the clock is already running, and call the helper from npcm_wdt_set_timeout() instead; only the watchdog .start callback (and the restart path, which intentionally keeps the clock) now acquires the clock.

---
 drivers/watchdog/npcm_wdt.c |   15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
drivers/watchdog/npcm_wdt.c +11 -4
@@ -145,13 +145,11 @@ static int npcm_wdt_ping(struct watchdog
 	return 0;
 }
 
-static int npcm_wdt_start(struct watchdog_device *wdd)
+static void __npcm_wdt_start(struct watchdog_device *wdd)
 {
 	struct npcm_wdt *wdt = to_npcm_wdt(wdd);
 	u32 val;
 
-	clk_prepare_enable(wdt->clk);
-
 	if (wdd->timeout < 2)
 		val = 0x800;
 	else if (wdd->timeout < 3)
@@ -176,6 +174,15 @@ static int npcm_wdt_start(struct watchdo
 	val |= NPCM_WTRE | NPCM_WTE | NPCM_WTR | NPCM_WTIE;
 
 	writel(val, wdt->reg);
+}
+
+static int npcm_wdt_start(struct watchdog_device *wdd)
+{
+	struct npcm_wdt *wdt = to_npcm_wdt(wdd);
+
+	clk_prepare_enable(wdt->clk);
+
+	__npcm_wdt_start(wdd);
 
 	return 0;
 }
@@ -216,7 +223,7 @@ static int npcm_wdt_set_timeout(struct w
 		wdd->timeout = 2750;
 
 	if (watchdog_active(wdd))
-		npcm_wdt_start(wdd);
+		__npcm_wdt_start(wdd);
 
 	return 0;
 }
author maintainer
#736 lore raw

PATCH 735/1005 watchdog: rzv2h: Use pm_runtime_put_sync()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Lad Prabhakar <[email protected]>

commit ca800e625d18a9f5b19f94ab837ceb3fccdca22f upstream.

pm_runtime_put() may trigger the idle check after pm_runtime_disable() is run as part of devm_pm_runtime_enable()'s cleanup action, leaving runtime PM active.

Use pm_runtime_put_sync() to ensure the idle check runs synchronously.

Fixes f6febd0a30b6e ("watchdog: Add Watchdog Timer driver for RZ/V2H(P)")
---
 drivers/watchdog/rzv2h_wdt.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/watchdog/rzv2h_wdt.c +2 -2
@@ -174,7 +174,7 @@ static int rzv2h_wdt_stop(struct watchdo
 	if (priv->of_data->wdtdcr)
 		rzt2h_wdt_wdtdcr_count_stop(priv);
 
-	pm_runtime_put(wdev->parent);
+	pm_runtime_put_sync(wdev->parent);
 
 	return 0;
 }
@@ -268,7 +268,7 @@ static int rzt2h_wdt_wdtdcr_init(struct
 
 	rzt2h_wdt_wdtdcr_count_stop(priv);
 
-	pm_runtime_put(&pdev->dev);
+	pm_runtime_put_sync(&pdev->dev);
 
 	return 0;
 }
author maintainer
#737 lore raw

PATCH 736/1005 watchdog: rzv2h: Drop runtime PM handling from WDTDCR init

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Lad Prabhakar <[email protected]>

commit f00afd5d8d5dc03994cb67246543d5c70571ebbe upstream.

WDTDCR is located in the CPG region, outside the watchdog module, and is accessible regardless of the watchdog's clocks and reset state.

Drop the unnecessary runtime PM handling from WDTDCR initialization and access the register directly.

Fixes f6febd0a30b6e ("watchdog: Add Watchdog Timer driver for RZ/V2H(P)")
---
 drivers/watchdog/rzv2h_wdt.c |    8 --------
 1 file changed, 8 deletions(-)
drivers/watchdog/rzv2h_wdt.c +0 -8
@@ -256,20 +256,12 @@ static const struct watchdog_ops rzv2h_w
 static int rzt2h_wdt_wdtdcr_init(struct platform_device *pdev,
 				 struct rzv2h_wdt_priv *priv)
 {
-	int ret;
-
 	priv->wdtdcr = devm_platform_ioremap_resource(pdev, 1);
 	if (IS_ERR(priv->wdtdcr))
 		return PTR_ERR(priv->wdtdcr);
 
-	ret = pm_runtime_resume_and_get(&pdev->dev);
-	if (ret)
-		return ret;
-
 	rzt2h_wdt_wdtdcr_count_stop(priv);
 
-	pm_runtime_put_sync(&pdev->dev);
-
 	return 0;
 }
 
author maintainer
#738 lore raw

PATCH 737/1005 x86/CPU/AMD: Dont print reset reason in VMs

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jason Andryuk <[email protected]>

commit ea51d1a4c31fc8320c34f897dc5296a0bfc5c7ca upstream.

print_s5_reset_status_mmio() expects to read FCH MMIO on baremetal. VMs don't have emulated FCH registers, so there is nothing to check. Add an early exit when running on a hypervisor.

The real motivation is Xen PV domUs can't boot on Zen CPUs. PV domUs PTEs contain system physical addresses - they don't have the concept of guest physical addresses. domUs can only map physical addresses they are assigned, so a domU fails to map the FCH MMIO addresses.

However set_pte() does not return failure, so ioremap() returns a pointer while the PTEs are unpopulated. print_s5_reset_status_mmio() faults when reading through the pointer, breaking the boot.

Limit the reset reason printing to baremetal only where it actually makes sense.

[ bp: Massage commit message. ]

---
 arch/x86/kernel/cpu/amd.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/x86/kernel/cpu/amd.c +2 -1
@@ -1362,7 +1362,8 @@ static __init int print_s5_reset_status_
 	u32 value;
 	int i;
 
-	if (!cpu_feature_enabled(X86_FEATURE_ZEN))
+	if (!cpu_feature_enabled(X86_FEATURE_ZEN) ||
+	    cpu_feature_enabled(X86_FEATURE_HYPERVISOR))
 		return 0;
 
 	addr = ioremap(FCH_PM_BASE + FCH_PM_S5_RESET_STATUS, sizeof(value));
author maintainer
#739 lore raw

PATCH 738/1005 x86/mm: Ensure write visibility during LDT installation

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Dave Hansen <[email protected]>

commit 0dc2a4dac3d04e9e4479aeb0b46172feab1cca0a upstream.

During LDT installation, the intent is to overwrite the old per-mm LDT value, then send an IPI to the mm user CPUs to have each load the new value.

But there is an ordering problem: a new mm user CPU sets itself in mm_cpumask() and then reads mm->context.ldt. The LDT-installing CPU writes mm->context.ldt and then reads mm_cpumask(). But, there is nothing which orders the LDT installation side actions. The CPU can read mm_cpumask() before its write becomes visible.

Ensure that new mm user CPUs see the new mm->context.ldt. Make mm->context.ldt visible before reading mm_cpumask().

Also convert the smp_store_release() over to a WRITE_ONCE(). smp_store_release() has an internal barrier which is weaker than the new smp_mb(). Avoid an extra barrier by converting it to WRITE_ONCE().

Also refresh/correct misleading comments. READ/WRITE_ONCE() do not "synchronize" anything themselves.

---
 arch/x86/kernel/ldt.c |   12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
arch/x86/kernel/ldt.c +9 -3
@@ -43,7 +43,7 @@ void load_mm_ldt(struct mm_struct *mm)
 {
 	struct ldt_struct *ldt;
 
-	/* READ_ONCE synchronizes with smp_store_release */
+	/* Pairs with WRITE_ONCE() in install_ldt() */
 	ldt = READ_ONCE(mm->context.ldt);
 
 	/*
@@ -422,8 +422,14 @@ static void install_ldt(struct mm_struct
 {
 	mutex_lock(&mm->context.lock);
 
-	/* Synchronizes with READ_ONCE in load_mm_ldt. */
-	smp_store_release(&mm->context.ldt, ldt);
+	/*
+	 * Ensure that new mm user CPUs either see the new LDT value
+	 * or get an IPI. Make the store visible before reading
+	 * mm_cpumask(). New mm users make their mm_cpumask() writes
+	 * visible before reading mm->context.ldt.
+	 */
+	WRITE_ONCE(mm->context.ldt, ldt);
+	smp_mb();
 
 	/* Activate the LDT for all CPUs using currents mm. */
 	on_each_cpu_mask(mm_cpumask(mm), flush_ldt, mm, true);
author maintainer
#740 lore raw

PATCH 739/1005 x86/video: Preserve the default VGA fallback for legacy modes

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hengyu Liang <[email protected]>

commit 3b4c98b47ba7c3c57bcf54fb85f54a854622041c upstream.

Commit

596b3678326d ("x86/video: Only fall back to vga_default_device() without screen info")

made video_is_primary_device() rely exclusively on screen_info resources whenever any are available.

However, screen_info_resources() also returns legacy I/O and memory ranges for VGA text modes. These ranges are not PCI BARs, so pci_find_resource() does not find them and the default VGA fallback is skipped. As a result, no device is primary in VGA text mode.

On a SeaBIOS QEMU guest with bochs and VKMS, the boot VGA (bochs) loses its DRM boot_display attribute. VKMS registers fb0 and bochs registers fb1. VKMS is not a PCI device, so it is not primary either. With no primary device, fbcon keeps the console on fb0 and never remaps it to bochs. This can be checked with:

cat /sys/class/drm/card1/boot_display
stty -F /dev/tty1 size

Without the fix, boot_display is missing and tty1 is 48 rows by 128 columns. With it, boot_display contains 1 and tty1 is 50 rows by 160 columns. VKMS only makes the console part visible. Without VKMS, tty1 has the same size with and without the fix, but boot_display is still missing without it.

Use resource-based selection only for linear framebuffers. Fall back to vga_default_device() for legacy display modes, while keeping EFI and VESA framebuffer ownership authoritative.

---
 arch/x86/video/video-common.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/video/video-common.c +1 -1
@@ -45,7 +45,7 @@ bool video_is_primary_device(struct devi
 
 #ifdef CONFIG_SCREEN_INFO
 	numres = screen_info_resources(si, res, ARRAY_SIZE(res));
-	if (numres > 0) {
+	if (numres > 0 && __screen_info_has_lfb(screen_info_video_type(si))) {
 		for (i = 0; i < numres; ++i) {
 			if (!(res[i].flags & IORESOURCE_MEM))
 				continue;
author maintainer
#741 lore raw

PATCH 740/1005 xen/gntdev: fix deadlock between map ioctl and mmap

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Andrey Misiurov <[email protected]>

commit 7620a997e4854c94eacebf0c2d453fbd78ccdb46 upstream.

Commit 45ca1afe2fd1 ("xen/gntdev: fix error handling in ioctl") moved copy_to_user() in gntdev_ioctl_map_grant_ref() under priv->lock. A fault in copy_to_user() takes mmap_lock, while gntdev_mmap() is called with mmap_lock held and takes priv->lock:

ioctl thread mmap thread
mutex_lock(&priv->lock)

                                      mmap_write_lock(mm)
                                      gntdev_mmap()
                                        mutex_lock(&priv->lock)

copy_to_user() faults
mmap_read_lock(mm)

Reproduced on Debian 6.12.111 in a Xen guest, with the ioctl argument on a MAP_PRIVATE file page that has not been written yet. sysrq-w:

task:repro state:D stack:0 pid:4479 tgid:4477 ppid:1 flags:0x00000000

   rwsem_down_read_slowpath+0x25c/0x480
   down_read_killable+0x48/0xc0
   lock_mm_and_find_vma+0x96/0x250
   do_user_addr_fault+0x12d/0x620
   exc_page_fault+0x7e/0x180
   asm_exc_page_fault+0x26/0x30
   _copy_to_user+0x36/0x50
   gntdev_ioctl+0x3b9/0xa00 [xen_gntdev]
   __x64_sys_ioctl+0x97/0xc0
  task:repro state:D stack:0 pid:4480 tgid:4477 ppid:1 flags:0x00000000
   __mutex_lock.constprop.0+0x41b/0x720
   gntdev_mmap+0x4d/0x330 [xen_gntdev]
   __mmap_region+0x697/0xb10
   mmap_region+0x78/0xa0
   do_mmap+0x45d/0x630
   vm_mmap_pgoff+0xf8/0x1c0

Drop priv->lock before copy_to_user() again. On failure, re-take it and remove the map by index, as IOCTL_GNTDEV_UNMAP_GRANT_REF does, since another thread may have unmapped it meanwhile.

Fixes 45ca1afe2fd1 ("xen/gntdev: fix error handling in ioctl")

Message-ID: <[email protected]>

---
 drivers/xen/gntdev.c |    8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/xen/gntdev.c +6 -2
@@ -670,15 +670,19 @@ static long gntdev_ioctl_map_grant_ref(s
 	mutex_lock(&priv->lock);
 	gntdev_add_map(priv, map);
 	op.index = map->index << PAGE_SHIFT;
+	mutex_unlock(&priv->lock);
 
 	if (copy_to_user(u, &op, sizeof(op)) != 0) {
-		list_del(&map->next);
+		mutex_lock(&priv->lock);
+		map = gntdev_find_map_index(priv, op.index >> PAGE_SHIFT,
+					    op.count);
+		if (map)
+			list_del(&map->next);
 		mutex_unlock(&priv->lock);
 		gntdev_put_map(priv, map);
 		return -EFAULT;
 	}
 
-	mutex_unlock(&priv->lock);
 	return 0;
 }
 
author maintainer
#742 lore raw

PATCH 741/1005 xen/privcmd: fix double free when an irqfd is shut down twice

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Qihang <[email protected]>

commit 72a900c666adb97df77b05cf8540c4117f9c83ba upstream.

irqfd_deactivate() takes the irqfd off irqfds_list and queues irqfd_shutdown(). queue_work() is not a once-only gate: it refuses to enqueue a work item only while WORK_STRUCT_PENDING is set, and process_one_work() clears that bit before it calls the work function. So nothing records that the shutdown work has already been queued, and nothing protects the window between the start of irqfd_shutdown() and the kfree() at its end.

Two paths call irqfd_deactivate() for the same irqfd:

- privcmd_irqfd_deassign(), from the PRIVCMD_IRQFD_FLAG_DEASSIGN ioctl;

- irqfd_wakeup(), with EPOLLHUP set, when the last reference to the

    eventfd file goes away, which runs wake_up_poll(&ctx->wqh, EPOLLHUP)
    from eventfd_release().

irqfds_lock serialises the two calls, but it does not make the second one a no-op, and eventfd_ctx_fdget() takes a reference to the eventfd_ctx, not to the struct file, so the last fd can still be closed while the ioctl is running:

CPU0 CPU1

eventfd_ctx_fdget()
spin_lock(irqfds_lock)
list_del_init(&kirqfd->list)
queue_work(&kirqfd->shutdown) close(fd)
eventfd_release()
wake_up_poll(EPOLLHUP)
irqfd_wakeup() spin_lock(irqfds_lock) irqfd_deactivate() again

If the work item has already started by then, its pending bit has been cleared and the second queue_work() succeeds. irqfd_shutdown() then runs twice, so eventfd_ctx_remove_wait_queue(), eventfd_ctx_put() and kfree() each hit the same object a second time; and when the second queue_work() lands after the irqfd has been freed, the workqueue list operations write to freed memory.

virt/kvm/eventfd.c has the same two callers and has had this guard since the original irqfd support (721eecbf4fe99): irqfd_wakeup() calls irqfd_deactivate() only if irqfd_is_active(). The comment there explains why that is enough: the other side deactivates the irqfd before it takes it off the waitqueue, and irqfd_shutdown() needs the waitqueue lock, which this callback holds, so the irqfd cannot be freed under it.

Do the same here. list_del_init() leaves the list head empty and the irqfd stays off the list until kfree(), so it serves as a one-way "active" flag. The test is in irqfd_deactivate() rather than in irqfd_wakeup() because privcmd_irqfd_deassign() walks irqfds_list and can therefore never reach an inactive irqfd; only the wakeup path can, and a single test covers both callers.

Fixes f8941e6c4c712 ("xen: privcmd: Add support for irqfd")

Message-ID: <[email protected]>

---
 drivers/xen/privcmd.c |   15 +++++++++++++++
 1 file changed, 15 insertions(+)
drivers/xen/privcmd.c +15 -0
@@ -901,10 +901,25 @@ struct privcmd_kernel_irqfd {
 	poll_table pt;
 };
 
+static bool irqfd_is_active(struct privcmd_kernel_irqfd *kirqfd)
+{
+	lockdep_assert_held(&irqfds_lock);
+
+	return !list_empty(&kirqfd->list);
+}
+
 static void irqfd_deactivate(struct privcmd_kernel_irqfd *kirqfd)
 {
 	lockdep_assert_held(&irqfds_lock);
 
+	/*
+	 * Both the deassign ioctl and the eventfd wakeup path can reach
+	 * this function.  list_del_init() marks the irqfd inactive, so
+	 * only the first caller may queue the shutdown work.
+	 */
+	if (!irqfd_is_active(kirqfd))
+		return;
+
 	list_del_init(&kirqfd->list);
 	queue_work(irqfd_cleanup_wq, &kirqfd->shutdown);
 }
author maintainer
#743 lore raw

PATCH 742/1005 xen/pvcalls: unwind pvcalls_new_active_socket() step by step

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yehyeong Lee <[email protected]>

commit 702ba3c80a8736898813a2c7484d695278aa114d upstream.

Every error path in pvcalls_new_active_socket() jumps to one shared label that does list_del(&map->list) and then hands map to pvcalls_back_release_active(). But map comes from kzalloc() and its list_head is only published at the very end of the function, after the last of those jumps:

	down(&fedata->socket_lock);
	list_add_tail(&map->list, &fedata->socket_mappings);
	up(&fedata->socket_lock);

so on the error path map->list is still {NULL, NULL} and __list_del() writes through a NULL pointer.

A frontend gets there with one value it owns: the ring_order field of the page it granted. Anything above MAX_RING_ORDER takes the second goto, and nothing else in the function has run by then.

The result is an oops in whichever context handled the request - the pvcalls-back threaded IRQ handler for PVCALLS_CONNECT, mappass->wq for PVCALLS_ACCEPT - and because it happens after down(&fedata->socket_lock) that semaphore is never released, so every later operation on the frontend blocks on it and the backend never completes backend_disconnect(). (With CONFIG_DEBUG_LIST the list_del() only reports and returns, and pvcalls_back_release_active() then runs on a map whose irq is still 0 and whose bytes, ioworker.wq and saved_data_ready are all NULL.)

A frontend asking for ring_order 5, on a dom0 built with KASAN (the request was issued by a test-only change to the frontend):

[  133.728877] pvcalls_new_active_socket frontend requested ring_order 5, which is > MAX (4)
[  133.732868] Oops: general protection fault, probably for non-canonical address 0xdffffc0000000001: 0000 [#1] SMP KASAN NOPTI
[  133.737910] KASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f]
[  133.741666] CPU: 0 UID: 0 PID: 133 Comm: irq/39-pvcalls- Not tainted 7.3.0-kCTLblk2-15482-g21a7f44fd076-dirty #1 PREEMPT(full)
[  133.746986] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
[  133.751512] RIP: 0010:pvcalls_new_active_socket+0x821/0xb90
[  133.754237] Code: 48 89 fa 48 c1 ea 03 80 3c 02 00 0f 85 f6 01 00 00 48 8d 79 08 4c 8b 6b 08 48 b8 00 00 00 00 00 fc ff df 48 89 fa 48 c1 ea 03 <80> 3c 02 00 0f 85 14 02 00 00 4c 89 ea 4c 89 69 08 48 b8 00 00 00
[  133.763126] RSP: 0018:ffffc900004afb38 EFLAGS: 00010202
[  133.765861] RAX: dffffc0000000000 RBX: ffff88810886c900 RCX: 0000000000000000
[  133.769348] RDX: 0000000000000001 RSI: 0000000000000246 RDI: 0000000000000008
[  133.772787] RBP: 1ffff92000095f6b R08: 0000000000000001 R09: fffff52000095f58
[  133.776260] R10: 0000000000000003 R11: ffff888100077320 R12: ffff88810858b410
[  133.779823] R13: 0000000000000000 R14: ffff88810858b460 R15: ffff88810858b400
[  133.783382] FS:  0000000000000000(0000) GS:ffff8881b034c000(0000) knlGS:0000000000000000
[  133.787351] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[  133.790308] CR2: 00000000006042c0 CR3: 0000000108400001 CR4: 0000000000770ef0
[  133.793822] PKRU: 55555554
[  133.795347] Call Trace:
[  133.796778]  <TASK>
[  133.798082]  ? __pfx_pvcalls_new_active_socket+0x10/0x10
[  133.800801]  ? security_socket_post_create+0x4d/0x60
[  133.803275]  ? release_sock+0x1a/0x1d0
[  133.805182]  pvcalls_back_event+0x1b09/0x23e0
[  133.807431]  ? __pfx_pvcalls_back_event+0x10/0x10
[  133.809814]  ? __pfx__raw_spin_lock_irqsave+0x10/0x10
[  133.812251]  ? __pfx_pvcalls_back_event+0x10/0x10
[  133.814554]  irq_thread_fn+0x86/0x150
[  133.816468]  irq_thread+0x2da/0x580
[  133.818363]  ? __pfx_irq_thread_fn+0x10/0x10
[  133.820586]  ? __pfx_irq_thread+0x10/0x10
[  133.822670]  ? __kthread_parkme+0x88/0x170
[  133.824803]  ? __pfx_irq_thread+0x10/0x10
[  133.827153]  ? __pfx_irq_thread+0x10/0x10
[  133.829304]  kthread+0x2c8/0x3b0
[  133.831176]  ? recalc_sigpending+0x15c/0x1e0
[  133.833570]  ? __pfx_kthread+0x10/0x10
[  133.835572]  ret_from_fork+0x373/0x5b0
[  133.837581]  ? __pfx_ret_from_fork+0x10/0x10
[  133.839978]  ? __switch_to+0x3c4/0xb40
[  133.841984]  ? __pfx_kthread+0x10/0x10
[  133.843970]  ret_from_fork_asm+0x1a/0x30
[  133.846031]  </TASK>
[  133.847420] Modules linked in:
[  133.849240] ---[ end trace 0000000000000000 ]---

Give each failure its own label, so that only resources that were actually acquired are released and the list the map was never added to is left
alone. The map is not published anywhere at that point, so the error path needs no socket_lock at all. sock_release() stays in the callee on every error path, the way
commit 8fafac202d18 ("xen/pvcalls-back: fix double frees with pvcalls_new_active_socket()") arranged it.

Fixes 5db4d286a8ef ("xen/pvcalls: implement connect command")

Message-ID: <[email protected]>

---
 drivers/xen/pvcalls-back.c |   25 +++++++++++++++----------
 1 file changed, 15 insertions(+), 10 deletions(-)
drivers/xen/pvcalls-back.c +15 -10
@@ -337,7 +337,7 @@ static struct sock_mapping *pvcalls_new_
 
 	ret = xenbus_map_ring_valloc(fedata->dev, &ref, 1, &page);
 	if (ret < 0)
-		goto out;
+		goto out_map;
 	map->ring = page;
 	map->ring_order = map->ring->ring_order;
 	/* first read the order, then map the data ring */
@@ -345,19 +345,19 @@ static struct sock_mapping *pvcalls_new_
 	if (map->ring_order > MAX_RING_ORDER) {
 		pr_warn("%s frontend requested ring_order %u, which is > MAX (%u)\n",
 				__func__, map->ring_order, MAX_RING_ORDER);
-		goto out;
+		goto out_unmap_ring;
 	}
 	ret = xenbus_map_ring_valloc(fedata->dev, map->ring->ref,
 				     (1 << map->ring_order), &page);
 	if (ret < 0)
-		goto out;
+		goto out_unmap_ring;
 	map->bytes = page;
 
 	ret = bind_interdomain_evtchn_to_irqhandler_lateeoi(
 			fedata->dev, evtchn,
 			pvcalls_back_conn_event, 0, "pvcalls-backend", map);
 	if (ret < 0)
-		goto out;
+		goto out_unmap_bytes;
 	map->irq = ret;
 
 	map->data.in = map->bytes;
@@ -365,7 +365,7 @@ static struct sock_mapping *pvcalls_new_
 
 	map->ioworker.wq = alloc_ordered_workqueue("pvcalls_io", 0);
 	if (!map->ioworker.wq)
-		goto out;
+		goto out_unbind;
 	atomic_set(&map->io, 1);
 	INIT_WORK(&map->ioworker.register_work,	pvcalls_back_ioworker);
 
@@ -381,11 +381,16 @@ static struct sock_mapping *pvcalls_new_
 	write_unlock_bh(&map->sock->sk->sk_callback_lock);
 
 	return map;
-out:
-	down(&fedata->socket_lock);
-	list_del(&map->list);
-	pvcalls_back_release_active(fedata->dev, fedata, map);
-	up(&fedata->socket_lock);
+
+out_unbind:
+	unbind_from_irqhandler(map->irq, map);
+out_unmap_bytes:
+	xenbus_unmap_ring_vfree(fedata->dev, map->bytes);
+out_unmap_ring:
+	xenbus_unmap_ring_vfree(fedata->dev, (void *)map->ring);
+out_map:
+	sock_release(sock);
+	kfree(map);
 	return NULL;
 }
 
author maintainer
#744 lore raw

PATCH 743/1005 xen/pvcalls: destroy the per-socket workqueue on release

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yehyeong Lee <[email protected]>

commit 6b3feb6bfa9ac384f7a3ec25c40b9b4d3da96d25 upstream.

pvcalls_new_active_socket() gives every active socket its own ordered workqueue:

	map->ioworker.wq = alloc_ordered_workqueue("pvcalls_io", 0);

and nothing ever destroys it. pvcalls_back_release_active() flushes map->ioworker.register_work and frees map, but the workqueue and its pool_workqueues stay allocated, so a frontend leaks a workqueue per socket it connects and releases - a loop a guest can run as long as it likes.

Destroy it right after flush_work(): the IRQ is disabled and sk_data_ready restored by then, so nothing can queue new work, and the rings are still mapped while it drains - pvcalls_conn_back_read() reads map->ring and map->data, which xenbus_unmap_ring_vfree() takes away a few lines later. pvcalls_back_ioworker() does not take fedata->socket_lock, which the backend_disconnect() caller holds here - only the socket's own sk_receive_queue lock - so draining it from this point is safe; the flush_work() just above already has the same requirement.

Fixes 5db4d286a8ef ("xen/pvcalls: implement connect command")

Message-ID: <[email protected]>

---
 drivers/xen/pvcalls-back.c |    1 +
 1 file changed, 1 insertion(+)
drivers/xen/pvcalls-back.c +1 -0
@@ -452,6 +452,7 @@ static int pvcalls_back_release_active(s
 
 	atomic_set(&map->release, 1);
 	flush_work(&map->ioworker.register_work);
+	destroy_workqueue(map->ioworker.wq);
 
 	xenbus_unmap_ring_vfree(dev, map->bytes);
 	xenbus_unmap_ring_vfree(dev, (void *)map->ring);
author maintainer
#745 lore raw

PATCH 744/1005 kbuild: rust: support stabilized flag `-Cprofile-sample-use` for Rust >= 1.100

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Miguel Ojeda <[email protected]>

commit 1178120c3bed1733aea1c465200a6b42f8a7105d upstream.

Starting with Rust 1.100.0 (expected 2026-11-12), the -Zprofile-sample-use flag has been stabilized as -Cprofile-sample-use and the former is not available anymore [1].

Without this change, when building with CLANG_AUTOFDO_PROFILE set, one gets in the latest betas and nightlies:

error: unknown unstable option: profile-sample-use

Thus pass the right name.

---
 scripts/Makefile.autofdo | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/Makefile.autofdo +1 -1
index 57a3aba6ffc2..32c18df237f1 100644
@@ -13,7 +13,7 @@ endif
 ifdef CLANG_AUTOFDO_PROFILE
   CFLAGS_AUTOFDO_CLANG += -fprofile-sample-use=$(CLANG_AUTOFDO_PROFILE) -ffunction-sections
   CFLAGS_AUTOFDO_CLANG += -fsplit-machine-functions
-  RUSTFLAGS_AUTOFDO_CLANG += -Zprofile-sample-use=$(CLANG_AUTOFDO_PROFILE) -Zfunction-sections=y
+  RUSTFLAGS_AUTOFDO_CLANG += $(if $(call rustc-min-version,110000),-Cprofile-sample-use,-Zprofile-sample-use)=$(CLANG_AUTOFDO_PROFILE) -Zfunction-sections=y
   RUSTFLAGS_AUTOFDO_CLANG += -Cllvm-args=-split-machine-functions
 endif
 
Signature · 1 line
2.56.1
author maintainer
#746 lore raw

PATCH 745/1005 hwmon: (aht10) Fix update_interval overflow on 64-bit

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rupesh Majhi <[email protected]>

commit b5c5b67e02406fb48acf57cf2c30a570230fd6aa upstream.

On 64-bit, update_interval writes are clamped to LONG_MAX ms, but ms_to_ktime() overflows above 9223372036854 ms and the interval wraps. LONG_MAX becomes -1 ms, so every read starts a new measurement and update_interval reads back -1.

Clamp to INT_MAX like sht4x, so the limit is the same on all platforms.

Fixes 8c78f0dee437 ("hwmon: Add AHT10 Temperature and Humidity Sensor Driver")
---
 drivers/hwmon/aht10.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/aht10.c +1 -1
@@ -222,7 +222,7 @@ static int aht10_read_values(struct aht1
 static ssize_t aht10_interval_write(struct aht10_data *data,
 				    long val)
 {
-	data->min_poll_interval = ms_to_ktime(clamp_val(val, 2000, LONG_MAX));
+	data->min_poll_interval = ms_to_ktime(clamp_val(val, 2000, INT_MAX));
 	return 0;
 }
 
author maintainer
#747 lore raw

PATCH 746/1005 hwmon: (gpio-fan) Fix runtime PM imbalance in probe and teardown

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Guenter Roeck <[email protected]>

commit 221b565a3316b1ba3a9bcd1f61238440207b3e00 upstream.

In gpio_fan_probe(), gpio_fan_stop() is registered conditionally as a devres action before runtime PM is initialized, while gpio_fan_stop() unconditionally calls pm_runtime_disable(). This breaks runtime PM disable_depth and usage_count invariants across several paths:

- On alarm-only devices without control GPIOs, gpio_fan_stop() is never registered, leaving pm_runtime_enable() unbalanced on unbind and triggering "Unbalanced pm_runtime_enable!" on subsequent binds.
- When control GPIOs are present and devm_add_action_or_reset(), hwmon registration, or fan_alarm_init() fails, gpio_fan_stop() runs before pm_runtime_enable(), incrementing disable_depth to 2 (leaving runtime PM permanently disabled on re-probe) and, if speed_index > 0, underflowing usage_count via pm_runtime_put_sync().
- If pm_runtime_resume_and_get() fails when speed_index > 0, it drops its reference while speed_index remains non-zero, causing gpio_fan_stop() to call pm_runtime_put_sync() and underflow usage_count.
- Registering the hwmon device before enabling runtime PM exposes sysfs attributes that can invoke set_fan_speed() before runtime PM state is initialized.

Initialize runtime PM upfront with pm_runtime_set_suspended() and devm_pm_runtime_enable(), remove pm_runtime_disable() from gpio_fan_stop(), and acquire the initial active runtime PM reference before registering gpio_fan_stop() and the hwmon device.

---
 drivers/hwmon/gpio-fan.c |   24 +++++++++++-------------
 1 file changed, 11 insertions(+), 13 deletions(-)
drivers/hwmon/gpio-fan.c +11 -13
@@ -531,8 +531,6 @@ static void gpio_fan_stop(void *data)
 	mutex_lock(&fan_data->lock);
 	set_fan_speed(data, 0);
 	mutex_unlock(&fan_data->lock);
-
-	pm_runtime_disable(fan_data->dev);
 }
 
 static int gpio_fan_probe(struct platform_device *pdev)
@@ -560,6 +558,11 @@ static int gpio_fan_probe(struct platfor
 		return dev_err_probe(dev, PTR_ERR(fan_data->supply),
 				     "Failed to get fan-supply");
 
+	pm_runtime_set_suspended(dev);
+	err = devm_pm_runtime_enable(dev);
+	if (err)
+		return err;
+
 	/* Configure control GPIOs if available. */
 	if (fan_data->gpios && fan_data->num_gpios > 0) {
 		if (!fan_data->speed || fan_data->num_speed <= 1)
@@ -567,6 +570,12 @@ static int gpio_fan_probe(struct platfor
 		err = fan_ctrl_init(fan_data);
 		if (err)
 			return err;
+		/* If current GPIO state is active, mark RPM as active as well */
+		if (fan_data->speed_index > 0) {
+			err = pm_runtime_resume_and_get(dev);
+			if (err)
+				return err;
+		}
 		err = devm_add_action_or_reset(dev, gpio_fan_stop, fan_data);
 		if (err)
 			return err;
@@ -587,17 +596,6 @@ static int gpio_fan_probe(struct platfor
 			return err;
 	}
 
-	pm_runtime_set_suspended(&pdev->dev);
-	pm_runtime_enable(&pdev->dev);
-	/* If current GPIO state is active, mark RPM as active as well */
-	if (fan_data->speed_index > 0) {
-		int ret;
-
-		ret = pm_runtime_resume_and_get(&pdev->dev);
-		if (ret)
-			return ret;
-	}
-
 	/* Optional cooling device register for Device tree platforms */
 	fan_data->cdev = devm_thermal_of_child_cooling_device_register(dev, np,
 								       "gpio-fan",
author maintainer
#748 lore raw

PATCH 747/1005 hwmon: (pmbus/mp2975) Get vout fault limits dynamically

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Felix Radensky <[email protected]>

commit 00944852275efd39706fe7b9ce75c28edde983eb upstream.

The over- and under-voltage fault limits of the tracking mode are relative to the voltage reference, which follows the VID/AVS requests issued to the device and therefore changes at runtime.

The driver reads the voltage reference once during probe and derives the limits from that snapshot, which the PMBus core caches in addition. As a result in2_crit and in2_lcrit reflect the operating point at probe, rather than the thresholds the device enforces. On systems where the device supplies the CPU core voltage, in2_crit was reported anywhere between 1.15V and 1.70V across identical systems, causing false over-voltage reports once the CPU voltage exceeded the value latched at probe.

Read the voltage reference and the over-voltage offset selector whenever a limit is requested, and mark both limits with pmbus_set_update(), so that the core does not cache them. The voltage reference is available on page 3 only. Let the core change the page, so that the page it caches matches the device, except for a single rail configuration, for which the core does not issue PAGE commands, and the page is changed directly.

With the selector read at runtime, a device configured with an unsupported selector no longer fails to probe. The OVP1 threshold, which does not depend on the selector, is reported for it instead, with a warning.

Clamp the under-voltage limit to zero, since the offset can exceed a low voltage reference, while a negative value would be reported as a read error.

Fixes 2c6fcbb21149 ("hwmon: (pmbus) Add support for MPS Multi-phase mp2975 controller")
---
 drivers/hwmon/pmbus/mp2975.c |  207 +++++++++++++++++++++++--------------------
 1 file changed, 115 insertions(+), 92 deletions(-)
drivers/hwmon/pmbus/mp2975.c +115 -92
@@ -109,10 +109,7 @@ struct mp2975_data {
 	int vout_scale;
 	int max_phases[MP2975_PAGE_NUM];
 	int vid_step[MP2975_PAGE_NUM];
-	int vref[MP2975_PAGE_NUM];
-	int vref_off[MP2975_PAGE_NUM];
 	int vout_max[MP2975_PAGE_NUM];
-	int vout_ov_fixed[MP2975_PAGE_NUM];
 	int curr_sense_gain[MP2975_PAGE_NUM];
 };
 
@@ -460,12 +457,77 @@ static int mp2973_write_word_data(struct
 	return pmbus_write_word_data(client, 0, PMBUS_SMBALERT_MASK, ret);
 }
 
+/*
+ * Let the PMBus core change the page, so that the page it caches matches the
+ * device. The core does not issue PAGE commands for a single rail
+ * configuration, thus change the page directly then.
+ */
+static int
+mp2975_page_set(struct i2c_client *client, struct mp2975_data *data, int page)
+{
+	if (data->info.pages > 1)
+		return pmbus_set_page(client, page, 0xff);
+
+	return i2c_smbus_write_byte_data(client, PMBUS_PAGE, page);
+}
+
+/*
+ * Voltage reference is available on page 3 only. The callers read a register
+ * of the rail through the core first, thus the core caches the rail page.
+ */
+static int
+mp2975_vref_get(struct i2c_client *client, struct mp2975_data *data, int page)
+{
+	int ret, vref;
+
+	ret = mp2975_page_set(client, data, 3);
+	if (ret < 0)
+		return ret;
+
+	vref = i2c_smbus_read_word_data(client, page ? MP2975_MFR_READ_VREF_R2 :
+						       MP2975_MFR_READ_VREF_R1);
+
+	ret = mp2975_page_set(client, data, page);
+	if (ret < 0)
+		return ret;
+
+	return (vref < 0) ? vref : vref * data->vid_step[page];
+}
+
+static int
+mp2975_ovp2_offset_get(int ovp_th_set)
+{
+	switch ((ovp_th_set & GENMASK(5, 3)) >> 3) {
+	case 1:
+		return 140;
+	case 2:
+		return 220;
+	case 4:
+		return 400;
+	default:
+		return -EINVAL;
+	}
+}
+
+static int
+mp2975_vout_ovp2_get(struct i2c_client *client, struct mp2975_data *data,
+		     int page, int vref_off)
+{
+	int vref;
+
+	vref = mp2975_vref_get(client, data, page);
+	if (vref < 0)
+		return vref;
+
+	return vref + DIV_ROUND_CLOSEST(vref_off * data->vout_scale, 10);
+}
+
 static int mp2975_read_word_data(struct i2c_client *client, int page,
 				 int phase, int reg)
 {
 	const struct pmbus_driver_info *info = pmbus_get_driver_info(client);
 	struct mp2975_data *data = to_mp2975_data(info);
-	int ret;
+	int ret, ovp1, vref_off, uv_off;
 
 	switch (reg) {
 	case PMBUS_OT_FAULT_LIMIT:
@@ -482,19 +544,35 @@ static int mp2975_read_word_data(struct
 		break;
 	case PMBUS_VOUT_OV_FAULT_LIMIT:
 		/*
-		 * Register provides two values for over-voltage protection
-		 * threshold for fixed (ovp2) and tracking (ovp1) modes. The
-		 * minimum of these two values is provided as over-voltage
-		 * fault alarm.
+		 * Device provides dual over-voltage protection. OVP1 is
+		 * referred to the maximum reference voltage, while OVP2 is
+		 * referred to the current voltage reference, which is changed
+		 * at runtime. Protection is tripped by any of them, thus the
+		 * minimum of the two is exposed as over-voltage fault alarm,
+		 * and OVP2 is obtained on each read.
 		 */
 		ret = mp2975_read_word_helper(client, page, phase,
 					      MP2975_MFR_OVP_TH_SET,
-					      GENMASK(2, 0));
+					      GENMASK(5, 0));
 		if (ret < 0)
 			return ret;
 
-		ret = min_t(int, data->vout_max[page] + 50 * (ret + 1),
-			    data->vout_ov_fixed[page]);
+		ovp1 = data->vout_max[page] + 50 * ((ret & GENMASK(2, 0)) + 1);
+
+		/* OVP1 still applies if the OVP2 threshold is unknown. */
+		vref_off = mp2975_ovp2_offset_get(ret);
+		if (vref_off < 0) {
+			dev_warn_once(&client->dev,
+				      "unsupported OVP2 selector, reporting OVP1 threshold\n");
+			ret = ovp1;
+			break;
+		}
+
+		ret = mp2975_vout_ovp2_get(client, data, page, vref_off);
+		if (ret < 0)
+			return ret;
+
+		ret = min_t(int, ovp1, ret);
 		break;
 	case PMBUS_VOUT_UV_FAULT_LIMIT:
 		ret = mp2975_read_word_helper(client, page, phase,
@@ -503,8 +581,17 @@ static int mp2975_read_word_data(struct
 		if (ret < 0)
 			return ret;
 
-		ret = DIV_ROUND_CLOSEST(data->vref[page] * 10 - 50 *
-					(ret + 1) * data->vout_scale, 10);
+		uv_off = 50 * (ret + 1) * data->vout_scale;
+
+		ret = mp2975_vref_get(client, data, page);
+		if (ret < 0)
+			return ret;
+
+		/*
+		 * Offset can exceed the voltage reference, while a negative
+		 * value would be reported as a read error.
+		 */
+		ret = max_t(int, DIV_ROUND_CLOSEST(ret * 10 - uv_off, 10), 0);
 		break;
 	case PMBUS_VIRT_READ_POUT_MAX:
 		ret = mp2975_read_word_helper(client, page, phase,
@@ -754,60 +841,6 @@ mp2975_current_sense_gain_get(struct i2c
 }
 
 static int
-mp2975_vref_get(struct i2c_client *client, struct mp2975_data *data,
-		struct pmbus_driver_info *info)
-{
-	int ret;
-
-	ret = i2c_smbus_write_byte_data(client, PMBUS_PAGE, 3);
-	if (ret < 0)
-		return ret;
-
-	/* Get voltage reference value for rail 1. */
-	ret = i2c_smbus_read_word_data(client, MP2975_MFR_READ_VREF_R1);
-	if (ret < 0)
-		return ret;
-
-	data->vref[0] = ret * data->vid_step[0];
-
-	/* Get voltage reference value for rail 2, if connected. */
-	if (data->info.pages == MP2975_PAGE_NUM) {
-		ret = i2c_smbus_read_word_data(client, MP2975_MFR_READ_VREF_R2);
-		if (ret < 0)
-			return ret;
-
-		data->vref[1] = ret * data->vid_step[1];
-	}
-	return 0;
-}
-
-static int
-mp2975_vref_offset_get(struct i2c_client *client, struct mp2975_data *data,
-		       int page)
-{
-	int ret;
-
-	ret = i2c_smbus_read_word_data(client, MP2975_MFR_OVP_TH_SET);
-	if (ret < 0)
-		return ret;
-
-	switch ((ret & GENMASK(5, 3)) >> 3) {
-	case 1:
-		data->vref_off[page] = 140;
-		break;
-	case 2:
-		data->vref_off[page] = 220;
-		break;
-	case 4:
-		data->vref_off[page] = 400;
-		break;
-	default:
-		return -EINVAL;
-	}
-	return 0;
-}
-
-static int
 mp2975_vout_max_get(struct i2c_client *client, struct mp2975_data *data,
 		    struct pmbus_driver_info *info, int page)
 {
@@ -911,25 +944,6 @@ mp2975_vout_per_rail_config_get(struct i
 		ret = mp2975_vout_max_get(client, data, info, i);
 		if (ret < 0)
 			return ret;
-
-		/* Skip if reading Vref is unsupported */
-		if (data->chip_id != mp2975)
-			continue;
-
-		/* Obtain voltage reference offsets. */
-		ret = mp2975_vref_offset_get(client, data, i);
-		if (ret < 0)
-			return ret;
-
-		/*
-		 * Set over-voltage fixed value. Thresholds are provided as
-		 * fixed value, and tracking value. The minimum of them are
-		 * exposed as over-voltage critical threshold.
-		 */
-		data->vout_ov_fixed[i] = data->vref[i] +
-					 DIV_ROUND_CLOSEST(data->vref_off[i] *
-							   data->vout_scale,
-							   10);
 	}
 
 	return 0;
@@ -1043,11 +1057,6 @@ static int mp2975_probe(struct i2c_clien
 		if (ret)
 			return ret;
 
-		/* Obtain voltage reference values. */
-		ret = mp2975_vref_get(client, data, info);
-		if (ret)
-			return ret;
-
 		/* Obtain vout over-voltage scales. */
 		ret = mp2975_vout_ov_scale_get(client, data, info);
 		if (ret < 0)
@@ -1064,7 +1073,21 @@ static int mp2975_probe(struct i2c_clien
 	if (ret)
 		return ret;
 
-	return pmbus_do_probe(client, info);
+	ret = pmbus_do_probe(client, info);
+	if (ret)
+		return ret;
+
+	/*
+	 * Vout over- and under-voltage fault limits are relative to the
+	 * voltage reference, which is changed at runtime. Do not allow the
+	 * PMBus core to cache them.
+	 */
+	if (data->chip_id == mp2975) {
+		pmbus_set_update(client, PMBUS_VOUT_OV_FAULT_LIMIT, true);
+		pmbus_set_update(client, PMBUS_VOUT_UV_FAULT_LIMIT, true);
+	}
+
+	return 0;
 }
 
 static const struct of_device_id mp2975_of_match[] = {
author maintainer
#749 lore raw

PATCH 748/1005 hwmon: (sy7636a) fix negative temperatures

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Pablo Mazzini <[email protected]>

commit fc8519fab34e162b0c29dacccf73031820878917 upstream.

The thermistor readout is a signed 8-bit value in degrees Celsius.

Fixes de34a4053250 ("hwmon: sy7636a: Add temperature driver for sy7636a")
---
 drivers/hwmon/sy7636a-hwmon.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/sy7636a-hwmon.c +1 -1
@@ -29,7 +29,7 @@ static int sy7636a_read(struct device *d
 	if (ret)
 		return ret;
 
-	*temp = reg_val * 1000;
+	*temp = (s8)reg_val * 1000;
 
 	return 0;
 }
author maintainer
#750 lore raw

PATCH 749/1005 hwmon: (scmi) Check channel config allocation

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Sudeep Holla <[email protected]>

commit a2996d892d0150d059d39c683d95d6fd7a37630a upstream.

scmi_hwmon_add_chan_info() can fail to allocate a channel's config array. Ignoring that error leaves a channel with a NULL config pointer in the hwmon chip info, which hwmon dereferences while registering the device.

Check the helper's return value and abort probe on failure.

---
 drivers/hwmon/scmi-hwmon.c |   12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)
drivers/hwmon/scmi-hwmon.c +7 -5
@@ -228,8 +228,8 @@ static int scmi_thermal_sensor_register(
 
 static int scmi_hwmon_probe(struct scmi_device *sdev)
 {
-	int i, idx;
 	u16 nr_sensors;
+	int i, idx, ret;
 	enum hwmon_sensor_types type;
 	struct scmi_sensors *scmi_sensors;
 	const struct scmi_sensor_info *sensor;
@@ -299,8 +299,12 @@ static int scmi_hwmon_probe(struct scmi_
 		if (!nr_count[type])
 			continue;
 
-		scmi_hwmon_add_chan_info(scmi_hwmon_chan, dev, nr_count[type],
-					 type, hwmon_attributes[type]);
+		ret = scmi_hwmon_add_chan_info(scmi_hwmon_chan, dev,
+					       nr_count[type], type,
+					       hwmon_attributes[type]);
+		if (ret)
+			return ret;
+
 		*ptr_scmi_ci++ = scmi_hwmon_chan++;
 
 		scmi_sensors->info[type] =
@@ -335,8 +339,6 @@ static int scmi_hwmon_probe(struct scmi_
 		return PTR_ERR(hwdev);
 
 	for (i = 0; i < nr_count_temp; i++) {
-		int ret;
-
 		sensor = *(scmi_sensors->info[hwmon_temp] + i);
 		if (!sensor)
 			continue;
author maintainer
#751 lore raw

PATCH 750/1005 hwmon: (scmi) Enable temperature sensors using their sensor IDs

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Xu Rao <[email protected]>

commit 3ae1af2faad93276645d7620261643457daec73b upstream.

scmi_hwmon_probe() groups sensors by hwmon type, so the index in scmi_sensors->info[hwmon_temp] is not necessarily the SCMI sensor ID. Passing that index to config_set() targets a different sensor if the platform exposes non-temperature sensors ahead of temperature sensors. The intended temperature sensor can remain disabled, causing subsequent readings to fail. If configuring the wrong sensor fails, thermal registration of the intended sensor is also skipped.

Use the firmware sensor ID, as the read and thermal registration paths already do, so temperature sensors are enabled correctly.

The patch was reviewed and the commit message expanded with OpenCode AI assistance.

Fixes 72804d1631b3 ("hwmon: (scmi) Enable sensors to assure they can be read")
---
 drivers/hwmon/scmi-hwmon.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/scmi-hwmon.c +1 -1
@@ -343,7 +343,7 @@ static int scmi_hwmon_probe(struct scmi_
 		if (!sensor)
 			continue;
 
-		ret = sensor_ops->config_set(ph, i, sensor_config);
+		ret = sensor_ops->config_set(ph, sensor->id, sensor_config);
 		if (ret) {
 			dev_err(dev, "Error enabling sensor %s. err=%d\n",
 				sensor->name, ret);
author maintainer
#752 lore raw

PATCH 751/1005 hwmon: (scmi) Configure sensors before exposing channels

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Sudeep Holla <[email protected]>

commit 68af85b730f9a9e5f66c96ba861a66da08cfa5a9 upstream.

SCMI hwmon enables sensors with SENSOR_CONFIG_SET, but only after registering the hwmon device and only for temperature sensors. This leaves other sensor classes disabled on firmware that defaults sensors to off, and exposes temperature channels before they are ready.

Configure each supported sensor while building the channel list, before registering the hwmon device. Leave failed sensors out of the list so their channels remain hidden, while continuing with other sensors.

---
 drivers/hwmon/scmi-hwmon.c |   13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)
drivers/hwmon/scmi-hwmon.c +6 -7
@@ -327,6 +327,12 @@ static int scmi_hwmon_probe(struct scmi_
 		case ENERGY:
 			type = scmi_types[sensor->type];
 			idx = --nr_count[type];
+			ret = sensor_ops->config_set(ph, sensor->id, sensor_config);
+			if (ret) {
+				dev_err(dev, "Error enabling sensor %s. err=%d\n",
+					sensor->name, ret);
+				continue;
+			}
 			*(scmi_sensors->info[type] + idx) = sensor;
 			break;
 		}
@@ -343,13 +349,6 @@ static int scmi_hwmon_probe(struct scmi_
 		if (!sensor)
 			continue;
 
-		ret = sensor_ops->config_set(ph, sensor->id, sensor_config);
-		if (ret) {
-			dev_err(dev, "Error enabling sensor %s. err=%d\n",
-				sensor->name, ret);
-			continue;
-		}
-
 		/*
 		 * Warn on any misconfiguration related to thermal zones but
 		 * bail out of probing only on memory errors.
author maintainer
#753 lore raw

PATCH 752/1005 hwmon: (max31760) Fix the local temperature limit registers

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Stanislav Aleksandrov <[email protected]>

commit 028ed93145d9be88eee670088ef13482b5d36c1a upstream.

temp2_max and temp2_crit use each other's registers, so reading them shows the local limits swapped and writing temp2_max changes the overtemperature (SHDN) threshold.

Use the high limit (0x0C) for temp2_max and the overtemperature limit (0x08) for temp2_crit.

Fixes 38b04ad02d0d ("drivers: hwmon: Add max31760 fan speed controller driver")
---
 drivers/hwmon/max31760.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hwmon/max31760.c +2 -2
@@ -27,8 +27,8 @@
 
 #define REG_TACH(ch)		(0x52 + (ch) * 2)
 #define REG_TEMP_INPUT(ch)	(0x56 + (ch) * 2)
-#define REG_TEMP_MAX(ch)	(0x06 + (ch) * 2)
-#define REG_TEMP_CRIT(ch)	(0x0A + (ch) * 2)
+#define REG_TEMP_MAX(ch)	((ch) ? 0x0C : 0x06)
+#define REG_TEMP_CRIT(ch)	((ch) ? 0x08 : 0x0A)
 
 #define TEMP11_FROM_REG(reg)	((reg) / 32 * 125)
 #define TEMP11_TO_REG(val)	(DIV_ROUND_CLOSEST(clamp_val((val), -128000, \
author maintainer
#754 lore raw

PATCH 753/1005 hwmon: (max31760) Leave standby mode at probe

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Stanislav Aleksandrov <[email protected]>

commit 95bddc5252a4c0a2ed9d62e7e53a3461265d9603 upstream.

The driver never clears the standby bit (CR2_STBY) during probe. While max31760_resume() clears this bit on resume, probe only configured CR2_ALERTS.

If the chip was left in standby (for example, by boot firmware or a previously running OS before a warm reboot), it remains in standby:
temperature sensing, fan speed counting, and PWM output are halted. This occurs on the Samsung Galaxy XR, where the bootloader places the chip in standby during boot.

Clear CR2_STBY alongside setting CR2_ALERTS in probe.

Fixes 38b04ad02d0d ("drivers: hwmon: Add max31760 fan speed controller driver")
---
 drivers/hwmon/max31760.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/hwmon/max31760.c +3 -2
@@ -533,8 +533,9 @@ static int max31760_probe(struct i2c_cli
 
 	dev_set_drvdata(dev, state);
 
-	/* Set alert output to comparator mode */
-	ret = regmap_set_bits(state->regmap, REG_CR2, CR2_ALERTS);
+	/* Leave standby mode, set alert output to comparator mode */
+	ret = regmap_update_bits(state->regmap, REG_CR2, CR2_STBY | CR2_ALERTS,
+				 CR2_ALERTS);
 	if (ret)
 		return dev_err_probe(dev, ret, "cannot write register\n");
 
author maintainer
#755 lore raw

PATCH 754/1005 hwmon: (max31760) Report 0 RPM before the first fan speed measurement

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Stanislav Aleksandrov <[email protected]>

commit 33d58cbf2ab26bda81bc3052158d8b9867d5b9a6 upstream.

The tachometer count registers initialize to 0 until the first measurement cycle completes after power-on. To prevent division by zero, tach_to_rpm() clamped tach == 0 to 1, causing it to compute and report 3,000,000 RPM (60 * 100000 / 1 / 2).

Return 0 RPM when tach == 0 instead.

Fixes 38b04ad02d0d ("drivers: hwmon: Add max31760 fan speed controller driver")
---
 drivers/hwmon/max31760.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/hwmon/max31760.c +2 -1
@@ -68,8 +68,9 @@ static const int max31760_pwm_freq[] = {
 
 static int tach_to_rpm(u16 tach)
 {
+	/* The count is 0 until the first measurement */
 	if (tach == 0)
-		tach = 1;
+		return 0;
 
 	return 60 * 100000 / tach / 2;
 }
author maintainer
#756 lore raw

PATCH 755/1005 s390/dasd: Fix wrong free and refcount leak in build_check_tcw error path

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Stefan Haberland <[email protected]>

commit df56f7a6c20a5eb2794c0a7391bde50ba7c8c54b upstream.

dasd_eckd_build_check_tcw() allocates its request with dasd_fmalloc_request(), but its out_err path frees it with dasd_sfree_request(). The latter uses a different pool and therefor, leading to invalid pointer arithmetic and a crash.
Use the matching dasd_ffree_request() instead.

The same error path also leaves start_priv->count incremented without ever decrementing it again.
This leaks a permanent reference on every build failure. Decrement it before freeing the request.

Fixes 8fd575200db5 ("s390/dasd: Add new ioctl BIODASDCHECKFMT")
Fixes 5e2b17e712cf ("s390/dasd: Add dynamic formatting support for ESE volumes")
---
 drivers/s390/block/dasd_eckd.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/s390/block/dasd_eckd.c +2 -1
@@ -2780,7 +2780,8 @@ dasd_eckd_build_check_tcw(struct dasd_de
 	return cqr;
 
 out_err:
-	dasd_sfree_request(cqr, startdev);
+	start_priv->count--;
+	dasd_ffree_request(cqr, startdev);
 
 	return ERR_PTR(rc);
 }
author maintainer
#757 lore raw

PATCH 756/1005 s390/dasd: Dont trust userspace-supplied result field in format check

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Stefan Haberland <[email protected]>

commit 7cc2dda4f7aaf596c1796184649007151ff98f8d upstream.

BIODASDCHECKFMT used to copy the entire format_check_t struct from userspace, including the result/unit/rec/num_records/blksize/ key_length fields that are output fields only. dasd_eckd_format_evaluate_tracks() relies on cdata->result being zero to decide whether to apply an index correction (i--/pos--) after a successful check. A caller that pre-sets result to a non-zero value can suppress that correction, leaving pos advanced past the last valid entry; the (partially out-of-bounds) fmt_buffer[pos] fields are then copied back to userspace, leaking heap contents.

Only expect is an Input field; copy just that member in and zero the rest of cdata.

---
 drivers/s390/block/dasd_ioctl.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/s390/block/dasd_ioctl.c +3 -1
@@ -303,7 +303,9 @@ static int dasd_ioctl_check_format(struc
 		goto out_err;
 	}
 
-	if (copy_from_user(&cdata, argp, sizeof(cdata))) {
+	/* copy only input fields, clear the rest */
+	memset(&cdata, 0, sizeof(cdata));
+	if (copy_from_user(&cdata.expect, argp, sizeof(cdata.expect))) {
 		rc = -EFAULT;
 		goto out_err;
 	}
author maintainer
#758 lore raw

PATCH 757/1005 sched/deadline: Fix spurious -EPERM for migration-disabled tasks

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Andrea Parri <[email protected]>

commit 6616bffa9b52da1338cf8bff9882404e02b9e361 upstream.

sched_setattr() can refuse to make a task SCHED_DEADLINE with -EPERM, even though the task's affinity covers the whole root domain. A retry can succeed, but the error blames an affinity the task does not have.

__sched_setscheduler() tests p->cpus_ptr, which is not always the task's affinity. When a task is scheduled out inside a migrate_disable() section, migrate_disable_switch() points p->cpus_ptr at the current CPU until migrate_enable(). On PREEMPT_RT every spinlock_t holder is in such a section, so ordinary kernel work opens the window. Elsewhere, seccomp filters run in one.

Test p->cpus_mask instead, which keeps the task's affinity and is what sched_getaffinity() reports. This should be safe because an admitted task's cpus_mask covers the root domain, so set_cpus_allowed_dl() moves no bandwidth when migrate_enable() restores p->cpus_ptr.

The following program, run as root, had 553679, 453720 and 424623 of its 1000000 requests refused on three boots of a 4-CPU PREEMPT_RT guest, and 236182, 217174 and 237183 without PREEMPT_RT. With this applied the count is 0, also with lockdep, and a task pinned to one CPU is still refused:

  #define _GNU_SOURCE
  #include <errno.h>
  #include <linux/filter.h>
  #include <linux/seccomp.h>
  #include <pthread.h>
  #include <stddef.h>
  #include <stdint.h>
  #include <stdio.h>
  #include <sys/syscall.h>
  #include <unistd.h>

  #define REQUESTS 1000000
  #define INSNS 300

  struct attr {
      uint32_t size, policy;
      uint64_t flags;
      int32_t nice;
      uint32_t prio;
      uint64_t runtime, deadline, period;
  };

static volatile int stop;
static volatile pid_t target;

  static long set(struct attr a)
  {
      a.size = sizeof(a);
      return syscall(SYS_sched_setattr, target, &a, 0);
  }

  static void *worker(void *arg)
  {
      struct sock_filter f[INSNS + 1];
      struct sock_fprog prog = { .len = INSNS + 1, .filter = f };
      int i;
      /* Reading the arguments keeps seccomp from caching the result */
      for (i = 0; i < INSNS; i++)
          f[i] = (struct sock_filter)
              BPF_STMT(BPF_LD | BPF_W | BPF_ABS,
                       offsetof(struct seccomp_data, args));
      f[INSNS] = (struct sock_filter)
          BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW);
      syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog);

      target = syscall(SYS_gettid);
      while (!stop)
          syscall(SYS_getppid);
      return arg;

}

  static void *hog(void *arg)
  {
      while (!stop)
          ;
      return arg;
  }

  int main(void)
  {
      pthread_t t[9];
      long refused = 0;
      int i;
      pthread_create(&t[0], NULL, worker, NULL);
      while (!target)
          usleep(100);
      for (i = 1; i < 9; i++)
          pthread_create(&t[i], NULL, hog, NULL);
      for (i = 0; i < REQUESTS; i++) {
          /* SCHED_DEADLINE, 2us every 1s */
          if (set((struct attr){ .policy = 6, .runtime = 2000,
                                 .deadline = 1000000000,
                                 .period = 1000000000 }) && errno == EPERM)
              refused++;
          set((struct attr){ .policy = 0 }); /* SCHED_OTHER */
      }
      stop = 1;
      for (i = 0; i < 9; i++)
          pthread_join(t[i], NULL);
      printf("%ld of %d requests refused\n", refused, REQUESTS);
      return 0;

}

An LLM helped find this bug and write this patch and its test.

---
 kernel/sched/syscalls.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/sched/syscalls.c +1 -1
@@ -628,7 +628,7 @@ change:
 			 * the entire root_domain to become SCHED_DEADLINE. We
 			 * will also fail if there's no bandwidth available.
 			 */
-			if (!cpumask_subset(span, p->cpus_ptr) ||
+			if (!cpumask_subset(span, &p->cpus_mask) ||
 			    rq->rd->dl_bw.bw == 0) {
 				retval = -EPERM;
 				goto unlock;
author maintainer
#759 lore raw

PATCH 758/1005 sched/uclamp: Reject clamp values above SCHED_CAPACITY_SCALE

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Andrea Parri <[email protected]>

commit 8127ec8458df29bd702db602473042ccb9e619b9 upstream.

sched_setattr() accepts sched_util_min and sched_util_max values that do not fit in uclamp_se::value. A single thread can do:

sched_setattr(max = 800) returns 0
sched_setattr(min = 0xfffffffe) returns 0
sched_getattr() min=2046 max=800

which leaves the minimum above both SCHED_CAPACITY_SCALE and the task's own maximum.

The range check in uclamp_validate() relies on the + 1 wrapping -1, the reset value, to 0:

if (util_min + 1 > SCHED_CAPACITY_SCALE + 1)

That only works for an unsigned type. util_min and util_max are int and SCHED_CAPACITY_SCALE is a long, so every negative value passes the check, and so does INT_MAX, whose + 1 wraps.

uclamp_se_set() then truncates what got through to the 11 bits of uclamp_se::value, but computes the bucket from the full value. A minimum of 0xfffff800 is stored as 0 in the top bucket, where uclamp_rq_max_value() takes it for the highest active clamp once a higher value leaves the rq. The rq clamp falls below what the remaining tasks requested, and emptying their bucket trips the WARN_ON_ONCE() in uclamp_rq_dec_id(), without any privilege:

  WARNING: kernel/sched/core.c:1862 at dequeue_task+0x2a3/0x2b0, CPU#0: repro/126
  Call Trace:
   __schedule+0x933/0x1320
   schedule+0x36/0x100
   do_nanosleep+0x61/0x190
   hrtimer_nanosleep+0xb5/0x1d0

Make util_min and util_max unsigned int, so that -1 is the only value that wraps. The pair check below is unaffected, since it skips -1 explicitly and anything else is at most SCHED_CAPACITY_SCALE by then.

Requests that were only accepted because of this now fail with -EINVAL.

The following program triggers the warning when run by any user outside a child cpu cgroup. With this applied, its 0xfffff800 request fails with -EINVAL and the warning no longer appears:

  #define _GNU_SOURCE
  #include <pthread.h>
  #include <sched.h>
  #include <stdint.h>
  #include <sys/syscall.h>
  #include <time.h>
  #include <unistd.h>

  struct attr {
      uint32_t size, policy;
      uint64_t flags;
      int32_t nice;
      uint32_t prio;
      uint64_t runtime, deadline, period;
      uint32_t util_min, util_max;
  };

static volatile int stop;

  static void set_min(uint32_t v)
  {
      /* KEEP_POLICY | KEEP_PARAMS | UTIL_CLAMP_MIN */
      struct attr a = { .size = sizeof(a), .flags = 0x38, .util_min = v };
      syscall(SYS_sched_setattr, 0, &a, 0);

}

  static void burn(long us)
  {
      struct timespec s, n;
      clock_gettime(CLOCK_MONOTONIC, &s);
      do
          clock_gettime(CLOCK_MONOTONIC, &n);
      while ((n.tv_sec - s.tv_sec) * 1000000 +
             (n.tv_nsec - s.tv_nsec) / 1000 < us);

}

  static void *bogus(void *arg)
  {
      set_min(0xfffff800);
      while (!stop)
          burn(1000);
      return arg;
  }

  static void *worker(void *arg)
  {
      long v = (long)arg;
      set_min(v);
      while (!stop) {
          burn(v == 800 ? 300 : 1500);
          usleep(100);
      }
      return arg;

}

  int main(void)
  {
      pthread_t t[3];
      cpu_set_t c;
      int i;
      CPU_ZERO(&c);
      CPU_SET(0, &c);
      sched_setaffinity(0, sizeof(c), &c);
      pthread_create(&t[0], NULL, bogus, NULL);
      usleep(50000);
      pthread_create(&t[1], NULL, worker, (void *)500L);
      pthread_create(&t[2], NULL, worker, (void *)800L);
      sleep(15);
      stop = 1;
      for (i = 0; i < 3; i++)
          pthread_join(t[i], NULL);
      return 0;

}

An LLM helped find the warning and write this patch and its tests.

---
 kernel/sched/syscalls.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/sched/syscalls.c +2 -2
@@ -318,8 +318,8 @@ static inline void __setscheduler_dl_pi(
 static int uclamp_validate(struct task_struct *p,
 			   const struct sched_attr *attr)
 {
-	int util_min = p->uclamp_req[UCLAMP_MIN].value;
-	int util_max = p->uclamp_req[UCLAMP_MAX].value;
+	unsigned int util_min = p->uclamp_req[UCLAMP_MIN].value;
+	unsigned int util_max = p->uclamp_req[UCLAMP_MAX].value;
 
 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) {
 		util_min = attr->sched_util_min;
author maintainer
#760 lore raw

PATCH 759/1005 sched/core: Fix cpuset_mutex double unlock in __sched_setscheduler()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Andrea Parri <[email protected]>

commit f7141257dd67d4936f906a6cfd1d0007721f6898 upstream.

A sched_setattr() with SCHED_FLAG_KEEP_POLICY on a SCHED_DEADLINE task unlocks cpuset_mutex twice if the task's policy changes concurrently:

WARNING: bad unlock balance detected! 7.4.0-rc1 #1 Not tainted
-------------------------------------
repro/126 is trying to release lock (cpuset_mutex) at:

  [<ffffffff9a17cacc>] __sched_setscheduler+0x9cc/0xc40
  but there are no more locks to release!
  ...
  Call Trace:
   print_unlock_imbalance_bug.part.0+0xfb/0x110
   lock_release+0x286/0x2e0
   __mutex_unlock_slowpath+0x1a/0x400
   __sched_setscheduler+0x9cc/0xc40
   __x64_sys_sched_setattr+0xa3/0x1b0
   do_syscall_64+0x106/0x5f0
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

__sched_setscheduler() samples p->policy before taking any lock, and restarts from the recheck label if p->policy differs under the rq lock. The restart drops cpuset_mutex but leaves cpuset_locked set, so a pass that no longer needs the mutex still unlocks it on its way out:

CPU 1 CPU 2
__sched_setscheduler(KEEP_POLICY)

    policy = p->policy /* DEADLINE */
                                       __sched_setscheduler(SCHED_OTHER)
                                         p->policy = SCHED_OTHER
    cpuset_locked = true
    cpuset_lock()
    rq = task_rq_lock(p)
    oldpolicy != p->policy
      cpuset_unlock()
      goto recheck
    /* no cpuset_lock() this time */
    ...
    if (cpuset_locked)
      cpuset_unlock()

Without CONFIG_DEBUG_MUTEXES, or CONFIG_DEBUG_RT_MUTEXES on PREEMPT_RT, nothing warns. The second unlock still clears the owner field regardless of who holds the mutex, so another task can lose cpuset_mutex inside its critical section. Entering SCHED_DEADLINE needs CAP_SYS_NICE, but a racing caller that owns the task does not need it if it samples a policy other than SCHED_DEADLINE.

Clear cpuset_locked when dropping the mutex for the restart. This should be safe because the flag is only tested on the paths leaving the next pass, after that pass has set it again if it took the mutex.

The following program, run as root, reproduces the splat, which no longer appears with this applied. On PREEMPT_RT it crashes the kernel within seconds, which this also fixes:

  #define _GNU_SOURCE
  #include <pthread.h>
  #include <stdint.h>
  #include <sys/syscall.h>
  #include <unistd.h>

  struct attr {
      uint32_t size, policy;
      uint64_t flags;
      int32_t nice;
      uint32_t prio;
      uint64_t runtime, deadline, period;
  };

static volatile int stop;
static volatile pid_t target;

  static void set(struct attr a)
  {
      a.size = sizeof(a);
      syscall(SYS_sched_setattr, target, &a, 0);
  }

  static void *sleeper(void *arg)
  {
      target = syscall(SYS_gettid);
      while (!stop)
          usleep(1000);
      return arg;
  }

  static void *switcher(void *arg)
  {
      while (!stop) {
          /* SCHED_DEADLINE, 2us every 1s */
          set((struct attr){ .policy = 6, .runtime = 2000,
                             .deadline = 1000000000,
                             .period = 1000000000 });
          set((struct attr){ .policy = 0 }); /* SCHED_OTHER */
      }
      return arg;
  }

  static void *racer(void *arg)
  {
      /* KEEP_POLICY | KEEP_PARAMS */
      while (!stop)
          set((struct attr){ .flags = 0x18 });
      return arg;
  }

  int main(void)
  {
      pthread_t t[5];
      int i;
      pthread_create(&t[0], NULL, sleeper, NULL);
      while (!target)
          usleep(100);
      pthread_create(&t[1], NULL, switcher, NULL);
      for (i = 2; i < 5; i++)
          pthread_create(&t[i], NULL, racer, NULL);
      sleep(30);
      stop = 1;
      for (i = 0; i < 5; i++)
          pthread_join(t[i], NULL);
      return 0;

}

An LLM helped find the PREEMPT_RT crash and write this patch and its test.

---
 kernel/sched/syscalls.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/sched/syscalls.c +3 -1
@@ -640,8 +640,10 @@ change:
 	if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
 		policy = oldpolicy = -1;
 		task_rq_unlock(rq, p, &rf);
-		if (cpuset_locked)
+		if (cpuset_locked) {
 			cpuset_unlock();
+			cpuset_locked = false;
+		}
 		goto recheck;
 	}
 
author maintainer
#761 lore raw

PATCH 760/1005 sched/core: Do not touch SMT siblings that have not joined the core yet

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Seiji Nishikawa <[email protected]>

commit ec6f6731538e0d45872eb279fdeb477bed152d6f upstream.

When a CPU comes online, it is added to cpu_smt_mask() of its siblings before sched_core_cpu_starting() sets its rq->core to the core leader. For example, on x86, ap_starting() calls set_cpu_sibling_map() first, and calls notify_cpu_starting() after that. This order is intended.

Before sched_core_cpu_starting() runs, rq->core of the new CPU still points to its own rq. But rq->core_enabled of the new CPU is already set. __sched_core_flip() sets it for all possible CPUs, also for offline CPUs, and CPU offline does not clear it. So __rq_lockp() of the new CPU returns its own rq->__lock. It does not return the core wide lock.

If a sibling CPU runs pick_next_task() for SCHED_CORE at this time, it checks all CPUs in cpu_smt_mask(). It calls update_rq_clock() and pick_task() for the rq of the new CPU. But it holds only its own core lock, not the lock of the new CPU. Then lockdep shows this warning in update_rq_clock().

  debug_locks && !(lock_is_held(&(__rq_lockp(rq))->dep_map) != 0)
  WARNING: kernel/sched/sched.h:1666 at update_rq_clock+0x40a/0xd20 kernel/sched/core.c:875, CPU#0: syz-executor251/5712
  Call Trace:
   <TASK>
   pick_next_task kernel/sched/core.c:6375 [inline]
   __schedule+0x1c69/0x6920 kernel/sched/core.c:7199
   preempt_schedule_irq+0x4e/0x90 kernel/sched/core.c:7606

The next loops in pick_next_task() also change rq_i->core_pick of this rq, and can call resched_curr() for it, without its lock. resched_curr() has the same lockdep_assert_rq_held() check. __sched_core_account_forceidle() also checks all CPUs in the same mask.

CPU offline does not have this problem. remove_siblinginfo() and sched_core_cpu_dying() both run in take_cpu_down() under stop_machine. So no sibling CPU can be in pick_next_task() at that time.

Fix this. In these loops, skip a sibling CPU if its rq->core is different from our rq->core. At run time, rq->core of a CPU is changed by sched_core_cpu_starting(), sched_core_cpu_deactivate() and sched_core_cpu_dying(). The first two hold sched_core_lock(), and sched_core_lock() takes the rq locks of all CPUs in the SMT mask. The last one runs under stop_machine, as written above. So while we hold our core lock, the result of this check does not change. A CPU that is not in the core yet will pick its own tasks. The comment in the reschedule loop of pick_next_task() already expects this case.

I tested this with the syzbot C reproducer in QEMU. The two vCPUs were SMT siblings (-smp 2,sockets=1,cores=1,threads=2). Without this patch, the warning came after about 100 seconds. Just before the warning, a debug print showed that the loop on CPU 0 saw CPU 1 with rq->core pointing to CPU 1 itself, and cpu_online() was false for CPU 1. With this patch, the same state still happened, but there was no warning in more than 2 hours.

---
 kernel/sched/core.c       |    9 +++------
 kernel/sched/core_sched.c |    3 +--
 kernel/sched/sched.h      |   19 +++++++++++++++++++
 3 files changed, 23 insertions(+), 8 deletions(-)
kernel/sched/core.c +3 -6
@@ -6251,7 +6251,6 @@ pick_next_task(struct rq *rq, struct rq_
 	__must_hold(__rq_lockp(rq))
 {
 	struct task_struct *next, *p, *max;
-	const struct cpumask *smt_mask;
 	bool fi_before = false;
 	bool core_clock_updated = (rq == rq->core);
 	unsigned long cookie;
@@ -6301,8 +6300,6 @@ pick_next_task(struct rq *rq, struct rq_
 
 	prev_balance(rq, rf);
 
-	smt_mask = cpu_smt_mask(cpu);
-
 restart:
 	need_sync |= !!rq->core->core_cookie;
 
@@ -6368,7 +6365,7 @@ restart:
 	 * Tie-break prio towards the current CPU
 	 */
 	max = NULL;
-	for_each_cpu_wrap(i, smt_mask, cpu) {
+	for_each_core_cpu_wrap(i, rq) {
 		rq_i = cpu_rq(i);
 
 		/*
@@ -6401,7 +6398,7 @@ restart:
 	 * For each thread: try and find a runnable task that matches @max or
 	 * force idle.
 	 */
-	for_each_cpu(i, smt_mask) {
+	for_each_core_cpu(i, rq) {
 		rq_i = cpu_rq(i);
 		p = rq_i->core_pick;
 
@@ -6447,7 +6444,7 @@ restart:
 	 * their task. This ensures there is no inter-sibling overlap between
 	 * non-matching user state.
 	 */
-	for_each_cpu(i, smt_mask) {
+	for_each_core_cpu(i, rq) {
 		rq_i = cpu_rq(i);
 
 		/*
kernel/sched/core_sched.c +1 -2
@@ -241,7 +241,6 @@ out:
 /* REQUIRES: rq->core's clock recently updated. */
 void __sched_core_account_forceidle(struct rq *rq)
 {
-	const struct cpumask *smt_mask = cpu_smt_mask(cpu_of(rq));
 	u64 delta, now = rq_clock(rq->core);
 	struct rq *rq_i;
 	struct task_struct *p;
@@ -273,7 +272,7 @@ void __sched_core_account_forceidle(stru
 		delta = div_u64(delta, rq->core->core_forceidle_occupation);
 	}
 
-	for_each_cpu(i, smt_mask) {
+	for_each_core_cpu(i, rq) {
 		rq_i = cpu_rq(i);
 		p = rq_i->core_pick ?: rq_i->curr;
 
kernel/sched/sched.h +19 -0
@@ -1514,6 +1514,25 @@ static inline raw_spinlock_t *__rq_lockp
 	return &rq->__lock;
 }
 
+/*
+ * A CPU coming online is set in cpu_smt_mask() before
+ * sched_core_cpu_starting() links its rq->core to the core leader.
+ * Until then it does not share the core-wide lock, so it must not be
+ * touched as part of the core.
+ */
+static inline bool sched_core_sibling(struct rq *rq, struct rq *rq_i)
+{
+	return rq_i->core == rq->core;
+}
+
+#define for_each_core_cpu(i, rq) \
+	for_each_cpu(i, cpu_smt_mask(rq->cpu)) \
+		if (sched_core_sibling(rq, cpu_rq(i)))
+
+#define for_each_core_cpu_wrap(i, rq) \
+	for_each_cpu_wrap(i, cpu_smt_mask(rq->cpu), rq->cpu) \
+		if (sched_core_sibling(rq, cpu_rq(i)))
+
 extern bool
 cfs_prio_less(const struct task_struct *a, const struct task_struct *b, bool fi);
 
author maintainer
#762 lore raw

PATCH 761/1005 sched_ext: Fix stale pick when the donor changes during dispatch

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tejun Heo <[email protected]>

commit 9ce6fca02867911ba79bc3664219effe8c7be8f4 upstream.

Dispatch takes rq->donor as @prev and can drop the rq lock. With proxy execution, @prev may not be the running task, and another CPU can reset the donor to rq->curr meanwhile, through proxy_needs_return() on a wakeup or sched_proxy_block_task() on a class or scheduler change. The wakeup case:

1. dispatch_one() drops the rq lock, e.g. to move a task from another CPU.
2. Another CPU wakes the donor, which proxy execution migrated to this CPU. proxy_needs_return() dequeues it and resets the donor to rq->curr, and the wakeup enqueues it, possibly on another CPU.
3. dispatch_one() sees @prev queued and returns SCX_DSP_PREV.
4. do_pick_task_scx() returns @prev, and this CPU runs a task that is queued on another rq.

Under core scheduling, the core pick runs dispatch for the sibling rqs with each sibling's donor as @prev, and a sibling can switch @prev out while dispatch has the lock dropped.

Whatever dispatch concluded, and whatever it does with @prev after the drop, is about a task the rq no longer owns, whether it keeps @prev running or hands it to ops.dispatch().

rq_modified_above() catches the change only when rq->curr is in a class above ext, and the dl_server pick skips that check. dispatch_core_pick() retries after a lock drop, but by then dispatch has used @prev.

Restart the pick when @prev is no longer the donor. dispatch_one() tests after each step that can drop the lock, and scx_dispatch_sched() decides per ops.dispatch() call whether to hand @prev over, which also covers a class or scheduler change across a drop.

With proxy execution alone, the donor only ever changes to rq->curr during a pick, so the retried pick can't go stale again. Under core scheduling, the restart goes through the core pick, which already retries after any lock drop.

7a3a6bfbd62a ("sched: Rework prev_balance() to avoid stale prev references") closed the same window in prev_balance() by reading rq->donor instead of taking @prev. That doesn't work here, as dispatch never evaluated the new donor, which may not even be a sched_ext task.

Verified with synthetic reproducers for both cases.

v2: Also cover rq lock drops inside dispatch (sashiko).

v3: Don't keep a stale @prev after ops.dispatch() (sashiko).

v4: Also cover a sibling switching @prev out under core scheduling. Retitle.

Fixes 7b0888b7cc19 ("sched_ext: Implement core-sched support")
Fixes c6fe97c34a1a ("sched: Allow enabling proxy exec with sched_ext")
Cc [email protected] # v6.12+
---
 kernel/sched/ext/ext.c     |   10 ++++++++++
 kernel/sched/ext/inlines.h |   37 +++++++++++++++++++++++++++++++++----
 2 files changed, 43 insertions(+), 4 deletions(-)
kernel/sched/ext/ext.c +10 -0
@@ -3007,6 +3007,12 @@ static enum scx_dsp_verdict dispatch_one
 		rq->scx.cpu_released = false;
 	}
 
+	/* the ecaps sync may have dropped the rq lock */
+	if (scx_dsp_prev_stale(rq, prev)) {
+		verdict = SCX_DSP_RETRY;
+		goto has_tasks;
+	}
+
 	if (prev->sched_class == &ext_sched_class) {
 		update_curr_scx(rq);
 
@@ -3034,6 +3040,10 @@ static enum scx_dsp_verdict dispatch_one
 	}
 
 	verdict = scx_dispatch_sched(root_sch, rq, prev, false);
+
+	/* scx_dispatch_sched() may have dropped the rq lock */
+	if (scx_dsp_prev_stale(rq, prev))
+		verdict = SCX_DSP_RETRY;
 	if (verdict != SCX_DSP_NONE)
 		goto has_tasks;
 
kernel/sched/ext/inlines.h +33 -4
@@ -18,9 +18,32 @@ enum scx_dsp_verdict {
 	SCX_DSP_NONE,		/* nothing to run */
 	SCX_DSP_LOCAL,		/* local DSQ has tasks */
 	SCX_DSP_PREV,		/* keep running @prev */
-	SCX_DSP_RETRY,		/* pick helpers only: restart the pick */
+	SCX_DSP_RETRY,		/* restart the pick */
 };
 
+/**
+ * scx_dsp_prev_stale - Test whether dispatch's @prev went stale
+ * @rq: rq being dispatched for
+ * @prev: @rq's donor when dispatch started
+ *
+ * @prev can stop being @rq's donor while dispatch has the rq lock dropped. With
+ * proxy execution, @prev may not be the running task, and another CPU can reset
+ * the donor to rq->curr. With core scheduling, the core pick runs dispatch for
+ * the sibling rqs too, and a sibling can switch @prev out. Dispatch restarts
+ * the pick when that happened and doesn't hand the old donor to the BPF
+ * scheduler.
+ *
+ * With proxy execution alone, the donor only ever changes to rq->curr during a
+ * pick. Only __schedule() on this CPU sets a different donor, after the pick,
+ * so the restarted pick takes rq->curr as @prev and can't go stale again. Under
+ * core scheduling, the restart goes through the core pick, which already
+ * retries whenever dispatch dropped the lock.
+ */
+static inline bool scx_dsp_prev_stale(struct rq *rq, struct task_struct *prev)
+{
+	return (sched_proxy_exec() || sched_core_enabled(rq)) && unlikely(prev != rq->donor);
+}
+
 /*
  * One user of this function is scx_bpf_sub_dispatch() which can be called
  * recursively as sub-sched dispatches nest. Always inline to reduce stack usage
@@ -33,8 +56,7 @@ scx_dispatch_sched(struct scx_sched *sch
 	struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
 	int nr_loops = SCX_DSP_MAX_LOOPS;
 	s32 cpu = cpu_of(rq);
-	bool prev_on_sch = (prev->sched_class == &ext_sched_class) &&
-		scx_task_on_sched(sch, prev);
+	bool prev_on_sch;
 
 	if (scx_consume_global_dsq(sch, rq))
 		return SCX_DSP_LOCAL;
@@ -106,6 +128,11 @@ scx_dispatch_sched(struct scx_sched *sch
 			rq->scx.sub_dispatch_prev = prev;
 #endif
 
+		/* the dispatch so far may have dropped the rq lock */
+		prev_on_sch = !scx_dsp_prev_stale(rq, prev) &&
+			      prev->sched_class == &ext_sched_class &&
+			      scx_task_on_sched(sch, prev);
+
 		SCX_CALL_OP(sch, dispatch, rq, scx_cpu_arg(cpu),
 			    prev_on_sch ? prev : NULL);
 
@@ -116,7 +143,9 @@ scx_dispatch_sched(struct scx_sched *sch
 
 		scx_flush_dispatch_buf(sch, rq);
 
-		if ((prev->scx.flags & SCX_TASK_QUEUED) && prev->scx.slice)
+		/* ops.dispatch() and the flush may have dropped the rq lock */
+		if (!scx_dsp_prev_stale(rq, prev) &&
+		    (prev->scx.flags & SCX_TASK_QUEUED) && prev->scx.slice)
 			return SCX_DSP_PREV;
 		if (rq->scx.local_dsq.nr)
 			return SCX_DSP_LOCAL;
author maintainer
#763 lore raw

PATCH 762/1005 sched_ext: Factor out drain_offline_rq()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tejun Heo <[email protected]>

commit 1826e5aa068cf6c21791773f160b4a2ce5d5f9a5 upstream.

Factor drain_offline_rq() out of rq_offline_scx() so that the drain can move to handle_hotplug() in the following patch, which removes the rq_online and rq_offline hooks. The drain is the rescue flush and the re-enqueue of an offline cpu's tasks onto its local DSQ. No functional change.

---
 kernel/sched/ext/ext.c |   35 ++++++++++++++++++++---------------
 kernel/sched/sched.h   |    2 +-
 2 files changed, 21 insertions(+), 16 deletions(-)
kernel/sched/ext/ext.c +20 -15
@@ -2157,7 +2157,7 @@ static void set_task_runnable(struct rq
 	}
 
 	/*
-	 * list_add_tail() must be used. scx_bypass() and rq_offline_scx()
+	 * list_add_tail() must be used. scx_bypass() and drain_offline_rq()
 	 * depend on tasks being appended to the runnable_list.
 	 */
 	list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list);
@@ -3806,6 +3806,24 @@ static void set_cpus_allowed_scx(struct
 		scx_call_op_set_cpumask(sch, task_rq(p), p, (struct cpumask *)p->cpus_ptr);
 }
 
+static void drain_offline_rq(struct rq *rq)
+{
+	struct task_struct *p, *n;
+
+	scx_rescue_flush(rq);
+
+	/*
+	 * An offline CPU no longer calls ops.dispatch(). Re-enqueue its tasks
+	 * onto the local DSQ so that they run here and balance_push() moves
+	 * them off.
+	 */
+	list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list, scx.runnable_node) {
+		if (p->scx.dsq == &rq->scx.local_dsq)
+			continue;
+		guard(sched_change)(p, DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK);
+	}
+}
+
 static void handle_hotplug(struct rq *rq, bool online)
 {
 	struct scx_sched *sch = scx_root_protected();
@@ -3886,26 +3904,13 @@ static void rq_online_scx(struct rq *rq)
 
 static void rq_offline_scx(struct rq *rq)
 {
-	struct task_struct *p, *n;
-
 	rq->scx.flags &= ~SCX_RQ_ONLINE;
 
 	/* sched domain rebuilds call rq_offline with the CPU staying alive */
 	if (cpu_active(cpu_of(rq)))
 		return;
 
-	scx_rescue_flush(rq);
-
-	/*
-	 * An offline CPU no longer calls ops.dispatch(). Re-enqueue its tasks
-	 * onto the local DSQ so that they run here and balance_push() moves
-	 * them off.
-	 */
-	list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list, scx.runnable_node) {
-		if (p->scx.dsq == &rq->scx.local_dsq)
-			continue;
-		guard(sched_change)(p, DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK);
-	}
+	drain_offline_rq(rq);
 }
 
 static bool check_rq_for_timeouts(struct rq *rq)
kernel/sched/sched.h +1 -1
@@ -4247,7 +4247,7 @@ extern void balance_callbacks(struct rq
  * Typically this must be called while holding task_rq_lock, since most/all
  * properties are serialized under those locks. There are currently two
  * exceptions to this rule in sched/ext which only hold rq->lock: scx_bypass()
- * and rq_offline_scx().
+ * and drain_offline_rq().
  */
 
 /*
author maintainer
#764 lore raw

PATCH 763/1005 sched_ext: Read exit_kind before flushing in scx_flush_disable_work()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Kuba Piecuch <[email protected]>

commit 3133107d98057595c0af39ff907c852134926912 upstream.

scx_disable_workfn() sets exit_kind to SCX_EXIT_DONE before it tears the scheduler down. scx_flush_disable_work() reads exit_kind after syncing disable_irq_work and flushing disable_work, so it can observe DONE from a disable_work that was queued after its flush and return while the teardown is still running:

CPU A CPU B
----- -----
scx_vexit()

    scx_claim_exit() -> true
                                 bpf_struct_ops_map_link_detach()
                                   bpf_scx_unreg()
                                     scx_disable()
                                       scx_claim_exit() -> false
                                     scx_flush_disable_work()
                                       irq_work_sync()      // not queued
                                       kthread_flush_work() // not queued
    irq_work_queue()
  scx_disable_irq_workfn()
    kthread_queue_work()
  scx_disable_workfn()
    exit_kind = SCX_EXIT_DONE
    scx_root_disable()
                                       atomic_read() -> SCX_EXIT_DONE
                                   bpf_map_put()

Once bpf_scx_unreg() returns, its caller drops the struct_ops map reference, and the struct_ops trampolines can be freed while scx_root_disable() is still running and can still call into the BPF scheduler, e.g. ops.exit().

Read exit_kind before syncing and flushing, with acquire ordering paired with the atomic_try_cmpxchg() in scx_disable_workfn(). DONE is only set from disable_work, so once it is observed, the following kthread_flush_work() sees the queued work and waits for the teardown to finish.

This patch was created with the help of an AI coding assistant.

---
 kernel/sched/ext/ext.c |    9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
kernel/sched/ext/ext.c +8 -1
@@ -7131,10 +7131,17 @@ void scx_flush_disable_work(struct scx_s
 {
 	int kind;
 
+	/*
+	 * scx_disable_workfn() sets SCX_EXIT_DONE before tearing down. Read
+	 * exit_kind with acquire ordering (paired with atomic_try_cmpxchg() in
+	 * scx_disable_workfn()) before syncing and flushing so that, once DONE
+	 * is seen, the following flush observes the queued work and waits for
+	 * the teardown to finish.
+	 */
 	do {
+		kind = atomic_read_acquire(&sch->exit_kind);
 		irq_work_sync(&sch->disable_irq_work);
 		kthread_flush_work(&sch->disable_work);
-		kind = atomic_read(&sch->exit_kind);
 	} while (kind != SCX_EXIT_NONE && kind != SCX_EXIT_DONE);
 }
 
author maintainer
#765 lore raw

PATCH 764/1005 sctp: abort unordered partial delivery when its message is skipped

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tim Budding <[email protected]>

commit 05852c8b70f2291a50bb3f740a66ce9caf9cb98d upstream.

When an I-FORWARD-TSN skips unordered messages on a stream, sctp_intl_skip() only aborts the stream's unordered partial delivery if the MID being delivered is lower than the skipped MID. If the skipped message is the one being partially delivered, partial delivery stays in
progress: no PARTIAL_DELIVERY_ABORTED is sent, and the next unordered message on the stream is delivered as the rest of the abandoned one.

Abort the partial delivery when the MID being delivered is at or below the skipped MID, as the ordered case already does.

Reproduced on an unmodified kernel with the uo_pd test of the sctp_ifwdtsn.sh selftest added later in this series; its partial delivery checks pass with this fix. Reproduction and fix done with AI assistance.

Fixes de60fe910543 ("sctp: implement handle_ftsn for sctp_stream_interleave")
---
 net/sctp/stream_interleave.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/sctp/stream_interleave.c +1 -1
@@ -1255,7 +1255,7 @@ static void sctp_intl_skip(struct sctp_u
 	struct sctp_stream *stream  = &ulpq->asoc->stream;
 
 	if (flags & SCTP_FTSN_U_BIT) {
-		if (sin->pd_mode_uo && MID_lt(sin->mid_uo, mid)) {
+		if (sin->pd_mode_uo && !MID_lt(mid, sin->mid_uo)) {
 			sin->pd_mode_uo = 0;
 			sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x1,
 						  GFP_ATOMIC);
author maintainer
#766 lore raw

PATCH 765/1005 sctp: avoid requeueing pending control chunks

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Kyle Zeng <[email protected]>

commit 665b4149e91b781a71bce8637c3a4d7d64dba05f upstream.

The T4 and RE-CONFIG timeout handlers take a reference to their cached control chunk and submit it through SCTP_CMD_REPLY. A previous transmission can still be on the control outqueue when output is corked or suppressed, or when sctp_packet_transmit_chunk() could not append the chunk.

sctp_outq_tail() then adds the same list node a second time. Re-adding a non-tail entry can corrupt the list without being caught by the insertion-time list checks. A subsequent flush or association teardown can access an already freed chunk. The ASCONF path is reproducible by an unprivileged SCTP socket owner in a user/network namespace, with KASAN reporting a use-after-free in __sctp_outq_teardown().

Check sctp_chunk_pending() in both timeout handlers before taking the extra reference and issuing SCTP_CMD_REPLY. If the chunk is already linked, leave the existing entry for normal output processing. Keep the remaining timer and error-handling commands unchanged. This also covers RE-CONFIG retransmission after sctp_assoc_rm_peer() moves the request to another transport and starts its timer.

The issue was found by an LLM.

Fixes 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet")
Fixes 7b9438de0cd4 ("sctp: add stream reconf timer")
---
 net/sctp/sm_statefuns.c |   16 ++++++++++------
 1 file changed, 10 insertions(+), 6 deletions(-)
net/sctp/sm_statefuns.c +10 -6
@@ -1122,9 +1122,11 @@ enum sctp_disposition sctp_sf_send_recon
 		return SCTP_DISPOSITION_DELETE_TCB;
 	}
 
-	sctp_chunk_hold(asoc->strreset_chunk);
-	sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
-			SCTP_CHUNK(asoc->strreset_chunk));
+	if (!sctp_chunk_pending(asoc->strreset_chunk)) {
+		sctp_chunk_hold(asoc->strreset_chunk);
+		sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
+				SCTP_CHUNK(asoc->strreset_chunk));
+	}
 	sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport));
 
 	return SCTP_DISPOSITION_CONSUME;
@@ -6197,9 +6199,11 @@ enum sctp_disposition sctp_sf_t4_timer_e
 	 * chunk, it MUST be the same (including its serial number) as the last
 	 * ASCONF sent.
 	 */
-	sctp_chunk_hold(asoc->addip_last_asconf);
-	sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
-			SCTP_CHUNK(asoc->addip_last_asconf));
+	if (!sctp_chunk_pending(asoc->addip_last_asconf)) {
+		sctp_chunk_hold(asoc->addip_last_asconf);
+		sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
+				SCTP_CHUNK(asoc->addip_last_asconf));
+	}
 
 	/* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different
 	 * destination is selected, then the RTO used will be that of the new
author maintainer
#767 lore raw

PATCH 766/1005 sctp: fix ASCONF address change on single-homed hosts

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Andrey Misiurov <[email protected]>

commit 5175b2fb34c77cf2cd56a290affa45412cb3a228 upstream.

Commit 9b2854f86f0b ("sctp: don't free the ASCONF's own transport in DEL-IP processing") refuses a DEL-IP of the transport the ASCONF was located by, so that a later wildcard DEL-IP cannot use it after free.

This also breaks the single-homed address change (RFC 5061 5.3.2). The host sends [Address Parameter L] [ADD-IP S] [DEL-IP L], the association is located by L, and DEL-IP L is now refused. The sender never gets an all-success ASCONF-ACK, keeps src_out_of_asoc_ok set and stops sending data, so the association stalls.

Fix the wildcard DEL-IP instead: look up the transport of the packet source rather than reusing asconf->transport. Both DEL-IP paths can now free asconf->transport, and chunks bundled after the ASCONF still use it, so point it at a surviving transport: the packet source for the wildcard delete, the primary path for a plain one.

Found by manual code inspection while reviewing a backport of commit 9b2854f86f0b; reproduced on a two-namespace single-homed renumber.

Fixes 9b2854f86f0b ("sctp: don't free the ASCONF's own transport in DEL-IP processing")
---
 net/sctp/sm_make_chunk.c |   17 ++++++++---------
 1 file changed, 8 insertions(+), 9 deletions(-)
net/sctp/sm_make_chunk.c +8 -9
@@ -3160,9 +3160,12 @@ static __be16 sctp_process_asconf_param(
 		 * packet MUST be deleted.
 		 */
 		if (af->is_any(&addr)) {
-			sctp_assoc_set_primary(asoc, asconf->transport);
-			sctp_assoc_del_nonprimary_peers(asoc,
-							asconf->transport);
+			peer = sctp_assoc_lookup_paddr(asoc, &asconf->source);
+			if (!peer)
+				return SCTP_ERROR_REQ_REFUSED;
+			sctp_assoc_set_primary(asoc, peer);
+			sctp_assoc_del_nonprimary_peers(asoc, peer);
+			asconf->transport = peer;
 			return SCTP_ERROR_NO_ERROR;
 		}
 
@@ -3175,13 +3178,9 @@ static __be16 sctp_process_asconf_param(
 		if (!peer)
 			return SCTP_ERROR_DNS_FAILED;
 
-		/* Don't free asconf->transport; a later wildcard DEL-IP
-		 * parameter reuses it.
-		 */
-		if (peer == asconf->transport)
-			return SCTP_ERROR_REQ_REFUSED;
-
 		sctp_assoc_rm_peer(asoc, peer);
+		if (asconf->transport == peer)
+			asconf->transport = asoc->peer.primary_path;
 		break;
 	case SCTP_PARAM_SET_PRIMARY:
 		/* ADDIP Section 4.2.4
author maintainer
#768 lore raw

PATCH 767/1005 sctp: fix I-FORWARD-TSN handling of fragments on other streams

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tim Budding <[email protected]>

commit 5b9cfc6491a6e32e7315dc222992c7dbd5baa3e9 upstream.

sctp_report_iftsn() incorrectly frees queued I-DATA fragments in two cases. First, it drops any queued fragments with TSN less than or equal to the New Cumulative TSN. This prevents reconstruction of messages still being received on other streams and can fully block an ordered stream. Second, it calls sctp_intl_abort_pd() if the New Cumulative TSN equals the highest TSN seen. This check exists for association resets but can be inadvertently triggered by any I-FORWARD-TSN that arrives before data with a higher TSN, causing data loss and, if a partial delivery is in progress on an ordered stream, an aborted association.

Fix the first by freeing fragments from sctp_intl_skip() based on stream, U bit, and MID instead of TSN. Fix the second by moving the call to sctp_intl_abort_pd() from sctp_report_iftsn() to the corresponding reset handlers.

Observed in real use as unexpected message loss. Reproduced on an unmodified kernel with the sctp_ifwdtsn.sh selftest added later in this series, which passes with this fix. Reproduction and fix done with AI assistance.

Fixes 47b20a88566f ("sctp: implement report_ftsn for sctp_stream_interleave")
---
 net/sctp/stream.c            |    2 ++
 net/sctp/stream_interleave.c |   32 +++++++++++---------------------
 2 files changed, 13 insertions(+), 21 deletions(-)
net/sctp/stream.c +2 -0
@@ -749,6 +749,7 @@ struct sctp_chunk *sctp_process_strreset
 	 */
 	max_tsn_seen = sctp_tsnmap_get_max_tsn_seen(&asoc->peer.tsn_map);
 	asoc->stream.si->report_ftsn(&asoc->ulpq, max_tsn_seen);
+	asoc->stream.si->abort_pd(&asoc->ulpq, GFP_ATOMIC);
 
 	/* G1: Compute an appropriate value for the Receiver's Next TSN -- the
 	 *     TSN that the peer should use to send the next DATA chunk.  The
@@ -1028,6 +1029,7 @@ struct sctp_chunk *sctp_process_strreset
 			LIST_HEAD(temp);
 
 			asoc->stream.si->report_ftsn(&asoc->ulpq, mtsn);
+			asoc->stream.si->abort_pd(&asoc->ulpq, GFP_ATOMIC);
 
 			sctp_tsnmap_init(&asoc->peer.tsn_map,
 					 SCTP_TSN_MAP_INITIAL,
net/sctp/stream_interleave.c +11 -21
@@ -1203,28 +1203,21 @@ static void sctp_report_fwdtsn(struct sc
 	sctp_ulpq_abort_pd(ulpq, GFP_ATOMIC);
 }
 
-static void sctp_intl_reasm_flushtsn(struct sctp_ulpq *ulpq, __u32 ftsn)
+static void sctp_intl_reasm_flush_mid(struct sk_buff_head *reasm, __u16 sid,
+				      __u32 mid)
 {
 	struct sk_buff *pos, *tmp;
 
-	skb_queue_walk_safe(&ulpq->reasm, pos, tmp) {
+	skb_queue_walk_safe(reasm, pos, tmp) {
 		struct sctp_ulpevent *event = sctp_skb2event(pos);
-		__u32 tsn = event->tsn;
 
-		if (TSN_lte(tsn, ftsn)) {
-			__skb_unlink(pos, &ulpq->reasm);
-			sctp_ulpevent_free(event);
-		}
-	}
+		if (event->stream < sid)
+			continue;
+		if (event->stream > sid || MID_lt(mid, event->mid))
+			break;
 
-	skb_queue_walk_safe(&ulpq->reasm_uo, pos, tmp) {
-		struct sctp_ulpevent *event = sctp_skb2event(pos);
-		__u32 tsn = event->tsn;
-
-		if (TSN_lte(tsn, ftsn)) {
-			__skb_unlink(pos, &ulpq->reasm_uo);
-			sctp_ulpevent_free(event);
-		}
+		__skb_unlink(pos, reasm);
+		sctp_ulpevent_free(event);
 	}
 }
 
@@ -1232,11 +1225,6 @@ static void sctp_report_iftsn(struct sct
 {
 	/* Move the Cumulattive TSN Ack ahead. */
 	sctp_tsnmap_skip(&ulpq->asoc->peer.tsn_map, ftsn);
-	/* purge the fragmentation queue */
-	sctp_intl_reasm_flushtsn(ulpq, ftsn);
-	/* abort only when it's for all data */
-	if (ftsn == sctp_tsnmap_get_max_tsn_seen(&ulpq->asoc->peer.tsn_map))
-		sctp_intl_abort_pd(ulpq, GFP_ATOMIC);
 }
 
 static void sctp_handle_fwdtsn(struct sctp_ulpq *ulpq, struct sctp_chunk *chunk)
@@ -1260,6 +1248,7 @@ static void sctp_intl_skip(struct sctp_u
 			sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x1,
 						  GFP_ATOMIC);
 		}
+		sctp_intl_reasm_flush_mid(&ulpq->reasm_uo, sid, mid);
 		return;
 	}
 
@@ -1271,6 +1260,7 @@ static void sctp_intl_skip(struct sctp_u
 		sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x0, GFP_ATOMIC);
 	}
 
+	sctp_intl_reasm_flush_mid(&ulpq->reasm, sid, mid);
 	sctp_mid_skip(stream, in, sid, mid);
 
 	sctp_intl_reap_ordered(ulpq, sid);
author maintainer
#769 lore raw

PATCH 768/1005 sctp: report the partially delivered MID in PARTIAL_DELIVERY_ABORTED

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tim Budding <[email protected]>

commit 3097fba868019924e92b8786ebd473992565f015 upstream.

When an I-FORWARD-TSN skips the message being partially delivered on a stream, sctp_intl_skip() passes the MID from the I-FORWARD-TSN to the PARTIAL_DELIVERY_ABORTED notification as pdapi_seq. That MID is the highest one skipped on the stream, so when more than one message is skipped, the notification names a later message instead of the one whose partial delivery was aborted.

Report the MID being partially delivered, sin->mid_uo or sin->mid, instead.

Reproduced on an unmodified kernel with the pdapi and pdapi_uo tests of the sctp_ifwdtsn.sh selftest added later in this series, which pass with this fix. Reproduction and fix done with AI assistance.

---
 net/sctp/stream_interleave.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
net/sctp/stream_interleave.c +2 -2
@@ -1245,7 +1245,7 @@ static void sctp_intl_skip(struct sctp_u
 	if (flags & SCTP_FTSN_U_BIT) {
 		if (sin->pd_mode_uo && !MID_lt(mid, sin->mid_uo)) {
 			sin->pd_mode_uo = 0;
-			sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x1,
+			sctp_intl_stream_abort_pd(ulpq, sid, sin->mid_uo, 0x1,
 						  GFP_ATOMIC);
 		}
 		sctp_intl_reasm_flush_mid(&ulpq->reasm_uo, sid, mid);
@@ -1257,7 +1257,7 @@ static void sctp_intl_skip(struct sctp_u
 
 	if (sin->pd_mode) {
 		sin->pd_mode = 0;
-		sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x0, GFP_ATOMIC);
+		sctp_intl_stream_abort_pd(ulpq, sid, sin->mid, 0x0, GFP_ATOMIC);
 	}
 
 	sctp_intl_reasm_flush_mid(&ulpq->reasm, sid, mid);
author maintainer
#770 lore raw

PATCH 769/1005 sctp: reset stored flag for each association

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Weiming Shi <[email protected]>

commit 173712d868eb20628ad82deb07f6829a68a9e064 upstream.

sctp_send_asconf_del_ip() walks every association on an endpoint. The stored flag records that the current association took the single-homed deferral path and therefore did not allocate an ASCONF chunk. It is currently scoped to the whole function. Once one association sets it, later eligible multihomed associations allocate chunks but skip sctp_send_asconf(), leaking each chunk and its skb.

Reset stored for every association so only an association taking the deferral path skips transmission. In an A/B kmemleak test, the vulnerable kernel reported 210 leaked objects from this call path and the fixed kernel reported none.

---
 net/sctp/socket.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/sctp/socket.c +1 -1
@@ -809,7 +809,6 @@ static int sctp_send_asconf_del_ip(struc
 	struct sctp_sockaddr_entry *saddr;
 	int 			i;
 	int 			retval = 0;
-	int			stored = 0;
 
 	chunk = NULL;
 	sp = sctp_sk(sk);
@@ -822,6 +821,7 @@ static int sctp_send_asconf_del_ip(struc
 		 __func__, sk, addrs, addrcnt);
 
 	list_for_each_entry(asoc, &ep->asocs, asocs) {
+		int stored = 0;
 
 		if (!asoc->peer.asconf_capable)
 			continue;
author maintainer
#771 lore raw

PATCH 770/1005 ksmbd: grant a caller what its groups and OWNER RIGHTS ACEs allow

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Ian Bridges <[email protected]>

commit 42ac1f1917ae678ee2c47f415ab844af03bbd46b upstream.

smb_check_perm_dacl() does not match ACEs for the caller's Unix groups and refuses an owner named only by OWNER RIGHTS. These callers cannot use rights the DACL grants them under MS-DTYP 2.5.3.2.

Match Unix group SIDs (S-1-22-2) against the caller's credentials. Use the ordered DACL result when the existing SID lookup and POSIX ACL fallback do not decide access. In that result, deny ACEs for the caller's groups limit what it grants, also for MAXIMUM_ALLOWED. Count only the exact OWNER RIGHTS SID in that result, since compare_sids() also matches shorter and longer SIDs, and return only file access rights. Preserve the refusal for non-inherit-only object deny ACEs, which ksmbd does not parse.

MAXIMUM_ALLOWED still excludes group allow ACEs. Including them requires corresponding changes in smb2_open() to avoid breaking existing opens. An open relying on group grants can therefore still fail when it requests a maximal access reply. For the owner, that reply leaves out the rights of its groups.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smbacl.c |  162 +++++++++++++++++++++++++++++++++++--------------
 1 file changed, 117 insertions(+), 45 deletions(-)
fs/smb/server/smbacl.c +117 -45
@@ -1452,6 +1452,35 @@ bool smb_inherit_flags(int flags, bool i
 	return false;
 }
 
+/* Whether the caller's credentials hold the group of an S-1-22-2-<gid> SID */
+static bool smb_sid_in_group(const struct smb_sid *sid)
+{
+	gid_t gid;
+
+	if (sid->num_subauth != sid_unix_groups.num_subauth + 1 ||
+	    compare_sids(sid, &sid_unix_groups))
+		return false;
+	gid = le32_to_cpu(sid->sub_auth[sid->num_subauth - 1]);
+	/*
+	 * ksmbd_override_fsids() builds the caller's credentials with
+	 * make_kgid(&init_user_ns, ...), so the group membership test must
+	 * compare in that space. Applying the mount idmap here (as when
+	 * resolving a SID to an on-disk gid) would mismatch on idmapped
+	 * mounts.
+	 */
+	return in_group_p(make_kgid(&init_user_ns, gid));
+}
+
+/*
+ * compare_sids() compares only the sub-authorities both SIDs have, so it
+ * also matches a shorter or longer SID, such as S-1-3 or S-1-3-4-777
+ */
+static bool smb_sid_is_owner_rights(const struct smb_sid *sid)
+{
+	return sid->num_subauth == sid_owner_rights.num_subauth &&
+	       !compare_sids(sid, &sid_owner_rights);
+}
+
 int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,
 			__le32 *pdaccess, __le32 raw_daccess, int uid,
 			bool strict)
@@ -1468,13 +1497,15 @@ int smb_check_perm_dacl(struct ksmbd_con
 	int granted = requested;
 	struct smb_ace *ace;
 	int i, found = 0;
-	unsigned int access_bits = 0, denied = 0;
+	unsigned int access_bits = 0, denied = 0, grp_granted = 0;
+	unsigned int grp_allowed = 0, grp_denied = 0, bits;
 	struct smb_ace *others_ace = NULL;
-	bool or_ace = false;
+	bool or_ace = false, obj_deny = false, member, counted;
 	struct posix_acl_entry *pa_entry;
 	unsigned int sid_type = SIDOWNER;
 	unsigned short ace_size;
 	bool is_owner, owner_rights = false;
+	bool maximal = *pdaccess & FILE_MAXIMAL_ACCESS_LE;
 	vfsuid_t vfsuid;
 
 	ksmbd_debug(SMB, "check permission using windows acl\n");
@@ -1515,7 +1546,7 @@ int smb_check_perm_dacl(struct ksmbd_con
 		 */
 		if (is_owner)
 			allowed = READ_CONTROL | WRITE_DAC;
-		if (*pdaccess & FILE_MAXIMAL_ACCESS_LE)
+		if (maximal)
 			requested |= allowed;
 		if (!allowed || requested & ~allowed)
 			rc = -EACCES;
@@ -1524,53 +1555,83 @@ int smb_check_perm_dacl(struct ksmbd_con
 		goto err_out;
 	}
 
-	if (*pdaccess & FILE_MAXIMAL_ACCESS_LE) {
-		ace = (struct smb_ace *)((char *)pdacl + sizeof(struct smb_acl));
-		aces_size = pdacl_size - sizeof(struct smb_acl);
-		for (i = 0; i < le16_to_cpu(pdacl->num_aces); i++) {
-			if (aces_size < offsetof(struct smb_ace, sid) +
-			    CIFS_SID_BASE_SIZE)
-				break;
-			ace_size = le16_to_cpu(ace->size);
-			if (ace_size > aces_size ||
-			    ace_size < offsetof(struct smb_ace, sid) +
-				       CIFS_SID_BASE_SIZE)
-				break;
-			aces_size -= ace_size;
+	/*
+	 * Evaluate the DACL in order (MS-DTYP 2.5.3.2). access_bits collects
+	 * the MAXIMUM_ALLOWED result. grp_granted collects what ACEs for the
+	 * caller's groups, or OWNER RIGHTS for the owner, grant. It is used
+	 * when the SID lookup and POSIX ACL fallback below do not decide.
+	 */
+	ace = (struct smb_ace *)((char *)pdacl + sizeof(struct smb_acl));
+	aces_size = pdacl_size - sizeof(struct smb_acl);
+	for (i = 0; i < le16_to_cpu(pdacl->num_aces); i++) {
+		if (aces_size < offsetof(struct smb_ace, sid) +
+		    CIFS_SID_BASE_SIZE)
+			break;
+		ace_size = le16_to_cpu(ace->size);
+		if (ace_size > aces_size ||
+		    ace_size < offsetof(struct smb_ace, sid) +
+			       CIFS_SID_BASE_SIZE)
+			break;
+		aces_size -= ace_size;
 
-			if (ace->sid.num_subauth > SID_MAX_SUB_AUTHORITIES ||
-			    ace_size < offsetof(struct smb_ace, sid) +
-				      CIFS_SID_BASE_SIZE +
-				      sizeof(__le32) * ace->sid.num_subauth)
-				break;
+		if (ace->sid.num_subauth > SID_MAX_SUB_AUTHORITIES ||
+		    ace_size < offsetof(struct smb_ace, sid) +
+			      CIFS_SID_BASE_SIZE +
+			      sizeof(__le32) * ace->sid.num_subauth)
+			break;
 
-			if (!compare_sids(&sid_owner_rights, &ace->sid)) {
-				owner_rights = true;
-				if (!is_owner)
-					goto next_ace;
-			}
+		if ((ace->type == ACCESS_DENIED_OBJECT_ACE_TYPE ||
+		     ace->type == ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE) &&
+		    !(ace->flags & INHERIT_ONLY_ACE))
+			obj_deny = true;
 
-			if (ace->flags & INHERIT_ONLY_ACE ||
-			    (compare_sids(&sid, &ace->sid) &&
-			     compare_sids(&sid_unix_NFS_mode, &ace->sid) &&
-			     compare_sids(&sid_everyone, &ace->sid) &&
-			     compare_sids(&sid_authusers, &ace->sid) &&
-			     compare_sids(&sid_owner_rights, &ace->sid)))
+		if (!compare_sids(&sid_owner_rights, &ace->sid)) {
+			owner_rights = true;
+			if (!is_owner)
 				goto next_ace;
+		}
 
-			switch (ace->type) {
-			case ACCESS_ALLOWED_ACE_TYPE:
-				access_bits |= le32_to_cpu(ace->access_req);
-				break;
-			case ACCESS_DENIED_ACE_TYPE:
-			case ACCESS_DENIED_CALLBACK_ACE_TYPE:
-				denied |= ~access_bits &
-					le32_to_cpu(ace->access_req);
+		member = smb_sid_in_group(&ace->sid);
+		/* The grp_ masks count groups and OWNER RIGHTS only */
+		counted = member ||
+			  (is_owner && smb_sid_is_owner_rights(&ace->sid));
+		if (ace->flags & INHERIT_ONLY_ACE ||
+		    (compare_sids(&sid, &ace->sid) &&
+		     compare_sids(&sid_unix_NFS_mode, &ace->sid) &&
+		     compare_sids(&sid_everyone, &ace->sid) &&
+		     compare_sids(&sid_authusers, &ace->sid) &&
+		     compare_sids(&sid_owner_rights, &ace->sid) &&
+		     !member))
+			goto next_ace;
+
+		bits = le32_to_cpu(ace->access_req);
+		switch (ace->type) {
+		case ACCESS_ALLOWED_ACE_TYPE:
+			if (counted)
+				grp_allowed |= bits;
+			/* MAXIMUM_ALLOWED takes no group grants */
+			if (maximal && member)
 				break;
-			}
-next_ace:
-			ace = (struct smb_ace *)((char *)ace + le16_to_cpu(ace->size));
+			if (counted)
+				grp_granted |= bits;
+			access_bits |= bits;
+			break;
+		case ACCESS_DENIED_ACE_TYPE:
+		case ACCESS_DENIED_CALLBACK_ACE_TYPE:
+			if (counted)
+				grp_denied |= ~grp_allowed & bits;
+			/* access_bits takes no group denials either */
+			if (!member)
+				denied |= ~access_bits & bits;
+			break;
 		}
+next_ace:
+		ace = (struct smb_ace *)((char *)ace + le16_to_cpu(ace->size));
+	}
+
+	/* Keep only file rights, not MAXIMUM_ALLOWED or generic bits */
+	grp_granted &= GENERIC_ALL_FLAGS & ~grp_denied;
+	if (maximal) {
 		if (is_owner && !owner_rights)
 			access_bits |= READ_CONTROL | WRITE_DAC |
 				FILE_READ_ATTRIBUTES | DELETE;
@@ -1580,6 +1641,9 @@ next_ace:
 		    (access_bits & GENERIC_READ_FLAGS) == GENERIC_READ_FLAGS)
 			access_bits |= FILE_EXECUTE;
 		granted = requested | access_bits;
+	} else {
+		/* An explicit request uses only grp_granted and obj_deny */
+		access_bits = 0;
 	}
 
 	ace = (struct smb_ace *)((char *)pdacl + sizeof(struct smb_acl));
@@ -1661,7 +1725,15 @@ next_ace:
 			 */
 			if (is_owner && !or_ace)
 				allowed = READ_CONTROL | WRITE_DAC;
-			if (*pdaccess & FILE_MAXIMAL_ACCESS_LE)
+			/*
+			 * Add what ACEs for the caller's groups, or OWNER
+			 * RIGHTS for the owner, grant in DACL order, unless an
+			 * object deny ACE, which ksmbd does not parse, could
+			 * apply.
+			 */
+			if (!obj_deny)
+				allowed |= grp_granted;
+			if (maximal)
 				requested |= allowed;
 			if (!allowed || requested & ~allowed) {
 				ksmbd_debug(SMB, "Can't find corresponding sid\n");
@@ -1673,7 +1745,7 @@ next_ace:
 		}
 	}
 
-	if (!(*pdaccess & FILE_MAXIMAL_ACCESS_LE)) {
+	if (!maximal) {
 		switch (ace->type) {
 		case ACCESS_ALLOWED_ACE_TYPE:
 			access_bits = le32_to_cpu(ace->access_req);
author maintainer
#772 lore raw

PATCH 771/1005 ksmbd: keep group denials when a POSIX ACL entry decides access

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Ian Bridges <[email protected]>

commit b0af9a3e6b1534d353ca6ac23caaf46127f62e4a upstream.

When no ACE names the caller, Everyone or Authenticated Users, smb_check_perm_dacl() lets a POSIX ACL entry for the caller decide access. The entry's rights replace the result of the DACL walk. Deny ACEs for the caller's groups, and OWNER RIGHTS for the owner, are then lost.

For example, a deny of FILE_WRITE_DATA for one of the caller's groups should refuse writes. A POSIX ACL entry that gives the caller write access still lets the caller write.

Remove the requested rights that those ACEs deny from the entry's rights. The DACL walk already records them in grp_denied.

---
 fs/smb/server/smbacl.c |    9 +++++++++
 1 file changed, 9 insertions(+)
fs/smb/server/smbacl.c +9 -0
@@ -1703,6 +1703,15 @@ next_ace:
 					if (!access_bits)
 						access_bits =
 							SET_MINIMUM_RIGHTS;
+					/*
+					 * Only ACEs for the caller's groups,
+					 * or OWNER RIGHTS for the owner, apply
+					 * here. The POSIX ACL entry does not
+					 * grant an explicitly requested right
+					 * that they deny first in DACL order.
+					 */
+					access_bits &= ~(grp_denied &
+							 requested);
 					posix_acl_release(posix_acls);
 					goto check_access_bits;
 				}
author maintainer
#773 lore raw

PATCH 772/1005 ksmbd: refuse reauthentication of an expired session as another user

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Michail Andreas Michalopoulos <[email protected]>

commit 265709f9dc271693d1a261a62242db652fcc471d upstream.

When a Kerberos session expires, its owner can reauthenticate it. For an NTLM reauthentication, ntlm_authenticate() only compares the new user with sess->user when the session is still valid. An expired session is in SMB2_SESSION_IN_PROGRESS during the reauthentication, so it takes the other branch and simply sets sess->user to the new user:

- the session's open files, tree connects and other state, created under the original user's identity, now belong to whichever user just authenticated, and a later Kerberos reauthentication is compared against that user rather than the original one;
- the original struct ksmbd_user is overwritten without being freed.

krb5_authenticate() already refuses a different user in this case, and the valid-session branch of ntlm_authenticate() does too. Do the same for an expired session: compare with the existing user and refuse a different one with -EKEYREJECTED, freeing the newly looked-up user either way.

An AI assistant was used to find and fix this and as an independent reviewer.

Fixes a47634cd729b ("ksmbd: expire SMB sessions when Kerberos tickets expire")
---
 fs/smb/server/smb2pdu.c |   11 +++++++++++
 1 file changed, 11 insertions(+)
fs/smb/server/smb2pdu.c +11 -0
@@ -2358,6 +2358,17 @@ static int ntlm_authenticate(struct ksmb
 			return -EKEYREJECTED;
 		}
 		ksmbd_free_user(user);
+	} else if (sess->user) {
+		/*
+		 * Reauthentication of an expired session: as for a valid
+		 * session, and as krb5_authenticate() does, it must be by the
+		 * same user. Replacing sess->user would also leak the old one.
+		 */
+		if (!ksmbd_compare_user(sess->user, user)) {
+			ksmbd_free_user(user);
+			return -EKEYREJECTED;
+		}
+		ksmbd_free_user(user);
 	} else {
 		sess->user = user;
 	}
author maintainer
#774 lore raw

PATCH 773/1005 LoongArch: BPF: Make arena support depend on 128-bit cmpxchg

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tiezhu Yang <[email protected]>

commit 9496832b824ab5f570c86d65e3b6f08163e6908b upstream.

When testing bpf selftest "jit_insns/cast_to_user", there are different behaviors on different Loongson machines.

(1) Loongson-3A6000

  $ sudo ./test_progs -a jit_insns/cast_to_user
  ...
  Summary: 1/1 PASSED, 0 SKIPPED, 0/0 FAILED

(2) Loongson-3A5000

  $ sudo ./test_progs -a jit_insns/cast_to_user
  ...
  libbpf: map 'arena': failed to create: -ENOMEM
  run_subtest:FAIL:unexpected_load_failure unexpected error: -12 (errno 12)
  ...
  Summary: 0/0 PASSED, 0 SKIPPED, 1/1 FAILED

This is because the arena range tree uses kmalloc_nolock() API, which requires 128-bit atomic cmpxchg. This feature is provided by not only hardware SCQ extension but also assembler support on LoongArch. On CPUs without the SCQ extension, or if the older versions of assembler do not support the sc.q instruction, arena map creation fails with a misleading -ENOMEM error.

Since system_has_cmpxchg128() and arch_cmpxchg128() are only available when CONFIG_AS_HAS_SCQ_EXTENSION is enabled (need assembler support), we guard bpf_jit_supports_arena() with an #ifdef block to preserve compile- time robustness first, and then safely return system_has_cmpxchg128() if defined, otherwise falling back to false. This ensures that arena map creation cleanly fails with a -EOPNOTSUPP on the systems without either the assembler support or the hardware SCQ extension.

With this patch, here is the test result on Loongson-3A5000 without SCQ extension:

  $ sudo ./test_progs -a jit_insns/cast_to_user
  ...
  libbpf: map 'arena': failed to create: -EOPNOTSUPP
  run_subtest:FAIL:unexpected_load_failure unexpected error: -95 (errno 95)
  ...
  Summary: 0/0 PASSED, 0 SKIPPED, 1/1 FAILED

It is better to mark the test status as SKIPPED rather than logging a false-alarm failure if the feature is not supported, but this belongs to a separate bpf selftest patch.

This is similar to commit 536b523b4073 ("bpf, riscv: Make arena support depend on ZACAS").

Note that BPF should not depend on a SLUB debug-mode escape hatch, so no need to consider the slub_debug exception.

Fixes 4fdb5dd8aeba ("LoongArch: BPF: Implement bpf_addr_space_cast instruction")
---
 arch/loongarch/net/bpf_jit.c |   11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
arch/loongarch/net/bpf_jit.c +10 -1
@@ -2436,7 +2436,16 @@ bool bpf_jit_bypass_spec_v4(void)
 
 bool bpf_jit_supports_arena(void)
 {
-	return true;
+	/*
+	 * The arena range tree uses kmalloc_nolock(), which requires
+	 * 128-bit atomic cmpxchg; this is provided by not only hardware
+	 * SCQ extension but also assembler support on LoongArch.
+	 */
+#ifdef system_has_cmpxchg128
+	return system_has_cmpxchg128();
+#else
+	return false;
+#endif
 }
 
 bool bpf_jit_supports_fsession(void)
author maintainer
#775 lore raw

PATCH 774/1005 LoongArch: BPF: Make use of beqz and bnez for trampoline branches

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tiezhu Yang <[email protected]>

commit 6dd070681326ef2fef5e008b8c3d0ae9634de222 upstream.

Currently, the implementation for BPF trampoline branches does not match the existing technical comments. The code uses larch_insn_gen_beq, where the comment indicates beqz should be used.

While the BPF trampoline size is restricted within a single memory page (at most 64KB on LoongArch) and cannot cross the original 16-bit branch offset limit of the reg2i16 format, switching to the beqz instruction (which belongs to the reg1i21 format) avoids explicitly specifying the zero register during dynamic JIT encoding, resulting in cleaner assembly generation.

While at it, also apply the same optimization to the bne instruction by replacing it with bnez and adding a corresponding comment.

---
 arch/loongarch/include/asm/inst.h |   21 +++++++++++++++++++++
 arch/loongarch/kernel/inst.c      |   28 ++++++++++++++++++++++++++++
 arch/loongarch/net/bpf_jit.c      |    5 +++--
 3 files changed, 52 insertions(+), 2 deletions(-)
arch/loongarch/include/asm/inst.h +21 -0
@@ -535,6 +535,8 @@ u32 larch_insn_gen_lu32id(enum loongarch
 u32 larch_insn_gen_lu52id(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm);
 u32 larch_insn_gen_beq(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm);
 u32 larch_insn_gen_bne(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm);
+u32 larch_insn_gen_beqz(enum loongarch_gpr rj, int imm);
+u32 larch_insn_gen_bnez(enum loongarch_gpr rj, int imm);
 u32 larch_insn_gen_jirl(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm);
 
 static inline bool signed_imm_check(long val, unsigned int bit)
@@ -592,6 +594,25 @@ DEF_EMIT_REG1I20_FORMAT(lu12iw, lu12iw_o
 DEF_EMIT_REG1I20_FORMAT(lu32id, lu32id_op)
 DEF_EMIT_REG1I20_FORMAT(pcaddu18i, pcaddu18i_op)
 
+#define DEF_EMIT_REG1I21_FORMAT(NAME, OP)				\
+static inline void emit_##NAME(union loongarch_instruction *insn,	\
+			       enum loongarch_gpr rj, int offset)	\
+{									\
+	unsigned int immediate_l, immediate_h;				\
+									\
+	immediate_l = offset & 0xffff;					\
+	offset >>= 16;							\
+	immediate_h = offset & 0x1f;					\
+									\
+	insn->reg1i21_format.opcode = OP;				\
+	insn->reg1i21_format.immediate_l = immediate_l;			\
+	insn->reg1i21_format.rj = rj;					\
+	insn->reg1i21_format.immediate_h = immediate_h;			\
+}
+
+DEF_EMIT_REG1I21_FORMAT(beqz, beqz_op)
+DEF_EMIT_REG1I21_FORMAT(bnez, bnez_op)
+
 #define DEF_EMIT_REG2_FORMAT(NAME, OP)					\
 static inline void emit_##NAME(union loongarch_instruction *insn,	\
 			       enum loongarch_gpr rd,			\
arch/loongarch/kernel/inst.c +28 -0
@@ -428,6 +428,34 @@ u32 larch_insn_gen_bne(enum loongarch_gp
 	return insn.word;
 }
 
+u32 larch_insn_gen_beqz(enum loongarch_gpr rj, int imm)
+{
+	union loongarch_instruction insn;
+
+	if ((imm & 3) || imm < -SZ_4M || imm >= SZ_4M) {
+		pr_warn("The generated beqz instruction is out of range.\n");
+		return INSN_BREAK;
+	}
+
+	emit_beqz(&insn, rj, imm >> 2);
+
+	return insn.word;
+}
+
+u32 larch_insn_gen_bnez(enum loongarch_gpr rj, int imm)
+{
+	union loongarch_instruction insn;
+
+	if ((imm & 3) || imm < -SZ_4M || imm >= SZ_4M) {
+		pr_warn("The generated bnez instruction is out of range.\n");
+		return INSN_BREAK;
+	}
+
+	emit_bnez(&insn, rj, imm >> 2);
+
+	return insn.word;
+}
+
 u32 larch_insn_gen_jirl(enum loongarch_gpr rd, enum loongarch_gpr rj, int imm)
 {
 	union loongarch_instruction insn;
arch/loongarch/net/bpf_jit.c +3 -2
@@ -1768,7 +1768,7 @@ static int invoke_bpf_prog(struct jit_ct
 	/* update branch with beqz */
 	if (ctx->image) {
 		int offset = (void *)(&ctx->image[ctx->idx]) - (void *)branch;
-		*branch = larch_insn_gen_beq(LOONGARCH_GPR_A0, LOONGARCH_GPR_ZERO, offset);
+		*branch = larch_insn_gen_beqz(LOONGARCH_GPR_A0, offset);
 	}
 
 	/* arg1: prog */
@@ -2081,9 +2081,10 @@ static int __arch_prepare_bpf_trampoline
 		emit_insn(ctx, std, regmap[BPF_REG_0], LOONGARCH_GPR_FP, -(retval_off - 8));
 	}
 
+	/* update branches with bnez */
 	for (i = 0; ctx->image && i < fmod_ret->nr_nodes; i++) {
 		int offset = (void *)(&ctx->image[ctx->idx]) - (void *)branches[i];
-		*branches[i] = larch_insn_gen_bne(LOONGARCH_GPR_T1, LOONGARCH_GPR_ZERO, offset);
+		*branches[i] = larch_insn_gen_bnez(LOONGARCH_GPR_T1, offset);
 	}
 
 	/* Set "is_return" flag for fsession */
author maintainer
#776 lore raw

PATCH 775/1005 LoongArch: kexec_file: Fix a modified cmdline leak

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jinjie Ruan <[email protected]>

commit b7000844b374a1ab75f0cc561f1d4d321cd6eeb0 upstream.

machine_kexec_prepare() copies it to KEXEC_CMDLINE_ADDR and overwrites the pointer. Free the heap buffer after the copy here.

Fixes d162feec6b6e ("LoongArch: Add preparatory infrastructure for kexec_file")
---
 arch/loongarch/kernel/machine_kexec.c |    2 ++
 1 file changed, 2 insertions(+)
arch/loongarch/kernel/machine_kexec.c +2 -0
@@ -14,6 +14,7 @@
 #include <linux/mm.h>
 #include <linux/of_fdt.h>
 #include <linux/reboot.h>
+#include <linux/slab.h>
 #include <linux/sched.h>
 #include <linux/sched/task_stack.h>
 
@@ -56,6 +57,7 @@ int machine_kexec_prepare(struct kimage
 		 */
 		memcpy((void *)KEXEC_CMDLINE_ADDR, (void *)kimage->arch.cmdline_ptr,
 					strlen((char *)kimage->arch.cmdline_ptr) + 1);
+		kfree((void *)kimage->arch.cmdline_ptr);
 		kimage->arch.cmdline_ptr = (unsigned long)KEXEC_CMDLINE_ADDR;
 	} else {
 		/* Find the command line */
author maintainer
#777 lore raw

PATCH 776/1005 LoongArch: kexec_file: Fix elf_headers memory leak in retry loop

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jinjie Ruan <[email protected]>

commit 065dd1636abef6b9962fd5af82accac69850bbe8 upstream.

A retry allocates new elf headers and overwrites image->elf_headers, leaking the previous buffer. Free it before assigning here.

---
 arch/loongarch/kernel/machine_kexec_file.c |    4 ++++
 1 file changed, 4 insertions(+)
arch/loongarch/kernel/machine_kexec_file.c +4 -0
@@ -166,6 +166,10 @@ int load_other_segments(struct kimage *i
 			vfree(headers);
 			goto out_err;
 		}
+
+		if (unlikely(image->elf_headers))
+			vfree(image->elf_headers);
+
 		image->elf_headers = headers;
 		image->elf_load_addr = kbuf.mem;
 		image->elf_headers_sz = headers_sz;
author maintainer
#778 lore raw

PATCH 777/1005 LoongArch: Restore KFENCE pages through DMW on resume

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mike Rapoport (Microsoft) <[email protected]>

commit 40d7a3e63c3d88b43e9115d23d9937dd506bbd02 upstream.

With KFENCE enabled, resume from hibernation triggers KFENCE reports while swsusp_asm_resume() copies the image pages, for example:

  BUG: KFENCE: use-after-free write in swsusp_asm_resume+0x20/0x94

Use-after-free write at 0x00000000a57ee925 (in kfence-#254):

   swsusp_asm_resume+0x20/0x94
   hibernation_restore+0x128/0x1a0
   load_image_and_restore+0x6c/0xc8
   software_resume+0x240/0x260
   do_one_initcall+0x68/0x200
   kernel_init_freeable+0x26c/0x304
   kernel_init+0x20/0x134
   ret_from_kernel_thread+0x24/0x1d0
   ret_from_kernel_thread_asm+0xc/0x98

During resume from hibernation, the image pages that occupy physical pages used by the restore kernel are first loaded into free pages and then, as the very last step, swsusp_asm_resume() copies them to their final location pointed to by pbe->orig_address, which the hibernation core sets to page_address() of the page in the restore kernel.

The early KFENCE pool is allocated from memblock and normally occupies the same physical pages in the restore kernel and in the image kernel, so these pages are usually copied by swsusp_asm_resume().

The KFENCE pool is remapped into the KFENCE area above vm_map_base and set_page_address() adjusts page->virtual so that page_address() returns the page-table mapped alias rather than the DMW virtual address of the pool pages.

Hence, pbe->orig_address of KFENCE pages points to that alias and swsusp_asm_resume() writes them through the page tables. But:

* the copy loop overwrites the kernel page tables, so a TLB refill for the KFENCE alias may use a partially restored page table
* the KFENCE pool pages that are protected in the restore kernel fault in the middle of the copy

Convert pbe->orig_address to DMW addresses before starting the copy.

Fixes 0ca84aeaee15 ("LoongArch: Make {virt, phys, page, pfn} translation work with KFENCE")
---
 arch/loongarch/power/hibernate.c |    6 ++++++
 1 file changed, 6 insertions(+)
arch/loongarch/power/hibernate.c +6 -0
@@ -59,6 +59,12 @@ extern int swsusp_asm_resume(void);
 
 int swsusp_arch_resume(void)
 {
+#ifdef CONFIG_KFENCE
+	struct pbe *pbe;
+
+	for (pbe = restore_pblist; pbe; pbe = pbe->next)
+		pbe->orig_address = __va(virt_to_phys(pbe->orig_address));
+#endif
 	/* Avoid TLB mismatch during and after kernel resume */
 	local_flush_tlb_all();
 	return swsusp_asm_resume();
author maintainer
#779 lore raw

PATCH 778/1005 LoongArch: KVM: Clear device pointer in irqchip destroy callbacks

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tao Cui <[email protected]>

commit a9ce1a00afb0402668877d37c04ffd0e53d48832 upstream.

The destroy callbacks of the four irqchip devices free the device structure without clearing kvm->arch.{ipi,eiointc,pch_pic,dmsintc}, leaving a dangling pointer. ops->destroy() is not only called at VM teardown but also when KVM_CREATE_DEVICE succeeds and the following anon_inode_getfd() fails (e.g. under RLIMIT_NOFILE); the VM stays alive, kvm_arch_irqchip_in_kernel() still reports true, and interrupt injection dereferences the freed device.

Clear the pointer when destroying.

Fixes c532de5a67a7 ("LoongArch: KVM: Add IPI device support")
Fixes 2e8b9df82631 ("LoongArch: KVM: Add EIOINTC device support")
Fixes e785dfacf7e7 ("LoongArch: KVM: Add PCHPIC device support")
Fixes 229132c309d6 ("LoongArch: KVM: Add DMSINTC device support")
---
 arch/loongarch/kvm/intc/dmsintc.c |    1 +
 arch/loongarch/kvm/intc/eiointc.c |    1 +
 arch/loongarch/kvm/intc/ipi.c     |    1 +
 arch/loongarch/kvm/intc/pch_pic.c |    1 +
 4 files changed, 4 insertions(+)
arch/loongarch/kvm/intc/dmsintc.c +1 -0
@@ -166,6 +166,7 @@ static void kvm_dmsintc_destroy(struct k
 		return;
 
 	kfree(dev->kvm->arch.dmsintc);
+	dev->kvm->arch.dmsintc = NULL;
 	kfree(dev);
 }
 
arch/loongarch/kvm/intc/eiointc.c +1 -0
@@ -675,6 +675,7 @@ static void kvm_eiointc_destroy(struct k
 
 	kvm = dev->kvm;
 	eiointc = kvm->arch.eiointc;
+	kvm->arch.eiointc = NULL;
 	mutex_lock(&kvm->slots_lock);
 	kvm_io_bus_unregister_dev(kvm, KVM_IOCSR_BUS, &eiointc->device);
 	kvm_io_bus_unregister_dev(kvm, KVM_IOCSR_BUS, &eiointc->device_vext);
arch/loongarch/kvm/intc/ipi.c +1 -0
@@ -444,6 +444,7 @@ static void kvm_ipi_destroy(struct kvm_d
 
 	kvm = dev->kvm;
 	ipi = kvm->arch.ipi;
+	kvm->arch.ipi = NULL;
 	mutex_lock(&kvm->slots_lock);
 	kvm_io_bus_unregister_dev(kvm, KVM_IOCSR_BUS, &ipi->device);
 	mutex_unlock(&kvm->slots_lock);
arch/loongarch/kvm/intc/pch_pic.c +1 -0
@@ -483,6 +483,7 @@ static void kvm_pch_pic_destroy(struct k
 
 	kvm = dev->kvm;
 	s = kvm->arch.pch_pic;
+	kvm->arch.pch_pic = NULL;
 	/* unregister pch pic device and free it's memory */
 	mutex_lock(&kvm->slots_lock);
 	kvm_io_bus_unregister_dev(kvm, KVM_MMIO_BUS, &s->device);
author maintainer
#780 lore raw

PATCH 779/1005 LoongArch: KVM: Propagate real error code in kvm_pch_pic_create()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tao Cui <[email protected]>

commit 20f3bf3d3dce16f43b82881293586ce7d73982b6 upstream.

The real error code of kvm_setup_default_irq_routing() is replaced by kvm_pch_pic_create() with a fixed -ENOMEM. Return the actual error code, as kvm_eiointc_create() already does; while the kvm_ipi_create() case is fixed separately by "Return the actual error code in kvm_ipi_create()" (Chaithanya Lagisetty).

Fixes e785dfacf7e7 ("LoongArch: KVM: Add PCHPIC device support")
---
 arch/loongarch/kvm/intc/pch_pic.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/loongarch/kvm/intc/pch_pic.c +1 -1
@@ -444,7 +444,7 @@ static int kvm_pch_pic_create(struct kvm
 
 	ret = kvm_setup_default_irq_routing(kvm);
 	if (ret)
-		return -ENOMEM;
+		return ret;
 
 	s = kzalloc_obj(struct loongarch_pch_pic);
 	if (!s)
author maintainer
#781 lore raw

PATCH 780/1005 LoongArch: KVM: Reject repeated PCH-PIC CTRL_INIT

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tao Cui <[email protected]>

commit 422e532809572ba1043192bf6a0c653bc68b3140 upstream.

KVM_DEV_LOONGARCH_PCH_PIC_CTRL_INIT has no guard against repeated
invocation: every call overwrites pch_pic_base and registers the same kvm_io_device on the MMIO bus at the new base address, while the kvm_pch_pic_destroy() unregisters only one bus range. After a repeated init, MMIO to the stale ranges computes its register offset against the new base address and silently reads 0 / drops writes, and the leftover bus entries persist until the VM is destroyed.

Reject repeated initialization with -EEXIST, using the initialized state of the kvm_io_device as the indicator. The check, the MMIO base update and the bus registration are serialized by slots_lock, and the real registration error is propagated instead of being replaced with -EFAULT. On a registration failure the base addr and the device state are rolled back so that a retry can start over.

Fixes d206d9514873 ("LoongArch: KVM: Add PCHPIC user mode read and write functions")
---
 arch/loongarch/kvm/intc/pch_pic.c |   15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
arch/loongarch/kvm/intc/pch_pic.c +12 -3
@@ -281,16 +281,25 @@ static int kvm_pch_pic_init(struct kvm_d
 	struct kvm_io_device *device;
 	struct loongarch_pch_pic *s = dev->kvm->arch.pch_pic;
 
-	s->pch_pic_base = addr;
 	device = &s->device;
+	mutex_lock(&kvm->slots_lock);
+	if (s->device.ops) {
+		ret = -EEXIST;
+		goto out;
+	}
+	s->pch_pic_base = addr;
 	/* init device by pch pic writing and reading ops */
 	kvm_iodevice_init(device, &kvm_pch_pic_ops);
-	mutex_lock(&kvm->slots_lock);
 	/* register pch pic device */
 	ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, addr, PCH_PIC_SIZE, device);
+	if (ret) {
+		s->pch_pic_base = 0;
+		s->device.ops = NULL;
+	}
+out:
 	mutex_unlock(&kvm->slots_lock);
 
-	return (ret < 0) ? -EFAULT : 0;
+	return ret;
 }
 
 /* used by user space to get or set pch pic registers */
author maintainer
#782 lore raw

PATCH 781/1005 tracing/perf: Clear stop state in perf_trace_add()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Paolo Bertinetti <[email protected]>

commit fb3f6b21b04f1e8b8982e90e9bf62db9f0dcb5e4 upstream.

Since commit 18dbcbfabfff ("perf: Fix the POLL_HUP delivery breakage"), __perf_event_overflow() stops the event with pmu->stop() and disables it when the PERF_EVENT_IOC_REFRESH limit is reached. When userspace re-arms the event with PERF_EVENT_IOC_REFRESH, the event is enabled again and pmu->add() is called with PERF_EF_START.

perf_trace_add() sets PERF_HES_STOPPED when PERF_EF_START is missing, but never clears it. The flag set by pmu->stop() stays, and perf_tp_event_match() drops every later hit. A tracepoint, kprobe or uprobe event re-armed this way delivers only its first overflow. This breaks self-profilers such as async-profiler, and the "Event re-armed with PERF_EVENT_IOC_REFRESH" perf test fails:

1000 events, count 1, 1 overflows (1 POLL_HUP), re-arm errno 0 Tracepoint event : FAILED!

Set the state from PERF_EF_START on every add, as perf_swevent_add() does.

---
 kernel/trace/trace_event_perf.c |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
kernel/trace/trace_event_perf.c +1 -2
@@ -354,8 +354,7 @@ int perf_trace_add(struct perf_event *p_
 	struct trace_event_call *tp_event = p_event->tp_event;
 	struct hw_perf_event *hwc = &p_event->hw;
 
-	if (!(flags & PERF_EF_START))
-		p_event->hw.state = PERF_HES_STOPPED;
+	hwc->state = (flags & PERF_EF_START) ? 0 : PERF_HES_STOPPED;
 
 	if (is_sampling_event(p_event)) {
 		hwc->last_period = hwc->sample_period;
author maintainer
#783 lore raw

PATCH 782/1005 tracing/uprobes: Fix memory leak of tail in __trace_uprobe_create()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit c15120853eebbda98f3fe1f1e59370439c6c4447 upstream.

When generating a default event name in __trace_uprobe_create(), tail is allocated with kstrdup() without __free(kfree). If the subsequent kmalloc() for buf fails, the function returns -ENOMEM immediately and leaks tail.

Declare tail with __free(kfree) so it is automatically freed on all exit paths.

Fixes 97e8230f89a3 ("tracing: uprobe-event: Allocate string buffers from heap")
---
 kernel/trace/trace_uprobe.c |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
kernel/trace/trace_uprobe.c +1 -2
@@ -663,7 +663,7 @@ static int __trace_uprobe_create(int arg
 	}
 
 	if (!event) {
-		char *tail;
+		char *tail __free(kfree) = NULL;
 		char *ptr;
 
 		tail = kstrdup(kbasename(filename), GFP_KERNEL);
@@ -679,7 +679,6 @@ static int __trace_uprobe_create(int arg
 			return -ENOMEM;
 		snprintf(buf, MAX_EVENT_NAME_LEN, "%c_%s_0x%lx", 'p', tail, offset);
 		event = buf;
-		kfree(tail);
 	}
 
 	argc -= 2;
author maintainer
#784 lore raw

PATCH 783/1005 tracing/eprobe: Fix 1-byte signed field fetch in get_event_field()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit a0f836eea463d4c468edb58eedb03911c9c0791d upstream.

Because the kernel is built with -funsigned-char, plain 'char' is unsigned on all architectures. Reading 1-byte signed trace event fields via *(char *)addr in get_event_field() therefore zero-extends instead of sign-extending negative s8 values.

Use explicit fixed-width integer types (s8/u8, s16/u16, s32/u32) when reading event fields.

Fixes 7491e2c44278 ("tracing: Add a probe that attaches to trace events")
---
 kernel/trace/trace_eprobe.c |   12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
kernel/trace/trace_eprobe.c +6 -6
@@ -330,21 +330,21 @@ get_event_field(struct fetch_insn *code,
 	switch (field->size) {
 	case 1:
 		if (field->is_signed)
-			val = *(char *)addr;
+			val = *(s8 *)addr;
 		else
-			val = *(unsigned char *)addr;
+			val = *(u8 *)addr;
 		break;
 	case 2:
 		if (field->is_signed)
-			val = *(short *)addr;
+			val = *(s16 *)addr;
 		else
-			val = *(unsigned short *)addr;
+			val = *(u16 *)addr;
 		break;
 	case 4:
 		if (field->is_signed)
-			val = *(int *)addr;
+			val = *(s32 *)addr;
 		else
-			val = *(unsigned int *)addr;
+			val = *(u32 *)addr;
 		break;
 	default:
 		if (field->size == sizeof(long)) {
author maintainer
#785 lore raw

PATCH 784/1005 tracing/eprobe: Disallow attaching eprobes to fprobe events

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit 92d9fa0ed69e1f724feed908bd0a462a42df4b88 upstream.

Event probes (eprobes) are not allowed to attach to other dynamic probe events (kprobes, uprobes, and eprobes) to avoid recursive probe chains and lifecycle dependencies. However, when fprobe events were introduced, TRACE_EVENT_FL_FPROBE was omitted from the exclusion mask in find_and_get_event(), allowing eprobes to attach to fprobe and tprobe events.

Exclude TRACE_EVENT_FL_FPROBE events in find_and_get_event().

Fixes 334e5519c375 ("tracing/probes: Add fprobe events for tracing function entry and exit.")
---
 kernel/trace/trace_eprobe.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/trace/trace_eprobe.c +2 -1
@@ -758,7 +758,8 @@ find_and_get_event(const char *system, c
 		    (TRACE_EVENT_FL_IGNORE_ENABLE |
 		     TRACE_EVENT_FL_KPROBE |
 		     TRACE_EVENT_FL_UPROBE |
-		     TRACE_EVENT_FL_EPROBE))
+		     TRACE_EVENT_FL_EPROBE |
+		     TRACE_EVENT_FL_FPROBE))
 			continue;
 		if (!tp_event->class->system ||
 		    strcmp(system, tp_event->class->system))
author maintainer
#786 lore raw

PATCH 785/1005 tracing/probes: Check enabled and busy state before unlinking sibling probes

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit f1d9b7a3fe99b4228acdbab3c744c29f7ffe86ef upstream.

When a multiprobe event is enabled or referenced (for example, by an eprobe, trigger, or open tracefs file) and a user attempts to delete the event or one of its probes via dynamic_events, checking trace_probe_has_sibling() before the enabled and busy checks allows the first probe to be unlinked and freed while the event is still active, only returning -EBUSY on the last sibling probe. For uprobe events, unlinking and freeing an enabled sibling probe without unregistering its uprobe_consumer also causes a use-after-free.

Ensure all four probe types (kprobe, fprobe, uprobe, and eprobe) verify that the event is neither enabled nor busy before unlinking any sibling probe.

Fixes ca89bc071d5e ("tracing/kprobe: Add multi-probe per event support")
Fixes 41af3cf587f4 ("tracing/uprobe: Add multi-probe per uprobe event support")
Fixes 7491e2c44278 ("tracing: Add a probe that attaches to trace events")
Fixes 334e5519c375 ("tracing/probes: Add fprobe events for tracing function entry and exit.")
---
 kernel/trace/trace_eprobe.c |   12 ++++++++----
 kernel/trace/trace_fprobe.c |    8 ++++----
 kernel/trace/trace_kprobe.c |    8 ++++----
 kernel/trace/trace_uprobe.c |    8 ++++++--
 4 files changed, 22 insertions(+), 14 deletions(-)
kernel/trace/trace_eprobe.c +8 -4
@@ -94,14 +94,18 @@ static int eprobe_dyn_event_show(struct
 
 static int unregister_trace_eprobe(struct trace_eprobe *ep)
 {
-	/* If other probes are on the event, just unregister eprobe */
-	if (trace_probe_has_sibling(&ep->tp))
-		goto unreg;
-
 	/* Enabled event can not be unregistered */
 	if (trace_probe_is_enabled(&ep->tp))
 		return -EBUSY;
 
+	/* If there's a reference to the dynamic event */
+	if (trace_event_dyn_busy(trace_probe_event_call(&ep->tp)))
+		return -EBUSY;
+
+	/* If other probes are on the event, just unregister eprobe */
+	if (trace_probe_has_sibling(&ep->tp))
+		goto unreg;
+
 	/* Will fail if probe is being used by ftrace or perf */
 	if (trace_probe_unregister_event_call(&ep->tp))
 		return -EBUSY;
kernel/trace/trace_fprobe.c +4 -4
@@ -853,10 +853,6 @@ static void __unregister_trace_fprobe(st
 /* Unregister a trace_probe and probe_event */
 static int unregister_trace_fprobe(struct trace_fprobe *tf)
 {
-	/* If other probes are on the event, just unregister fprobe */
-	if (trace_probe_has_sibling(&tf->tp))
-		goto unreg;
-
 	/* Enabled event can not be unregistered */
 	if (trace_probe_is_enabled(&tf->tp))
 		return -EBUSY;
@@ -865,6 +861,10 @@ static int unregister_trace_fprobe(struc
 	if (trace_event_dyn_busy(trace_probe_event_call(&tf->tp)))
 		return -EBUSY;
 
+	/* If other probes are on the event, just unregister fprobe */
+	if (trace_probe_has_sibling(&tf->tp))
+		goto unreg;
+
 	/* Will fail if probe is being used by ftrace or perf */
 	if (unregister_fprobe_event(tf))
 		return -EBUSY;
kernel/trace/trace_kprobe.c +4 -4
@@ -548,10 +548,6 @@ static void __unregister_trace_kprobe(st
 /* Unregister a trace_probe and probe_event */
 static int unregister_trace_kprobe(struct trace_kprobe *tk)
 {
-	/* If other probes are on the event, just unregister kprobe */
-	if (trace_probe_has_sibling(&tk->tp))
-		goto unreg;
-
 	/* Enabled event can not be unregistered */
 	if (trace_probe_is_enabled(&tk->tp))
 		return -EBUSY;
@@ -560,6 +556,10 @@ static int unregister_trace_kprobe(struc
 	if (trace_event_dyn_busy(trace_probe_event_call(&tk->tp)))
 		return -EBUSY;
 
+	/* If other probes are on the event, just unregister kprobe */
+	if (trace_probe_has_sibling(&tk->tp))
+		goto unreg;
+
 	/* Will fail if probe is being used by ftrace or perf */
 	if (unregister_kprobe_event(tk))
 		return -EBUSY;
kernel/trace/trace_uprobe.c +6 -2
@@ -396,13 +396,17 @@ static int unregister_trace_uprobe(struc
 {
 	int ret;
 
-	if (trace_probe_has_sibling(&tu->tp))
-		goto unreg;
+	/* Enabled event can not be unregistered */
+	if (trace_probe_is_enabled(&tu->tp))
+		return -EBUSY;
 
 	/* If there's a reference to the dynamic event */
 	if (trace_event_dyn_busy(trace_probe_event_call(&tu->tp)))
 		return -EBUSY;
 
+	if (trace_probe_has_sibling(&tu->tp))
+		goto unreg;
+
 	ret = unregister_uprobe_event(tu);
 	if (ret)
 		return ret;
author maintainer
#787 lore raw

PATCH 786/1005 tracing/probes: Enable newly appended probe when target event is enabled

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit 72d3a5cb0cd7335553549aaffecc683e3ecc0c43 upstream.

Unlike kprobe events, fprobe and uprobe events only register their underlying probes when the trace event is enabled. When a new probe is appended to an existing multiprobe fprobe or uprobe event that is already enabled, the appended probe is linked into the event's probe list without being registered.

As a result, the newly appended probe never fires until the event is disabled and re-enabled. Moreover, disabling an fprobe event calls unregister_fprobe() on the unregistered fprobe, and opening or closing a perf event on an enabled uprobe event dereferences a NULL tu->uprobe in uprobe_apply().

Register and enable the newly appended fprobe or uprobe immediately when the target event is already enabled.

Fixes 41af3cf587f4 ("tracing/uprobe: Add multi-probe per uprobe event support")
Fixes 2db832ec9090 ("tracing: fprobe-events: Register fprobe-events only when it is enabled")
---
 kernel/trace/trace_fprobe.c |   14 ++++-------
 kernel/trace/trace_uprobe.c |   56 +++++++++++++++++++++++++++++---------------
 2 files changed, 43 insertions(+), 27 deletions(-)
kernel/trace/trace_fprobe.c +6 -8
@@ -933,7 +933,10 @@ static int append_trace_fprobe_event(str
 	if (ret)
 		return ret;
 
-	ret = trace_fprobe_verify_target(tf);
+	if (trace_probe_is_enabled(&tf->tp))
+		ret = __register_trace_fprobe(tf);
+	else
+		ret = trace_fprobe_verify_target(tf);
 	if (ret)
 		trace_probe_unlink(&tf->tp);
 	else
@@ -1520,13 +1523,8 @@ static int disable_trace_fprobe(struct t
 		trace_probe_clear_flag(tp, TP_FLAG_PROFILE);
 
 	if (!trace_probe_is_enabled(tp)) {
-		list_for_each_entry(tf, trace_probe_probe_list(tp), tp.list) {
-			unregister_fprobe(&tf->fp);
-			if (tf->tuser) {
-				tracepoint_user_put(tf->tuser);
-				tf->tuser = NULL;
-			}
-		}
+		list_for_each_entry(tf, trace_probe_probe_list(tp), tp.list)
+			__unregister_trace_fprobe(tf);
 	}
 
  out:
kernel/trace/trace_uprobe.c +37 -19

75 lines not on this page · raw message

author maintainer
#788 lore raw

PATCH 787/1005 tracing/probes: Fix BTF bitfield parsing and out-of-bounds buffer write

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit 9b6e9d6a11090ac34516c45f48663b37ac94a9b1 upstream.

BTF bitfield parsing in trace_probe.c assumes a 64-bit (8-byte) container when computing FETCH_OP_MOD_BF shift amounts and basesize, whereas the preceding store instruction only allocates and writes the field's fetch type size (which may be 1, 2, or 4 bytes when kflag=1). At runtime, fetch_apply_bitfield() performs an 8-byte read-modify-write on the smaller ring buffer slot, corrupting adjacent ring buffer data or writing past the end of the event record.

In addition, signed bitfields with bit widths other than 8/16/32/64 fail to resolve a fetch type, bitfields whose width is a multiple of 8 inside a larger integer or spanning a byte boundary fail to emit FETCH_OP_MOD_BF or select a container wide enough for bitoffs + bitsize, kflag=0 bitfield offsets >= 8 bits are not folded into the byte offset, and big-endian architectures use the little-endian left-shift formula in parse_btf_bitfield().

Compute the bitfield byte and bit offsets consistently during field lookup, select the smallest unsigned fetch type that covers the bit offset and bit width, and calculate the FETCH_OP_MOD_BF parameters from the selected fetch type size for both big- and little-endian bitfields.

Fixes c440adfbe302 ("tracing/probes: Support BTF based data structure field access")
---
 kernel/trace/trace_probe.c |   59 ++++++++++++++++++++++++++++++++++-----------
 1 file changed, 45 insertions(+), 14 deletions(-)
kernel/trace/trace_probe.c +45 -14
@@ -486,6 +486,18 @@ static const char *fetch_type_from_btf_t
 {
 	u32 intdata;
 
+	if (ctx->last_bitsize) {
+		u32 bits = ctx->last_bitsize + ctx->last_bitoffs;
+
+		if (bits <= 8)
+			return "u8";
+		if (bits <= 16)
+			return "u16";
+		if (bits <= 32)
+			return "u32";
+		return "u64";
+	}
+
 	/* TODO: const char * could be converted as a string */
 	switch (BTF_INFO_KIND(type->info)) {
 	case BTF_KIND_ENUM:
@@ -520,10 +532,6 @@ static const char *fetch_type_from_btf_t
 			case 64:
 				return "u64";
 			}
-			/* bitfield, size is encoded in the type */
-			ctx->last_bitsize = BTF_INT_BITS(intdata);
-			ctx->last_bitoffs += BTF_INT_OFFSET(intdata);
-			return "u64";
 		}
 	}
 	/* TODO: support other types */
@@ -653,6 +661,12 @@ static int get_bitoffset_of_field(char *
 		/* Add anonymous structure/union offset */
 		bitoffs += anon_offs;
 
+		type = btf_type_skip_modifiers(btf, field->type, NULL);
+		if (!type) {
+			trace_probe_log_err(ctx->offset, BAD_BTF_TID);
+			return -EINVAL;
+		}
+
 		/* Accumulate the bit-offsets of the dot-connected fields */
 		if (btf_type_kflag(mtype)) {
 			bitoffs += BTF_MEMBER_BIT_OFFSET(field->offset);
@@ -660,12 +674,15 @@ static int get_bitoffset_of_field(char *
 		} else {
 			bitoffs += field->offset;
 			ctx->last_bitsize = 0;
-		}
+			if (BTF_INFO_KIND(type->info) == BTF_KIND_INT) {
+				u32 intdata = btf_type_int(type);
 
-		type = btf_type_skip_modifiers(btf, field->type, NULL);
-		if (!type) {
-			trace_probe_log_err(ctx->offset, BAD_BTF_TID);
-			return -EINVAL;
+				bitoffs += BTF_INT_OFFSET(intdata);
+				if ((bitoffs % 8) ||
+				    BTF_INT_BITS(intdata) != BYTES_TO_BITS(type->size) ||
+				    !is_power_of_2(type->size))
+					ctx->last_bitsize = BTF_INT_BITS(intdata);
+			}
 		}
 
 		if (next)
@@ -858,13 +875,22 @@ static const struct fetch_type *find_fet
 }
 
 static int parse_btf_bitfield(struct fetch_insn **pcode,
+			      const struct fetch_type *t,
 			      struct traceprobe_parse_context *ctx)
 {
 	struct fetch_insn *code = *pcode;
 
-	if ((ctx->last_bitsize % 8 == 0) && ctx->last_bitoffs == 0)
+	if ((ctx->last_bitsize == 0 ||
+	     ctx->last_bitsize == BYTES_TO_BITS(t->size)) &&
+	    ctx->last_bitoffs == 0)
 		return 0;
 
+	if (ctx->last_bitsize == 0 ||
+	    BYTES_TO_BITS(t->size) < (ctx->last_bitsize + ctx->last_bitoffs)) {
+		trace_probe_log_err(ctx->offset, BAD_BITFIELD);
+		return -EINVAL;
+	}
+
 	code++;
 	if (code->op != FETCH_OP_NOP) {
 		trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
@@ -873,9 +899,13 @@ static int parse_btf_bitfield(struct fet
 	*pcode = code;
 
 	code->op = FETCH_OP_MOD_BF;
-	code->lshift = 64 - (ctx->last_bitsize + ctx->last_bitoffs);
-	code->rshift = 64 - ctx->last_bitsize;
-	code->basesize = 64 / 8;
+#ifdef __BIG_ENDIAN_BITFIELD
+	code->lshift = ctx->last_bitoffs;
+#else
+	code->lshift = BYTES_TO_BITS(t->size) - (ctx->last_bitsize + ctx->last_bitoffs);
+#endif
+	code->rshift = BYTES_TO_BITS(t->size) - ctx->last_bitsize;
+	code->basesize = t->size;
 	return 0;
 }
 
@@ -1085,6 +1115,7 @@ static int parse_btf_arg(char *varname,
 }
 
 static int parse_btf_bitfield(struct fetch_insn **pcode,
+			      const struct fetch_type *t,
 			      struct traceprobe_parse_context *ctx)
 {
 	trace_probe_log_err(ctx->offset, NOSUP_BTFARG);
@@ -1995,7 +2026,7 @@ static int finalize_fetch_insn(struct fe
 	} else if (IS_ENABLED(CONFIG_PROBE_EVENTS_BTF_ARGS) &&
 		   ctx->last_type) {
 		/* If user not specified the type, try parsing BTF bitfield. */
-		ret = parse_btf_bitfield(&code, ctx);
+		ret = parse_btf_bitfield(&code, parg->type, ctx);
 		if (ret)
 			return ret;
 	}
author maintainer
#789 lore raw

PATCH 788/1005 tracing/probes: Fix missing BTF kind checks in char pointer/array helpers

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit c1e2c63e65421068566db3dde44dfd4fe7adb46d upstream.

In struct btf_type, the type ID and byte size share a union, and only BTF_KIND_INT types are followed by a 32-bit integer encoding word. Because btf_type_is_char_ptr() and btf_type_is_char_array() do not verify that the outer type is BTF_KIND_PTR or that the resolved element type is a non-NULL BTF_KIND_INT before inspecting it, non-pointer BTF types can have their byte size misinterpreted as a BTF type ID, and arrays of non-integer types read out-of-bounds or misinterpret trailing BTF metadata as BTF_INT_* encoding bits.

Validate the BTF type kinds and NULL pointers before reading inner type metadata in both helpers.

Fixes 27973e5c64b9 ("tracing/probes: Add string type check with BTF")
---
 kernel/trace/trace_probe.c |    8 ++++++++
 1 file changed, 8 insertions(+)
kernel/trace/trace_probe.c +8 -0
@@ -411,6 +411,9 @@ static bool btf_type_is_char_ptr(struct
 	const struct btf_type *real_type;
 	u32 intdata;
 
+	if (BTF_INFO_KIND(type->info) != BTF_KIND_PTR)
+		return false;
+
 	real_type = btf_type_skip_modifiers(btf, type->type, NULL);
 	if (!real_type)
 		return false;
@@ -435,6 +438,11 @@ static bool btf_type_is_char_array(struc
 	array = (const struct btf_array *)(type + 1);
 
 	real_type = btf_type_skip_modifiers(btf, array->type, NULL);
+	if (!real_type)
+		return false;
+
+	if (BTF_INFO_KIND(real_type->info) != BTF_KIND_INT)
+		return false;
 
 	intdata = btf_type_int(real_type);
 	return !(BTF_INT_ENCODING(intdata) & BTF_INT_SIGNED)
author maintainer
#790 lore raw

PATCH 789/1005 tracing/probes: Fix user-space dereference string array store type

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit 2721573e6c6faaba2e31f352f2c02ec5f3ecf5e9 upstream.

When finalizing a string array argument (e.g. +0u(%reg):string[N]), finalize_fetch_insn() advances the instruction pointer to a new slot for the store operation before checking whether the preceding operation was FETCH_OP_UDEREF. As a result, user-space dereference string arrays with type "string" emit FETCH_OP_ST_STRING (kernel memory read) instead of FETCH_OP_ST_USTRING.

Check for FETCH_OP_UDEREF before advancing the instruction pointer.

Fixes e65f7ae7f4da ("tracing/probe: Support user-space dereference")
---
 kernel/trace/trace_probe.c |    6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
kernel/trace/trace_probe.c +4 -2
@@ -1956,6 +1956,8 @@ static int finalize_fetch_insn(struct fe
 
 	/* Store operation */
 	if (parg->type->is_string) {
+		bool is_uderef;
+
 		/* Check bad combination of the type and the last fetch_insn. */
 		if (!strcmp(parg->type->name, "symstr")) {
 			if (code->op != FETCH_OP_REG && code->op != FETCH_OP_STACK &&
@@ -1975,6 +1977,7 @@ static int finalize_fetch_insn(struct fe
 			}
 		}
 
+		is_uderef = (code->op == FETCH_OP_UDEREF);
 		if (!strcmp(parg->type->name, "symstr") ||
 		    (code->op == FETCH_OP_IMM || code->op == FETCH_OP_COMM ||
 		     code->op == FETCH_OP_IMMSTR) || code->op == FETCH_OP_TP_ARG ||
@@ -1995,8 +1998,7 @@ static int finalize_fetch_insn(struct fe
 		}
 
 		/* If op == DEREF, replace it with STRING */
-		if (!strcmp(parg->type->name, "ustring") ||
-		    code->op == FETCH_OP_UDEREF)
+		if (!strcmp(parg->type->name, "ustring") || is_uderef)
 			code->op = FETCH_OP_ST_USTRING;
 		else if (!strcmp(parg->type->name, "symstr"))
 			code->op = FETCH_OP_ST_SYMSTR;
author maintainer
#791 lore raw

PATCH 790/1005 tracing/probes: Reject array count on non-dereference string sources

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit 0941144ebeaf3ce46c80711f00e935921eb28b21 upstream.

The runtime array loop (FETCH_OP_LP_ARRAY) for string types requires a preceding memory dereference instruction so it can advance the pointer address on each iteration. Non-dereference string sources such as $comm, immediate strings, and eprobe event fields cannot be indexed as pointer arrays, but finalize_fetch_insn() still accepts an array count on them and emits an invalid FETCH_OP_LP_ARRAY sequence.

Reject string array counts when the preceding operation is not a memory dereference.

Fixes 40b53b771806 ("tracing: probeevent: Add array type support")
---
 kernel/trace/trace_probe.c |    6 ++++++
 1 file changed, 6 insertions(+)
kernel/trace/trace_probe.c +6 -0
@@ -1990,6 +1990,12 @@ static int finalize_fetch_insn(struct fe
 			 * For the symstr, it doesn't need to dereference, thus
 			 * it just get the value.
 			 */
+			if (parg->count && (code->op != FETCH_OP_DEREF &&
+					    code->op != FETCH_OP_UDEREF)) {
+				trace_probe_log_err(ctx->offset + type_offset,
+						    BAD_STRING);
+				return -EINVAL;
+			}
 			code++;
 			if (code->op != FETCH_OP_NOP) {
 				trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
author maintainer
#792 lore raw

PATCH 791/1005 wifi: ath12k: assign device id from the WSI index

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Benoit Masson <[email protected]>

commit 81986a81f09fae73926c7c44863b335880269c90 upstream.

Devices of a hardware group are added to ag->ab[] in PCI probe completion order (ab->device_id = ag->num_probed++), which is not stable across boots. The wiphy radio array is built from ag->ab[] and the wiphy device is taken from its first entry, so the wiphy sysfs path and the mapping of radio indices to bands change on every boot.

Persisted wireless configurations reference radios by index (e.g. OpenWrt/hostapd "radio0"), so such a configuration attaches to a random band at each boot. This affects any multi-chip group with single-band radios, e.g. TP-Link Archer BE800 (three QCN9274/QCN9224 radios in one group).

Store each ab in ag->ab[] at its wsi_info.index, which is derived from the device tree WSI ring and is therefore deterministic. ag->num_probed remains the group device counter. The unassign path is unchanged, it already indexes ag->ab[] by ab->device_id.

---
 drivers/net/wireless/ath/ath12k/core.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/wireless/ath/ath12k/core.c +2 -1
@@ -2007,7 +2007,8 @@ exit:
 		goto invalid_group;
 	}
 
-	ab->device_id = ag->num_probed++;
+	ag->num_probed++;
+	ab->device_id = wsi->index;
 	ag->ab[ab->device_id] = ab;
 	ab->ag = ag;
 
author maintainer
#793 lore raw

PATCH 792/1005 wifi: ath9k_htc: do not start ANI before the first channel is set

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mehmet Fide <[email protected]>

commit dda63dd136ba2bc3b297079b190ac81a0aea40ae upstream.

ath9k_htc_add_interface() starts ANI for the first AP interface, before any channel is configured. The per-channel calibration data only gets attached by the first ath9k_htc_set_channel() that is not a fast channel change, and that same call cancels the ANI work a few milliseconds after add_interface, so normally the work never runs.

When the bring-up stalls for more than the 100 ms ANI poll interval in between, it does run, and ar9002_hw_per_calibration() records the IQ calibration result in the calibration data that does not exist yet:

  Unable to handle kernel NULL pointer dereference at virtual address
  00000008
  PC is at ar9002_hw_calibrate+0x1f8/0x570 [ath9k_hw]
  Workqueue: phy0 ath9k_htc_ani_work [ath9k_htc]

Seen about once per thousand AP starts with an AR9271 on a Cortex-A5 board that starts hostapd while still booting; a 500 ms delay after add_interface reproduces it on every start. The crashed work never completes, so the next cancel_delayed_work_sync() blocks for good.

Drop the start; it has nothing to calibrate against and is cancelled anyway. The TSF adjust bit that shared its condition is now set for every AP interface, which is harmless: the next reset applies it. The next patch starts ANI once the interface beacons.

---
 drivers/net/wireless/ath/ath9k/htc_drv_main.c |    5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)
drivers/net/wireless/ath/ath9k/htc_drv_main.c +1 -4
@@ -1098,11 +1098,8 @@ static int ath9k_htc_add_interface(struc
 
 	ath9k_htc_set_opmode(priv);
 
-	if ((priv->ah->opmode == NL80211_IFTYPE_AP) &&
-	    !test_bit(ATH_OP_ANI_RUN, &common->op_flags)) {
+	if (priv->ah->opmode == NL80211_IFTYPE_AP)
 		ath9k_hw_set_tsfadjust(priv->ah, true);
-		ath9k_htc_start_ani(priv);
-	}
 
 	ath_dbg(common, CONFIG, "Attach a VIF of type: %d at idx: %d\n",
 		vif->type, avp->index);
author maintainer
#794 lore raw

PATCH 793/1005 wifi: mac80211_hwsim: ignore non-generic netlink releases

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit 989f47c56e48d442d79497a25ed946d029c4dc53 upstream.

Closing an unrelated netlink socket can remove mac80211_hwsim radios or clear the active wmediumd registration when its port ID matches a generic netlink socket.

mac80211_hwsim_netlink_notify() handles every NETLINK_URELEASE event, but netlink port IDs are scoped by protocol. The notifier therefore treats a release from another protocol as a MAC80211_HWSIM socket release.

Ignore release notifications unless they come from NETLINK_GENERIC.

LLM assistance was used to find the bug and review.

Fixes 7882513bacb1 ("mac80211_hwsim driver support userspace frame tx/rx")
Fixes e9ed49bf4c2c ("mac80211-hwsim: Add support for HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE")
---
 drivers/net/wireless/virtual/mac80211_hwsim_main.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/wireless/virtual/mac80211_hwsim_main.c +1 -1
@@ -7197,7 +7197,7 @@ static int mac80211_hwsim_netlink_notify
 {
 	struct netlink_notify *notify = _notify;
 
-	if (state != NETLINK_URELEASE)
+	if (state != NETLINK_URELEASE || notify->protocol != NETLINK_GENERIC)
 		return NOTIFY_DONE;
 
 	remove_user_radios(notify->portid, hwsim_net_get_netgroup(notify->net));
author maintainer
#795 lore raw

PATCH 794/1005 wifi: nxpwifi: validate scan response TLV sizes before indexed access

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tristan Madani <[email protected]>

commit bcc5bbaa6de61a0ccaa57228ca233b4390eca27e upstream.

The scan response handler indexes into TSF and channel-band TLV arrays using a loop counter derived from the number of BSS entries, but never checks whether the TLV data is large enough. A firmware response with fewer TLV entries than BSS entries leads to reads past the TLV buffer.

Add bounds checks that verify each indexed access falls within the TLV's declared length before dereferencing.

Fixes 73b01e57ed3e ("wifi: nxp: add nxpwifi driver for IW61x")
---
 drivers/net/wireless/nxp/nxpwifi/scan.c |   18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)
drivers/net/wireless/nxp/nxpwifi/scan.c +14 -4
@@ -2017,12 +2017,22 @@ int nxpwifi_ret_802_11_scan(struct nxpwi
 		 * was received.
 		 */
 		if (tsf_tlv)
-			memcpy(&fw_tsf, &tsf_tlv->tsf_data[idx * TSF_DATA_SIZE],
-			       sizeof(fw_tsf));
+			if ((idx + 1) * TSF_DATA_SIZE <=
+			    le16_to_cpu(tsf_tlv->header.len))
+				memcpy(&fw_tsf,
+				       &tsf_tlv->tsf_data[idx *
+							  TSF_DATA_SIZE],
+				       sizeof(fw_tsf));
 
 		if (chan_band_tlv) {
-			chan_band = &chan_band_tlv->chan_band_param[idx];
-			radio_type = &chan_band->radio_type;
+			if ((idx + 1) * sizeof(*chan_band) <=
+			    le16_to_cpu(chan_band_tlv->header.len)) {
+				chan_band =
+					&chan_band_tlv->chan_band_param[idx];
+				radio_type = &chan_band->radio_type;
+			} else {
+				radio_type = NULL;
+			}
 		} else {
 			radio_type = NULL;
 		}
author maintainer
#796 lore raw

PATCH 795/1005 wifi: cfg80211: release rejected nontransmitted BSS reference

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit f3c45d5b741a7d7586e639c2f55d2557029f2e1a upstream.

Repeated MBSSID reports without an SSID can leak BSS entries outside the scan cache, where the BSS entry limit cannot account for them.

__cfg80211_bss_update() returns a referenced BSS. If adding it to the transmitting BSS list fails, unlinking drops the cache reference, but the caller reference is lost when res is cleared.

Release the caller reference before discarding the unlinked BSS.

LLM assistance was used to find the bug and review.

Fixes 0b7808818cb9 ("wifi: cfg80211: fix BSS refcounting bugs")
---
 net/wireless/scan.c |    1 +
 1 file changed, 1 insertion(+)
net/wireless/scan.c +1 -0
@@ -2452,6 +2452,7 @@ cfg80211_inform_single_bss_data(struct w
 		if (cfg80211_add_nontrans_list(data->source_bss, &res->pub)) {
 			if (__cfg80211_unlink_bss(rdev, res)) {
 				rdev->bss_generation++;
+				bss_ref_put(rdev, res);
 				res = NULL;
 			}
 		}
author maintainer
#797 lore raw

PATCH 796/1005 wifi: cfg80211: preserve mesh A-MSDU lengths when adding mesh headers

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit 9083da9dd3223068237395432323b407012aec1f upstream.

A malformed mesh A-MSDU subframe with a declared payload length near 65535 bytes can pass validation against a much shorter aggregate.

ieee80211_amsdu_subframe_length() adds the mesh control length to the declared length in a u16, and ieee80211_is_valid_amsdu() stores the result in a u16 local. The sum therefore wraps before either walker compares it with the remaining aggregate length. The decomposer then splits and delivers the malformed aggregate instead of rejecting it.

Keep the computed length in unsigned int in both the helper and the validator so oversized subframes cannot wrap.

LLM assistance was used to find the bug and review.

Fixes 6e4c0d0460bd ("wifi: mac80211: add a workaround for receiving non-standard mesh A-MSDU")
Fixes fe4a6d2db3ba ("wifi: mac80211: implement support for yet another mesh A-MSDU format")
---
 net/wireless/util.c |    6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
net/wireless/util.c +3 -3
@@ -822,12 +822,12 @@ __ieee80211_amsdu_copy(struct sk_buff *s
 	return frame;
 }
 
-static u16
+static unsigned int
 ieee80211_amsdu_subframe_length(void *field, u8 mesh_flags, u8 hdr_type)
 {
 	__le16 *field_le = field;
 	__be16 *field_be = field;
-	u16 len;
+	unsigned int len;
 
 	if (hdr_type >= 2)
 		len = le16_to_cpu(*field_le);
@@ -849,7 +849,7 @@ bool ieee80211_is_valid_amsdu(struct sk_
 		    __be16 len;
 		    u8 mesh_flags;
 		} hdr;
-		u16 len;
+		unsigned int len;
 
 		if (sizeof(hdr) > remaining)
 			return false;
author maintainer
#798 lore raw

PATCH 797/1005 wifi: cfg80211: dont truncate the merged MBSSID profile length

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Wahid Khan <[email protected]>

commit 3ea152f3f77eeffc37b2f4423688b4df9136f90c upstream.

cfg80211_parse_mbssid_data() keeps the length of a non-transmitted BSSID profile in a u8. cfg80211_merge_profile() returns a size_t, and it concatenates a profile that is split over several Multiple BSSID elements, so the merged length can be well above 255 even though every single sub-element is at most 255 bytes long.

The value is then cut to its low 8 bits. A 300 byte profile is handled as a 44 byte one: the elements after the cut are lost from the generated non-transmitted BSS, and if the Multiple BSSID-Index element lies past the cut the BSS is dropped altogether. Any AP in range can send such a profile.

The multi-link code further down in the same file already uses a signed size type for the profile length. Do the same here, cfg80211_find_ie() and cfg80211_gen_new_ie() take a size_t anyway.

Fixes fe806e4992c9 ("cfg80211: support profile split between elements")
---
 net/wireless/scan.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/wireless/scan.c +1 -1
@@ -2592,7 +2592,7 @@ cfg80211_parse_mbssid_data(struct wiphy
 		if (elem->data[0] < 1 || (int)elem->data[0] > 8)
 			continue;
 		for_each_element(sub, elem->data + 1, elem->datalen - 1) {
-			u8 profile_len;
+			size_t profile_len;
 
 			if (sub->id != 0 || sub->datalen < 4) {
 				/* not a valid BSS profile */
author maintainer
#799 lore raw

PATCH 798/1005 wifi: mac80211: fix use-after-free when MLO link setup is rolled back

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit a155ef2ef79531c139244289c5b8f15c05d16a0e upstream.

Rolling back an MLO link addition can free link containers while RCU readers still hold pointers to them. ieee80211_vif_update_links() publishes new links before checking for duplicate addresses and calling drv_change_vif_links(). If either fails, it restores the old pointers and frees the new containers without waiting for readers.

During a non-MLO to MLO transition, the published link 0 replaces the deflink, so existing link 0 users can acquire the new container. Readers such as ieee80211_csa_finish() and ieee80211_obss_color_collision_notify() can also queue work embedded in the link. If they queue after ieee80211_link_stop() cancels that work, it remains queued when the container is freed.

Wait for RCU readers after restoring the old pointers and before stopping the new links, so their work is queued before it is cancelled.

Fixes d3e2439b0f33 ("wifi: mac80211: fix link manipulation")
---
 net/mac80211/link.c |    2 ++
 1 file changed, 2 insertions(+)
net/mac80211/link.c +2 -0
@@ -400,6 +400,8 @@ static int ieee80211_vif_update_links(st
 		memcpy(sdata->link, old_data, sizeof(old_data));
 		memcpy(sdata->vif.link_conf, old, sizeof(old));
 		ieee80211_set_vif_links_bitmaps(sdata, old_links, dormant_links);
+		/* drain RCU readers before cancelling work they may queue */
+		synchronize_rcu();
 		for_each_set_bit(link_id, &add, IEEE80211_MLD_MAX_NUM_LINKS) {
 			ieee80211_link_debugfs_remove(&links[link_id]->data);
 			ieee80211_link_stop(&links[link_id]->data);
author maintainer
#800 lore raw

PATCH 799/1005 wifi: mac80211: drain link readers before stopping removed links

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit 745f5d04395dfc4c311f443c7c04ccb00c436984 upstream.

Removing an MLO link can leave work queued on its link container after the container is freed.

ieee80211_tear_down_links() stops each link before the RCU grace period. A reader that fetched the link earlier can therefore queue work after ieee80211_link_stop() has canceled it. ieee80211_request_smps() and ieee80211_csa_finish() can both reach this window.

Record each removed link while removing its keys and debugfs state. Wait for RCU readers, then stop the recorded links so cancellation includes work queued by those readers. Free the detached keys after the grace period as before.

LLM assistance was used to find the bug and review.

Fixes efe9c2bfd1a8 ("wifi: mac80211: isolate driver from inactive links")
---
 net/mac80211/link.c |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
net/mac80211/link.c +7 -1
@@ -191,6 +191,7 @@ struct link_container {
 static void ieee80211_tear_down_links(struct ieee80211_sub_if_data *sdata,
 				      struct link_container **links, u16 mask)
 {
+	struct ieee80211_link_data *stop[IEEE80211_MLD_MAX_NUM_LINKS] = {};
 	struct ieee80211_link_data *link;
 	LIST_HEAD(keys);
 	unsigned int link_id;
@@ -205,11 +206,16 @@ static void ieee80211_tear_down_links(st
 			continue;
 		ieee80211_remove_link_keys(link, &keys);
 		ieee80211_link_debugfs_remove(link);
-		ieee80211_link_stop(link);
+		stop[link_id] = link;
 	}
 
+	/* drain RCU readers before cancelling work they may queue */
 	synchronize_rcu();
 
+	for (link_id = 0; link_id < IEEE80211_MLD_MAX_NUM_LINKS; link_id++)
+		if (stop[link_id])
+			ieee80211_link_stop(stop[link_id]);
+
 	ieee80211_free_key_list(sdata->local, &keys);
 }
 
author maintainer
#801 lore raw

PATCH 800/1005 wifi: mac80211: recheck injected headers after removing FCS

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit 339564c7ac50464695dfed847f89d118f4cc1dc5 upstream.

Injecting a short frame with IEEE80211_RADIOTAP_F_FCS on a monitor interface can pass a truncated 802.11 header to transmit handlers.

ieee80211_monitor_start_xmit() validates the linear 802.11 header before parsing radiotap. Radiotap parsing then removes the four-byte FCS without rechecking the remaining header length. Software encryption can subtract the larger header length and pass the resulting negative length as an unsigned size.

Recheck the required linear header length after pulling the radiotap header and before handing the frame to the transmit path. Require at least addr1, which the transmit path reads even for extension frames whose header is shorter.

LLM assistance was used to find the bug and review.

Fixes bddc0c411a45 ("mac80211: Fix NULL ptr deref for injected rate info")
---
 net/mac80211/tx.c |    6 ++++++
 1 file changed, 6 insertions(+)
net/mac80211/tx.c +6 -0
@@ -2586,6 +2586,12 @@ netdev_tx_t ieee80211_monitor_start_xmit
 	/* remove the injection radiotap header */
 	skb_pull(skb, len_rthdr);
 
+	/* FCS removal may have shortened the 802.11 header. */
+	hdrlen = max_t(int, hdrlen,
+		       offsetofend(struct ieee80211_hdr, addr1));
+	if (skb_headlen(skb) < hdrlen)
+		goto fail_rcu;
+
 	ieee80211_xmit(sdata, NULL, skb);
 	rcu_read_unlock();
 
author maintainer
#802 lore raw

PATCH 801/1005 wifi: mac80211: recheck the IBSS station limit before insertion

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit f7670bcdf650b37551a9c5d084521f877d939f11 upstream.

Frames from successive unknown IBSS peers can make the deferred worker install more than 128 stations.

The receive path checks local->num_sta before allocating each station, but pending stations are not included in that count. Several allocations can therefore pass before the worker inserts any of them, and the worker then drains the list without rechecking the limit.

Recheck the installed-station limit in the worker under the wiphy mutex and free entries that no longer fit.

LLM assistance was used to find the bug and review.

---
 net/mac80211/ibss.c |    8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
net/mac80211/ibss.c +6 -2
@@ -1630,8 +1630,12 @@ void ieee80211_ibss_work(struct ieee8021
 		list_del(&sta->list);
 		spin_unlock_bh(&ifibss->incomplete_lock);
 
-		ieee80211_ibss_finish_sta(sta);
-		rcu_read_unlock();
+		if (sdata->local->num_sta >= IEEE80211_IBSS_MAX_STA_ENTRIES) {
+			sta_info_free(sdata->local, sta);
+		} else {
+			ieee80211_ibss_finish_sta(sta);
+			rcu_read_unlock();
+		}
 		spin_lock_bh(&ifibss->incomplete_lock);
 	}
 	spin_unlock_bh(&ifibss->incomplete_lock);
author maintainer
#803 lore raw

PATCH 802/1005 wifi: mac80211: recheck the OCB station limit before insertion

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit 27e29a077b4887d0e0a813337f8b7e06bd020c81 upstream.

Frames from successive unknown OCB peers can make the deferred worker install more than 128 stations.

The receive path checks local->num_sta before allocating each station, but pending stations are not included in that count. Several allocations can therefore pass before the worker inserts any of them, and the worker then drains the list without rechecking the limit.

Recheck the installed-station limit in the worker under the wiphy mutex and free entries that no longer fit.

LLM assistance was used to find the bug and review.

---
 net/mac80211/ocb.c |    8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
net/mac80211/ocb.c +6 -2
@@ -139,8 +139,12 @@ void ieee80211_ocb_work(struct ieee80211
 		list_del(&sta->list);
 		spin_unlock_bh(&ifocb->incomplete_lock);
 
-		ieee80211_ocb_finish_sta(sta);
-		rcu_read_unlock();
+		if (sdata->local->num_sta >= IEEE80211_OCB_MAX_STA_ENTRIES) {
+			sta_info_free(sdata->local, sta);
+		} else {
+			ieee80211_ocb_finish_sta(sta);
+			rcu_read_unlock();
+		}
 		spin_lock_bh(&ifocb->incomplete_lock);
 	}
 	spin_unlock_bh(&ifocb->incomplete_lock);
author maintainer
#804 lore raw

PATCH 803/1005 wifi: mac80211: reject invalid EHT guard intervals in airtime estimates

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit 582edbdbc5d288bd128b54935738fe38f15c8c29 upstream.

An invalid EHT guard interval can select the wrong airtime group and, at 320 MHz, read beyond airtime_mcs_groups.

Guard interval 3 advances EHT_GROUP_IDX() into the next bandwidth group at narrower widths. With one spatial stream and 320 MHz, it evaluates to 264, one past the 264-entry table. RX rate parsing rejects the value, but the common TX-status validator has no EHT check and last_rate_info can carry it to the airtime helper.

Reject values above NL80211_RATE_INFO_EHT_GI_3_2 in the helper. This also protects exported ieee80211_calc_rx_airtime() callers that do not pass through the TX-status validator.

LLM assistance was used to find the bug and review.

Fixes 3702a33216e6 ("wifi: mac80211: introduce EHT rate support in AQL airtime")
---
 net/mac80211/airtime.c |    2 ++
 1 file changed, 2 insertions(+)
net/mac80211/airtime.c +2 -0
@@ -550,6 +550,8 @@ static u32 ieee80211_get_rate_duration(s
 		group = HE_GROUP_IDX(streams, status->he_gi, bw);
 		break;
 	case RX_ENC_EHT:
+		if (status->eht.gi > NL80211_RATE_INFO_EHT_GI_3_2)
+			return 0;
 		streams = status->nss;
 		idx = status->rate_idx;
 		group = EHT_GROUP_IDX(streams, status->eht.gi, bw);
author maintainer
#805 lore raw

PATCH 804/1005 wifi: mac80211: restore dormant links when link updates fail

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit bb22f3b2d8f8a2f883944f24678cf84e18b162e8 upstream.

A failed MLO link update can leave the interface with the requested dormant-links bitmap instead of its previous one. This can disable active links or trigger a bitmap warning during rollback.

The error path restores the old valid-links bitmap but passes the new dormant_links argument to ieee80211_set_vif_links_bitmaps().

Save the old dormant bitmap before changing link state and use it when restoring the old configuration.

LLM assistance was used to find the bug and review.

Fixes 6d543b34dbcf ("wifi: mac80211: Support disabled links during association")
---
 net/mac80211/link.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/mac80211/link.c +2 -1
@@ -296,6 +296,7 @@ static int ieee80211_vif_update_links(st
 {
 	u16 old_links = sdata->vif.valid_links;
 	u16 old_active = sdata->vif.active_links;
+	u16 old_dormant = sdata->vif.dormant_links;
 	unsigned long add = new_links & ~old_links;
 	unsigned long rem = old_links & ~new_links;
 	unsigned long sta_rem = rem;
@@ -405,7 +406,7 @@ static int ieee80211_vif_update_links(st
 		/* restore config */
 		memcpy(sdata->link, old_data, sizeof(old_data));
 		memcpy(sdata->vif.link_conf, old, sizeof(old));
-		ieee80211_set_vif_links_bitmaps(sdata, old_links, dormant_links);
+		ieee80211_set_vif_links_bitmaps(sdata, old_links, old_dormant);
 		/* drain RCU readers before cancelling work they may queue */
 		synchronize_rcu();
 		for_each_set_bit(link_id, &add, IEEE80211_MLD_MAX_NUM_LINKS) {
author maintainer
#806 lore raw

PATCH 805/1005 wifi: mac80211: fix use-after-free on TTLM disconnect

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Johannes Berg <[email protected]>

commit 4af2b71495a3f12196cbea1c9a502c62ada867be upstream.

If ieee80211_process_adv_ttlm() disconnects, and some other changes were also detected in the beacon, the link update to the driver is still done, leading to use-after-free. Fix this by returning, like other functions, whether or not the update was accepted by the function.

---
 net/mac80211/mlme.c |   25 ++++++++++++++-----------
 1 file changed, 14 insertions(+), 11 deletions(-)
net/mac80211/mlme.c +14 -11
@@ -7849,15 +7849,15 @@ static void ieee80211_tid_to_link_map_wo
 	sdata->u.mgd.ttlm_info.switch_time = 0;
 }
 
-static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata,
-					  struct ieee802_11_elems *elems,
-					  u64 beacon_ts)
+static bool ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata,
+				       struct ieee802_11_elems *elems,
+				       u64 beacon_ts)
 {
 	u8 i;
 	int ret;
 
 	if (!ieee80211_vif_is_mld(&sdata->vif))
-		return;
+		return true;
 
 	if (!elems->ttlm_num) {
 		if (sdata->u.mgd.ttlm_info.switch_time) {
@@ -7875,14 +7875,14 @@ static void ieee80211_process_adv_ttlm(s
 						      0);
 			if (ret) {
 				sdata_info(sdata, "Failed setting valid/dormant links\n");
-				return;
+				return true;
 			}
 			ieee80211_vif_cfg_change_notify(sdata,
 							BSS_CHANGED_MLD_VALID_LINKS);
 		}
 		memset(&sdata->u.mgd.ttlm_info, 0,
 		       sizeof(sdata->u.mgd.ttlm_info));
-		return;
+		return true;
 	}
 
 	for (i = 0; i < elems->ttlm_num; i++) {
@@ -7894,7 +7894,7 @@ static void ieee80211_process_adv_ttlm(s
 
 		if (res) {
 			__ieee80211_disconnect(sdata);
-			return;
+			return false;
 		}
 
 		if (ttlm_info.switch_time) {
@@ -7919,7 +7919,7 @@ static void ieee80211_process_adv_ttlm(s
 			 * switch the AP will continue to announce it anyway.
 			 */
 			if (delay > IEEE80211_ADV_TTLM_ST_UNDERFLOW)
-				return;
+				return true;
 
 			delay_usec = ieee80211_tu_to_usec(delay);
 
@@ -7938,9 +7938,11 @@ static void ieee80211_process_adv_ttlm(s
 			wiphy_hrtimer_work_queue(sdata->local->hw.wiphy,
 						 &sdata->u.mgd.ttlm_work,
 						 us_to_ktime(delay_usec));
-			return;
+			return true;
 		}
 	}
+
+	return true;
 }
 
 static void
@@ -8463,8 +8465,9 @@ static void ieee80211_rx_mgmt_beacon(str
 					       elems->cisco_dtpc_elem);
 
 	ieee80211_ml_reconfiguration(sdata, elems);
-	ieee80211_process_adv_ttlm(sdata, elems,
-				      le64_to_cpu(mgmt->u.beacon.timestamp));
+	if (!ieee80211_process_adv_ttlm(sdata, elems,
+					le64_to_cpu(mgmt->u.beacon.timestamp)))
+		goto free;
 
 apply:
 	ieee80211_link_info_change_notify(sdata, link, changed);
author maintainer
#807 lore raw

PATCH 806/1005 wifi: mac80211: bound pending IBSS station allocations

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit 3029ca2112d7bee4d3e3eadd02decdb3eddb9485 upstream.

Delaying the IBSS station worker while frames arrive from new peers can retain an unbounded number of station allocations.

The receive-side limit counts installed stations, while new allocations wait on incomplete_stations until process context inserts them. The list lock does not cover the interval between allocation and list insertion.

Reserve one of 128 pending slots per interface before allocation. Release the reservation on allocation failure, after the worker inserts or frees the station, and when disconnect frees the pending list.

LLM assistance was used to find the bug and review.

---
 net/mac80211/ibss.c        |   13 ++++++++++++-
 net/mac80211/ieee80211_i.h |    1 +
 2 files changed, 13 insertions(+), 1 deletion(-)
net/mac80211/ibss.c +12 -1
@@ -684,6 +684,7 @@ static void ieee80211_ibss_disconnect(st
 		spin_unlock_bh(&ifibss->incomplete_lock);
 
 		sta_info_free(local, sta);
+		atomic_dec(&ifibss->incomplete_sta_count);
 		spin_lock_bh(&ifibss->incomplete_lock);
 	}
 	spin_unlock_bh(&ifibss->incomplete_lock);
@@ -1177,9 +1178,18 @@ void ieee80211_ibss_rx_no_sta(struct iee
 	band = chanctx_conf->def.chan->band;
 	rcu_read_unlock();
 
+	if (!atomic_add_unless(&ifibss->incomplete_sta_count, 1,
+			       IEEE80211_IBSS_MAX_STA_ENTRIES)) {
+		net_info_ratelimited("%s: No room for a new IBSS STA entry %pM\n",
+				     sdata->name, addr);
+		return;
+	}
+
 	sta = sta_info_alloc(sdata, addr, GFP_ATOMIC);
-	if (!sta)
+	if (!sta) {
+		atomic_dec(&ifibss->incomplete_sta_count);
 		return;
+	}
 
 	/* make sure mandatory rates are always added */
 	sband = local->hw.wiphy->bands[band];
@@ -1636,6 +1646,7 @@ void ieee80211_ibss_work(struct ieee8021
 			ieee80211_ibss_finish_sta(sta);
 			rcu_read_unlock();
 		}
+		atomic_dec(&ifibss->incomplete_sta_count);
 		spin_lock_bh(&ifibss->incomplete_lock);
 	}
 	spin_unlock_bh(&ifibss->incomplete_lock);
net/mac80211/ieee80211_i.h +1 -0
@@ -682,6 +682,7 @@ struct ieee80211_if_ibss {
 
 	spinlock_t incomplete_lock;
 	struct list_head incomplete_stations;
+	atomic_t incomplete_sta_count;
 
 	enum {
 		IEEE80211_IBSS_MLME_SEARCH,
author maintainer
#808 lore raw

PATCH 807/1005 wifi: mac80211: bound pending OCB station allocations

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit ee1a5e92dba0a98cabe476c780e3af4f0ab88b27 upstream.

Delaying the OCB station worker while frames arrive from new peers can retain an unbounded number of station allocations.

The receive-side limit counts installed stations, while new allocations wait on incomplete_stations until process context inserts them. The list lock does not cover the interval between allocation and list insertion.

Reserve one of 128 pending slots per interface before allocation. Release the reservation on allocation failure, after the worker inserts or frees the station, and when leave frees the pending list.

LLM assistance was used to find the bug and review.

---
 net/mac80211/ieee80211_i.h |    2 ++
 net/mac80211/ocb.c         |   13 ++++++++++++-
 2 files changed, 14 insertions(+), 1 deletion(-)
net/mac80211/ieee80211_i.h +2 -0
@@ -697,6 +697,7 @@ struct ieee80211_if_ibss {
  * @wrkq_flags: OCB deferred task action
  * @incomplete_lock: delayed STA insertion lock
  * @incomplete_stations: list of STAs waiting for delayed insertion
+ * @incomplete_sta_count: pending entries and reserved allocations
  * @joined: indication if the interface is connected to an OCB network
  */
 struct ieee80211_if_ocb {
@@ -705,6 +706,7 @@ struct ieee80211_if_ocb {
 
 	spinlock_t incomplete_lock;
 	struct list_head incomplete_stations;
+	atomic_t incomplete_sta_count;
 
 	bool joined;
 };
net/mac80211/ocb.c +12 -1
@@ -70,9 +70,18 @@ void ieee80211_ocb_rx_no_sta(struct ieee
 	band = chanctx_conf->def.chan->band;
 	rcu_read_unlock();
 
+	if (!atomic_add_unless(&ifocb->incomplete_sta_count, 1,
+			       IEEE80211_OCB_MAX_STA_ENTRIES)) {
+		net_info_ratelimited("%s: No room for a new OCB STA entry %pM\n",
+				     sdata->name, addr);
+		return;
+	}
+
 	sta = sta_info_alloc(sdata, addr, GFP_ATOMIC);
-	if (!sta)
+	if (!sta) {
+		atomic_dec(&ifocb->incomplete_sta_count);
 		return;
+	}
 
 	/* Add only mandatory rates for now */
 	sband = local->hw.wiphy->bands[band];
@@ -145,6 +154,7 @@ void ieee80211_ocb_work(struct ieee80211
 			ieee80211_ocb_finish_sta(sta);
 			rcu_read_unlock();
 		}
+		atomic_dec(&ifocb->incomplete_sta_count);
 		spin_lock_bh(&ifocb->incomplete_lock);
 	}
 	spin_unlock_bh(&ifocb->incomplete_lock);
@@ -228,6 +238,7 @@ int ieee80211_ocb_leave(struct ieee80211
 		spin_unlock_bh(&ifocb->incomplete_lock);
 
 		sta_info_free(local, sta);
+		atomic_dec(&ifocb->incomplete_sta_count);
 		spin_lock_bh(&ifocb->incomplete_lock);
 	}
 	spin_unlock_bh(&ifocb->incomplete_lock);
author maintainer
#809 lore raw

PATCH 808/1005 ksmbd: evaluate the DACL in order for explicit access requests

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Ian Bridges <[email protected]>

commit 20bed0d6ff62d985fe8222958825504b8aad4e88 upstream.

For requests without MAXIMUM_ALLOWED, smb_check_perm_dacl() selects one ACE instead of evaluating the DACL in order. When the selected ACE is a deny ACE, the function grants the complement of its mask, and deny ACEs before it are ignored. The selected ACE can also be inherit-only, unsupported, or an NFS mode ACE.

Guest and anonymous sessions also match Authenticated Users. These bugs can grant read or write access that the stored DACL does not grant. For example, a deny of FILE_READ_DATA grants FILE_WRITE_DATA, and guests can read files granted only to Authenticated Users.

Evaluate explicit requests in DACL order. Use exact SID matching for the caller, Everyone, Authenticated Users, OWNER RIGHTS and the caller's groups. Match Authenticated Users only for authenticated sessions, and ignore the NFS mode SID.

An Authenticated Users ACE must still prevent the POSIX ACL fallback from replacing the DACL result for guest and anonymous sessions. The ACE does not grant them access.

Keep the existing single-ACE behavior when a non-inherit-only object deny ACE is present because ksmbd does not parse those ACEs. Guest and anonymous sessions do not match Authenticated Users there either. MAXIMUM_ALLOWED behavior is unchanged.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Fixes cc2f133e80eb ("ksmbd: fix maximum allowed access checks")
---
 fs/smb/server/mgmt/user_config.h |    5 +++
 fs/smb/server/smb2pdu.c          |   11 +++++--
 fs/smb/server/smbacl.c           |   58 ++++++++++++++++++++++++++++++---------
 fs/smb/server/smbacl.h           |    2 -
 4 files changed, 60 insertions(+), 16 deletions(-)
fs/smb/server/mgmt/user_config.h +5 -0
@@ -67,4 +67,9 @@ struct ksmbd_user *ksmbd_alloc_user(stru
 void ksmbd_free_user(struct ksmbd_user *user);
 bool ksmbd_anonymous_user(struct ksmbd_user *user);
 bool ksmbd_compare_user(struct ksmbd_user *u1, struct ksmbd_user *u2);
+
+static inline bool ksmbd_user_authenticated(struct ksmbd_user *user)
+{
+	return user && !user_guest(user) && !ksmbd_anonymous_user(user);
+}
 #endif /* __USER_CONFIG_MANAGEMENT_H__ */
fs/smb/server/smb2pdu.c +8 -3
@@ -4359,7 +4359,8 @@ static int smb2_handle_app_instance_id(s
 	/* Authorize the referenced open even if its name changes meanwhile. */
 	old_path = &old_fp->filp->f_path;
 	rc = smb_check_perm_dacl(conn, old_path, &maximal_access, 0,
-				 work->sess->user->uid, false);
+				 work->sess->user->uid,
+				 ksmbd_user_authenticated(work->sess->user), false);
 	if (rc) {
 		/* Access denial prevents takeover, not the CREATE itself. */
 		ksmbd_put_durable_fd(old_fp);
@@ -4868,14 +4869,17 @@ resolve_path:
 	if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
 		rc = smb_check_perm_dacl(conn, &path, &daccess,
 					 req->DesiredAccess,
-					 sess->user->uid, false);
+					 sess->user->uid,
+					 ksmbd_user_authenticated(sess->user), false);
 		if (rc)
 			goto err_out;
 
 		if (maximal_access_ctxt) {
 			maximal_access = FILE_MAXIMAL_ACCESS_LE;
 			rc = smb_check_perm_dacl(conn, &path, &maximal_access,
-						 0, sess->user->uid, false);
+						 0, sess->user->uid,
+						 ksmbd_user_authenticated(sess->user),
+						 false);
 			if (rc)
 				goto err_out;
 
@@ -6158,6 +6162,7 @@ static int process_query_dir_entries(str
 			rc = smb_check_perm_dacl(priv->work->conn, &path,
 						 &daccess, daccess,
 						 priv->work->sess->user->uid,
+						 ksmbd_user_authenticated(priv->work->sess->user),
 						 true);
 			if (rc) {
 				dput(dent);
fs/smb/server/smbacl.c +46 -12

128 lines not on this page · raw message

fs/smb/server/smbacl.h +1 -1
@@ -96,7 +96,7 @@ int smb_inherit_dacl(struct ksmbd_conn *
 		     unsigned int uid, unsigned int gid);
 int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,
 			__le32 *pdaccess, __le32 raw_daccess, int uid,
-			bool strict);
+			bool authenticated, bool strict);
 int set_info_sec(struct ksmbd_conn *conn, struct ksmbd_tree_connect *tcon,
 		 const struct path *path, struct smb_ntsd *pntsd, int ntsd_len,
 		 bool type_check, bool get_write);
author maintainer
#810 lore raw

PATCH 809/1005 gpio: aspeed: Clear only the acked lines G4 interrupt status

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Billy Tsai <[email protected]>

commit 5d362564bd2982def7e80d7f1e756a97440c7adb upstream.

The G4 interrupt status registers are write-1-to-clear: writing 0 to a bit has no effect and writing 1 clears that line's status flag. aspeed_gpio_irq_ack() clears a line's status through aspeed_g4_reg_bit_set(), which reads the bank's status register, sets the line's bit and writes the whole value back. That write clears every interrupt pending in the 32-line bank, not just the acked one.

aspeed_gpio_irq_handler() reads each bank's status register once and dispatches the lines that were set. If another line in the same bank latches an edge after that read and before an ack in the bank, the ack clears its status and the handler is never called for it, so the edge is lost.

Write only the line's own bit when clearing the interrupt status on G4.

---
 drivers/gpio/gpio-aspeed.c |   11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/gpio/gpio-aspeed.c +11 -0
@@ -1041,6 +1041,17 @@ static void aspeed_g4_reg_bit_set(struct
 	void __iomem *addr = aspeed_gpio_g4_bank_reg(gpio, bank, reg);
 	u32 temp;
 
+	/*
+	 * The interrupt status register is write-1-to-clear. Write only this
+	 * line's bit so that interrupts pending on the other lines of the bank
+	 * stay latched.
+	 */
+	if (reg == reg_irq_status) {
+		if (val)
+			iowrite32(GPIO_BIT(offset), addr);
+		return;
+	}
+
 	if (reg == reg_val)
 		temp = gpio->dcache[GPIO_BANK(offset)];
 	else
author maintainer
#811 lore raw

PATCH 810/1005 gpio: aspeed: Preserve the pending G7 interrupt status on control writes

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Billy Tsai <[email protected]>

commit 18cc1d1ad94df8a6760fff2617d3d6923550cba0 upstream.

On G7 each line has its own control register, and its interrupt status bit (bit 12) is write-1-to-clear. aspeed_g7_reg_bit_set() updates a field by reading the control register, replacing that field and writing the value back. When the line's interrupt is pending, the status bit reads as 1 and is written back as 1, so updating an unrelated field such as the interrupt enable, trigger type, direction or debounce selection also clears the pending interrupt.

Mask out the status bit when composing the value to write, so it is written as 1 only when the status field itself is being set to ack the interrupt.

---
 drivers/gpio/gpio-aspeed.c |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/gpio/gpio-aspeed.c +7 -1
@@ -1168,7 +1168,13 @@ static void aspeed_g7_reg_bit_set(struct
 	u32 write_val;
 
 	if (mask) {
-		write_val = (ioread32(addr) & ~(mask)) | field_prep(mask, val);
+		/*
+		 * The interrupt status bit is write-1-to-clear. Keep it zero
+		 * unless it is the field being written, so that updating any
+		 * other field leaves a pending interrupt latched.
+		 */
+		write_val = ioread32(addr) & ~(mask | GPIO_G7_CTRL_IRQ_STS);
+		write_val |= field_prep(mask, val);
 		iowrite32(write_val, addr);
 	}
 }
author maintainer
#812 lore raw

PATCH 811/1005 gpio: brcmstb: fix UAF after IRQ domain setup failure

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Guangshuo Li <[email protected]>

commit baa14758afb3e2828de1f76511edc1de50216f39 upstream.

When devm_request_irq() fails in brcmstb_gpio_irq_setup(), the error path removes the IRQ domain but leaves priv->irq_domain non-NULL.

The probe error path subsequently calls brcmstb_gpio_remove(), which checks priv->irq_domain and attempts to access the already-freed domain through irq_find_mapping(). It also attempts to remove the domain again, resulting in a use-after-free and potentially further memory corruption.

Set priv->irq_domain to NULL after removing it so that the common cleanup path skips the already-freed IRQ domain.

This issue was found by our static analysis tool under development.

---
 drivers/gpio/gpio-brcmstb.c |    1 +
 1 file changed, 1 insertion(+)
drivers/gpio/gpio-brcmstb.c +1 -0
@@ -513,6 +513,7 @@ static int brcmstb_gpio_irq_setup(struct
 
 out_free_domain:
 	irq_domain_remove(priv->irq_domain);
+	priv->irq_domain = NULL;
 
 	return err;
 }
author maintainer
#813 lore raw

PATCH 812/1005 gpio: keep the chip reference when deferred setup fails

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Wentao Liang <[email protected]>

commit 7e899fe007d2ffc753e6aa5bc8f2ae0a802b9e07 upstream.

gpiochip_setup_devs() runs once gpiolib has been initialized and finishes the registration of the chips that were added before that. When the registration of such a chip fails, the function drops the reference taken in gpiochip_add_data_with_key() with gpio_device_put(), and only then logs the error through &gdev->dev.

For these chips that reference is the last one, so gpiodev_release() frees gdev: the dev_err() dereferences freed memory, and the chip is still linked in gpio_devices, so the next lookup walks into the freed object as well. Here the registration cannot be undone the way gpiochip_add_data_with_key() does it, as the driver already got success from gpiochip_add_data() and will call gpiochip_remove(), which unlinks the chip and drops the reference.

Keep the reference and only report the failure.

Fixes 16fdabe143fc ("gpio: Fix resource leaks on errors in gpiochip_add_data_with_key()")
Assisted-by DeepSeek-V4.1-Flash and OpenAI Codex
---
 drivers/gpio/gpiolib.c |   13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
drivers/gpio/gpiolib.c +9 -4
@@ -924,7 +924,8 @@ static const struct device_type gpio_dev
 
 /*
  * An initial reference count has been held in gpiochip_add_data_with_key().
- * The caller should drop the reference via gpio_device_put() on errors.
+ * A caller that tears the chip down on errors must drop the reference via
+ * gpio_device_put().
  */
 static int gpiochip_setup_dev(struct gpio_chip *gc)
 {
@@ -1100,12 +1101,16 @@ static void gpiochip_setup_devs(void)
 			continue;
 		}
 
+		/*
+		 * The reference taken in gpiochip_add_data_with_key() is
+		 * dropped by gpiochip_remove(): this chip is still registered
+		 * and its driver has not been told about the failure, so the
+		 * reference must be kept here.
+		 */
 		ret = gpiochip_setup_dev(gc);
-		if (ret) {
-			gpio_device_put(gdev);
+		if (ret)
 			dev_err(&gdev->dev,
 				"Failed to initialize gpio device (%d)\n", ret);
-		}
 	}
 }
 
author maintainer
#814 lore raw

PATCH 813/1005 gpio: of: fix potential misconfiguration of hogged lines

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Bartosz Golaszewski <[email protected]>

commit c62364eeac0f123478fca2f2d8e2424fdcd55032 upstream.

In of_gpiochip_get_lflags() the local variable xlate_flags is declared without being initialized before its address is passed to of_xlate_and_get_gpiod_flags() when processing a devicetree gpio-hog child node. If a driver uses an of_xlate() callback that doesn't update the flags argument (like gpiochip_fwd_delay_of_xlate()) we'll end up passing that uninitialized value to of_convert_gpio_flags(), potentially misconfiguring the hogged GPIO.

Initialize xlate_flags to 0.

---
 drivers/gpio/gpiolib-of.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpio/gpiolib-of.c +1 -1
@@ -725,7 +725,7 @@ int of_gpiochip_get_lflags(struct gpio_c
 			   struct fwnode_reference_args *gpiospec,
 			   unsigned long *lflags)
 {
-	enum of_gpio_flags xlate_flags;
+	enum of_gpio_flags xlate_flags = 0;
 	struct of_phandle_args args;
 	struct gpio_desc *desc;
 
author maintainer
#815 lore raw

PATCH 814/1005 gpio: rockchip: Fix debounce arithmetic for GPIO v2

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Cunhao Lu <[email protected]>

commit 13467fd6998f5da4f5b4f172f1af3d9c48d5de8f upstream.

The debounce interval calculations use unsigned long operands. On 32-bit systems, the numerator used to calculate the maximum interval overflows before division, while multiplying the requested interval by the clock rate overflows before it is assigned to a u64. A zero debounce clock rate also causes division by zero.

Use 64-bit arithmetic for both calculations and reject a zero clock rate before division.

At 32768 Hz, a 1 us request rounds to zero divider periods. Subtracting one then wraps the divider value to ULONG_MAX. Decrement only a nonzero rounded period count so that such requests use the smallest divider value.

Fixes 3bcbd1a85b68 ("gpio/rockchip: support next version gpio controller")
---
 drivers/gpio/gpio-rockchip.c |   15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/gpio/gpio-rockchip.c +10 -5
@@ -201,20 +201,25 @@ static int rockchip_gpio_set_debounce(st
 {
 	struct rockchip_pin_bank *bank = gpiochip_get_data(gc);
 	const struct rockchip_gpio_regs	*reg = bank->gpio_regs;
-	unsigned long flags, div_reg, freq, max_debounce;
+	unsigned long flags, div_reg, freq;
 	bool div_debounce_support;
 	unsigned int cur_div_reg;
-	u64 div;
+	u64 div, max_debounce;
 
 	if (bank->gpio_type == GPIO_TYPE_V2 && !IS_ERR(bank->db_clk)) {
 		div_debounce_support = true;
 		freq = clk_get_rate(bank->db_clk);
-		max_debounce = (GENMASK(23, 0) + 1) * 2 * 1000000 / freq;
+		if (!freq)
+			return -EINVAL;
+
+		div = (u64)(GENMASK(23, 0) + 1) * 2 * USEC_PER_SEC;
+		max_debounce = div64_u64(div, freq);
 		if (debounce > max_debounce)
 			return -EINVAL;
 
-		div = debounce * freq;
-		div_reg = DIV_ROUND_CLOSEST_ULL(div, 2 * USEC_PER_SEC) - 1;
+		div = (u64)debounce * freq;
+		div_reg = DIV_ROUND_CLOSEST_ULL(div, 2 * USEC_PER_SEC);
+		div_reg = div_reg ? div_reg - 1 : 0;
 	} else {
 		div_debounce_support = false;
 	}
author maintainer
#816 lore raw

PATCH 815/1005 gpio: sa1100: defer GPIO chip registration to postcore_initcall

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Dmitry Torokhov <[email protected]>

commit 32c89e32b3fef2ee0aa5c4d0b0fb089bb20b3223 upstream.

Registering the software node and the GPIO chip for the SA-1100 GPIO controller during early IRQ initialization causes boot hangs on SA-1100 platforms because the software node subsystem has not yet been initialized. At that early boot stage, attempting to register software nodes dereferences a NULL kset pointer before console or driver model initialization.

Nothing on SA-1100 platforms requests GPIO lines via gpiolib during early boot before initcalls run; only the GPIO IRQ controller and domain must be initialized during init_IRQ(). Defer registering the software node, assigning its firmware node, and registering the GPIO chip with gpiolib to postcore_initcall, running after driver and gpiolib device initialization and before board consumers register.

---
 drivers/gpio/gpio-sa1100.c | 32 +++++++++++++++++++++++++++-----
 1 file changed, 27 insertions(+), 5 deletions(-)
drivers/gpio/gpio-sa1100.c +27 -5
index e4f3bf949b87..1916200ebbd5 100644
@@ -8,6 +8,7 @@
 #include <linux/init.h>
 #include <linux/module.h>
 #include <linux/io.h>
+#include <linux/printk.h>
 #include <linux/syscore_ops.h>
 #include <soc/sa1100/pwer.h>
 #include <mach/hardware.h>
@@ -322,7 +323,6 @@ static const int sa1100_gpio_irqs[] __initconst = {
 void __init sa1100_init_gpio(void)
 {
 	struct sa1100_gpio_chip *sgc = &sa1100_gpio_chip;
-	struct gpio_chip *gc = &sgc->chip;
 	int i;
 
 	/* clear all GPIO edge detects */
@@ -330,10 +330,6 @@ void __init sa1100_init_gpio(void)
 	writel_relaxed(0, sgc->membase + R_GRER);
 	writel_relaxed(-1, sgc->membase + R_GEDR);
 
-	software_node_register(&sa1100_gpiochip_node);
-	gc->fwnode = software_node_fwnode(&sa1100_gpiochip_node);
-	gpiochip_add_data(gc, NULL);
-
 	sa1100_gpio_irqdomain = irq_domain_create_simple(NULL,
 			28, IRQ_GPIO0,
 			&sa1100_gpio_irqdomain_ops, sgc);
@@ -342,3 +338,29 @@ void __init sa1100_init_gpio(void)
 		irq_set_chained_handler_and_data(sa1100_gpio_irqs[i],
 						 sa1100_gpio_handler, sgc);
 }
+
+static int __init sa1100_gpio_init_chip(void)
+{
+	struct gpio_chip *gc = &sa1100_gpio_chip.chip;
+	int error;
+
+	error = software_node_register(&sa1100_gpiochip_node);
+	if (error) {
+		pr_err("failed to register sa1100 gpiochip software node: %d\n",
+		       error);
+		return error;
+	}
+
+	gc->fwnode = software_node_fwnode(&sa1100_gpiochip_node);
+
+	error = gpiochip_add_data(gc, NULL);
+	if (error) {
+		pr_err("failed to add sa1100 gpiochip: %d\n", error);
+		gc->fwnode = NULL;
+		software_node_unregister(&sa1100_gpiochip_node);
+		return error;
+	}
+
+	return 0;
+}
+postcore_initcall(sa1100_gpio_init_chip);
Signature · 1 line
2.56.1
author maintainer
#817 lore raw

PATCH 816/1005 gpio: shared: fix a race in shared desc release path

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Bartosz Golaszewski <[email protected]>

commit 53043b9e83cc7f4e30e70161b67ae93c4c9fdb87 upstream.

gpiod_shared_put() races with concurrent calls to
devm_gpiod_shared_get() like so:

CPU 0 (unbind / probe failure) CPU 1 (concurrent proxy probe)
============================== ==============================
gpiod_shared_put()
kref_put(&entry->ref, ...)

    refcount_dec_and_test() // -> 0
                                    devm_gpiod_shared_get()
                                      mutex_lock(&entry->lock);
                                      if (entry->shared_desc) {
                                        kref_get(&entry->ref); // on 0!
                                        shared_desc = entry->shared_desc;
                                      }
                                      mutex_unlock(&entry->lock);
    gpio_shared_release()
      mutex_lock(&entry->lock);
      kfree(shared_desc);
      entry->shared_desc = NULL;
      mutex_unlock(&entry->lock);
                                      // uses freed shared_desc

Because gpiod_shared_put() decrements entry->ref without holding entry->lock and gpio_shared_release() only acquires entry->lock after the reference count has already reached zero, a concurrent call to devm_gpiod_shared_get() can acquire entry->lock in the intermediate window and observe a non-NULL entry->shared_desc. This can result in a use-after-free and a double-free when the second consumer releases its reference.

Use kref_put_mutex() to ensure the entry lock is taken without a window in which a concurrent user can see a non-NULL entry->shared_desc while it's being released.

---
 drivers/gpio/gpiolib-shared.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/gpio/gpiolib-shared.c +3 -3
index 8c9ac9d93304..edb04a5bb987 100644
@@ -635,20 +635,20 @@ static void gpio_shared_release(struct kref *kref)
 		container_of(kref, struct gpio_shared_entry, ref);
 	struct gpio_shared_desc *shared_desc;
 
-	guard(mutex)(&entry->lock);
-
 	shared_desc = entry->shared_desc;
 	gpio_device_put(shared_desc->desc->gdev);
 	mutex_destroy(&shared_desc->mutex);
 	kfree(shared_desc);
 	entry->shared_desc = NULL;
+
+	mutex_unlock(&entry->lock);
 }
 
 static void gpiod_shared_put(void *data)
 {
 	struct gpio_shared_entry *entry = data;
 
-	kref_put(&entry->ref, gpio_shared_release);
+	kref_put_mutex(&entry->ref, gpio_shared_release, &entry->lock);
 }
 
 static struct gpio_shared_desc *
Signature · 1 line
2.56.1
author maintainer
#818 lore raw

PATCH 817/1005 gpio: sodaville: fix use-after-free bug when registering the irqchip

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Bartosz Golaszewski <[email protected]>

commit ab9102375b7c77e0c4d33c7594e514454dc9f2b3 upstream.

In sdv_register_irqsupport(), if irq_domain_create_legacy() fails during device probing, a generic IRQ chip is left registered in the global gc_list while its underlying memory is freed, leading to a use-after-free. Use the managed variant of irq_setup_generic_chip() to ensure that the chip gets unregistered before the memory it uses is freed.

---
 drivers/gpio/gpio-sodaville.c |    9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/gpio/gpio-sodaville.c +6 -3
@@ -166,9 +166,12 @@ static int sdv_register_irqsupport(struc
 	ct->chip.irq_eoi = irq_gc_eoi;
 	ct->chip.irq_set_type = sdv_gpio_pub_set_type;
 
-	irq_setup_generic_chip(sd->gc, IRQ_MSK(SDV_NUM_PUB_GPIOS),
-			IRQ_GC_INIT_MASK_CACHE, IRQ_NOREQUEST,
-			IRQ_LEVEL | IRQ_NOPROBE);
+	ret = devm_irq_setup_generic_chip(&pdev->dev, sd->gc,
+					  IRQ_MSK(SDV_NUM_PUB_GPIOS),
+					  IRQ_GC_INIT_MASK_CACHE, IRQ_NOREQUEST,
+					  IRQ_LEVEL | IRQ_NOPROBE);
+	if (ret)
+		return ret;
 
 	sd->id = irq_domain_create_legacy(dev_fwnode(&pdev->dev), SDV_NUM_PUB_GPIOS, sd->irq_base,
 					  0, &irq_domain_sdv_ops, sd);
author maintainer
#819 lore raw

PATCH 818/1005 gpio: virtuser: fix interrupt leak and UAF

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Bartosz Golaszewski <[email protected]>

commit 24cafd9580627f9f066296f4a6ce1b282a3f425d upstream.

When configuring interrupt handlers for GPIOs requested by virtual users, we never verify if an interrupt has been previously requested and just leak it if it was.

We also never free the interrupts at device unbind. This is both a leak and a potential UAF bug.

We use atomic_t for the irq field for now reason, it can't be modifying or read from atomic context. Let's repurpose the existing consumer_lock mutex and serialize access to the irq field. Let's add sanitization of input and schedule a tear-down action.

---
 drivers/gpio/gpio-virtuser.c |   39 +++++++++++++++++++++++++++++----------
 1 file changed, 29 insertions(+), 10 deletions(-)
drivers/gpio/gpio-virtuser.c +29 -10
@@ -55,9 +55,9 @@ struct gpio_virtuser_line_array_data {
 struct gpio_virtuser_line_data {
 	struct gpio_virtuser_attr_data ad;
 	char consumer[GPIO_VIRTUSER_NAME_BUF_LEN];
-	struct mutex consumer_lock;
+	struct mutex lock;
 	unsigned int debounce;
-	atomic_t irq;
+	int irq;
 	atomic_t irq_count;
 };
 
@@ -607,7 +607,7 @@ static ssize_t gpio_virtuser_consumer_re
 
 	memset(buf, 0x0, sizeof(buf));
 
-	scoped_guard(mutex, &data->consumer_lock)
+	scoped_guard(mutex, &data->lock)
 		ret = snprintf(buf, sizeof(buf), "%s\n", data->consumer);
 
 	return simple_read_from_buffer(user_buf, size, ppos, buf, ret);
@@ -635,7 +635,7 @@ static ssize_t gpio_virtuser_consumer_wr
 	if (ret)
 		return ret;
 
-	scoped_guard(mutex, &data->consumer_lock)
+	scoped_guard(mutex, &data->lock)
 		strscpy(data->consumer, buf, sizeof(data->consumer));
 
 	return count;
@@ -675,7 +675,12 @@ static int gpio_virtuser_interrupts_set(
 	if (val > 1)
 		return -EINVAL;
 
+	guard(mutex)(&ld->lock);
+
 	if (val) {
+		if (ld->irq >= 0)
+			return -EBUSY;
+
 		irq = gpiod_to_irq(ld->ad.desc);
 		if (irq < 0)
 			return irq;
@@ -689,11 +694,13 @@ static int gpio_virtuser_interrupts_set(
 		if (ret)
 			return ret;
 
-		atomic_set(&ld->irq, irq);
+		ld->irq = irq;
 	} else {
-		irq = atomic_xchg(&ld->irq, 0);
-		if (irq)
-			free_irq(irq, ld);
+		if (ld->irq < 0)
+			return -EBUSY;
+
+		free_irq(ld->irq, ld);
+		ld->irq = -1;
 	}
 
 	return 0;
@@ -793,6 +800,14 @@ static int gpio_virtuser_dbgfs_init_line
 			data->ad.dbgfs_dir, data);
 }
 
+static void gpio_virtuser_free_irq(void *data)
+{
+	struct gpio_virtuser_line_data *ld = data;
+
+	if (ld->irq >= 0)
+		free_irq(ld->irq, ld);
+}
+
 static int gpio_virtuser_dbgfs_init_line_attrs(struct device *dev,
 					       struct gpio_desc *desc,
 					       const char *id,
@@ -809,14 +824,18 @@ static int gpio_virtuser_dbgfs_init_line
 
 	data->ad.desc = desc;
 	strscpy(data->consumer, id);
-	atomic_set(&data->irq, 0);
+	data->irq = -1;
 	atomic_set(&data->irq_count, 0);
 
+	ret = devm_add_action_or_reset(dev, gpio_virtuser_free_irq, data);
+	if (ret)
+		return ret;
+
 	name = devm_kasprintf(dev, GFP_KERNEL, "gpiod:%s:%u", id, index);
 	if (!name)
 		return -ENOMEM;
 
-	ret = devm_mutex_init(dev, &data->consumer_lock);
+	ret = devm_mutex_init(dev, &data->lock);
 	if (ret)
 		return ret;
 
author maintainer
#820 lore raw

PATCH 819/1005 gpio: virtuser: remove the debugfs files before freeing the line data

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yu Zhang <[email protected]>

commit c2d0710318b8cd57d0ef6088d0ee4bbc1e827fd3 upstream.

gpio_virtuser_probe() registers the devm action that removes the debugfs directory before it allocates the per-line and per-array data that the debugfs files point to. devres releases resources in reverse order, so on unbind the line data is freed, the consumer_lock mutex is destroyed and the GPIO descriptors are put first, and the debugfs files are only removed afterwards.

A read or write of any of the per-line debugfs files (value, direction, consumer, interrupts, ...) that runs in that window dereferences the freed data. debugfs_remove_recursive() waits for in-flight file operations, but by then the data has already been freed.

Running eight threads that read the per-line debugfs files while another task writes 1 and 0 to the configfs "live" attribute triggers this within a second on a KASAN kernel, with gpio-sim as the provider:

  BUG: KASAN: slab-use-after-free in gpio_virtuser_value_get+0x19/0x60
  Read of size 8 at addr ffff888005109e38 by task vu_race/3479
  Call Trace:
   gpio_virtuser_value_get+0x19/0x60
   simple_attr_read+0x109/0x290
   debugfs_attr_read+0x5e/0x80
   full_proxy_read+0xae/0xe0
   vfs_read+0x1bc/0x7a0
  Allocated by task 1:
   devm_kmalloc+0x89/0x1d0
   gpio_virtuser_probe+0x56f/0x910
  Freed by task 1:
   kfree+0x196/0x430
   release_nodes+0x77/0xa0
   devres_release_all+0xf3/0x150
   device_unbind_cleanup+0x18/0x130
   ...
   platform_device_unregister+0x3c/0x50
   gpio_virtuser_device_deactivate+0x3c/0xc0

The same run also reports use-after-free on the freed consumer_lock from the consumer attribute.

Register the debugfs removal action after the line data has been set up, so that it runs first on unbind, and remove the directory by hand on the probe error paths before that point.

Fixes 91581c4b3f29 ("gpio: virtuser: new virtual testing driver for the GPIO API")
---
 drivers/gpio/gpio-virtuser.c |   46 +++++++++++++++++++++++++++----------------
 1 file changed, 29 insertions(+), 17 deletions(-)
drivers/gpio/gpio-virtuser.c +29 -17
@@ -946,38 +946,50 @@ static int gpio_virtuser_probe(struct pl
 				     "Failed to get the IDs of GPIOs to request\n");
 
 	dbgfs_entry = debugfs_create_dir(dev_name(dev), gpio_virtuser_dbg_root);
-	ret = devm_add_action_or_reset(dev, gpio_virtuser_debugfs_remove,
-				       dbgfs_entry);
-	if (ret)
-		return ret;
 
 	for (i = 0; i < num_ids; i++) {
 		descs = devm_gpiod_get_array(dev, ids[i], GPIOD_ASIS);
-		if (IS_ERR(descs))
-			return dev_err_probe(dev, PTR_ERR(descs),
-					     "Failed to request the '%s' GPIOs\n",
-					     ids[i]);
+		if (IS_ERR(descs)) {
+			ret = dev_err_probe(dev, PTR_ERR(descs),
+					    "Failed to request the '%s' GPIOs\n",
+					    ids[i]);
+			goto err_remove_debugfs;
+		}
 
 		ret = gpio_virtuser_dbgfs_init_line_array_attrs(dev, descs,
 								ids[i],
 								dbgfs_entry);
-		if (ret)
-			return dev_err_probe(dev, ret,
-					     "Failed to setup the debugfs array interface for the '%s' GPIOs\n",
-					     ids[i]);
+		if (ret) {
+			dev_err_probe(dev, ret,
+				      "Failed to setup the debugfs array interface for the '%s' GPIOs\n",
+				      ids[i]);
+			goto err_remove_debugfs;
+		}
 
 		for (j = 0; j < descs->ndescs; j++) {
 			ret = gpio_virtuser_dbgfs_init_line_attrs(dev,
 							descs->desc[j], ids[i],
 							j, dbgfs_entry);
-			if (ret)
-				return dev_err_probe(dev, ret,
-						     "Failed to setup the debugfs line interface for the '%s' GPIOs\n",
-						     ids[i]);
+			if (ret) {
+				dev_err_probe(dev, ret,
+					      "Failed to setup the debugfs line interface for the '%s' GPIOs\n",
+					      ids[i]);
+				goto err_remove_debugfs;
+			}
 		}
 	}
 
-	return 0;
+	/*
+	 * The debugfs files point to the devres-managed line data allocated
+	 * above. Register the removal last so that it runs first on unbind,
+	 * before any of that data is released.
+	 */
+	return devm_add_action_or_reset(dev, gpio_virtuser_debugfs_remove,
+					dbgfs_entry);
+
+err_remove_debugfs:
+	debugfs_remove_recursive(dbgfs_entry);
+	return ret;
 }
 
 static const struct of_device_id gpio_virtuser_of_match[] = {
author maintainer
#821 lore raw

PATCH 820/1005 gpiolib: fix stack out-of-bounds access in gpiochip_add_hog()

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Bartosz Golaszewski <[email protected]>

commit f8a4fdf57cedb9cb3f47d94269ff27fea8e819e8 upstream.

In gpiochip_add_hog(), parsing a device tree with an excessively large "#gpio-cells" property causes a stack out-of-bounds write when populating the GPIO specification.

The value read from #gpio-cells is used to copy the values into right places in struct fwnode_reference_args but that struct's args field is an array of size NR_FWNODE_REFERENCE_ARGS so a value larger than it will make the loop write past the end of that array.

If #gpio-cells is 0, we can trigger a divide-by-zero later when calculating the actual number of hogs.

If #gpio-cells is 1, we can also perform an out-of-bounds read of the "gpios" array.

Reject #gpio-cells larger than NR_FWNODE_REFERENCE_ARGS, lower than 1 and make sure #gpio-cells is larger than 1 before checking the active-low flag.

---
 drivers/gpio/gpiolib.c |    7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/gpio/gpiolib.c +5 -2
@@ -986,6 +986,8 @@ int gpiochip_add_hog(struct gpio_chip *g
 	ret = fwnode_property_read_u32(gc_node, "#gpio-cells", &cells);
 	if (ret && is_of_node(fwnode))
 		return ret;
+	if (cells < 1 || cells > NR_FWNODE_REFERENCE_ARGS)
+		return -EINVAL;
 	if (argc % cells)
 		return -EINVAL;
 
@@ -1041,9 +1043,10 @@ int gpiochip_add_hog(struct gpio_chip *g
 		} else {
 			/*
 			 * GPIO_ACTIVE_LOW is currently the only lookup flag
-			 * supported for non-OF firmware nodes.
+			 * supported for non-OF firmware nodes and it must live
+			 * in the second cell.
 			 */
-			if (gpios[i * cells + 1])
+			if (cells > 1 && gpios[i * cells + 1])
 				lflags |= GPIO_ACTIVE_LOW;
 		}
 
author maintainer
#822 lore raw

PATCH 821/1005 gpiolib: synchronize updates of descriptor labels

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Bartosz Golaszewski <[email protected]>

commit 82028344caeed2ea3536708906adee02e472633d upstream.

desc_set_label() swaps desc->label with rcu_replace_pointer() but without any synchronization of concurrent updates. The swap is a plain read + write: two threads can observe the same old label and then call call_scru() on the same SRCU head corrupting the state of the chain.

Add a spinlock to struct gpio_device - we're using a single spinlock for all descriptors as using a per-descriptor lock would unnecessarily bloat the size of the desc array with very little chance and no consequences of contention - and use it to serialize the pointer update.

---
 drivers/gpio/gpiolib.c |   11 ++++++++---
 drivers/gpio/gpiolib.h |    2 ++
 2 files changed, 10 insertions(+), 3 deletions(-)
drivers/gpio/gpiolib.c +8 -3
@@ -154,9 +154,12 @@ static int desc_set_label(struct gpio_de
 		memcpy(new->str, label, len);
 	}
 
-	old = rcu_replace_pointer(desc->label, new, 1);
-	if (old)
-		call_srcu(&desc->gdev->desc_srcu, &old->rh, desc_free_label);
+	scoped_guard(spinlock, &desc->gdev->desc_lock) {
+		old = rcu_replace_pointer(desc->label, new,
+					  lockdep_is_held(&desc->gdev->desc_lock));
+		if (old)
+			call_srcu(&desc->gdev->desc_srcu, &old->rh, desc_free_label);
+	}
 
 	return 0;
 }
@@ -1210,6 +1213,8 @@ int gpiochip_add_data_with_key(struct gp
 		goto err_free_ida;
 	rcu_assign_pointer(gdev->chip, gc);
 
+	spin_lock_init(&gdev->desc_lock);
+
 	ret = init_srcu_struct(&gdev->desc_srcu);
 	if (ret)
 		goto err_cleanup_gdev_srcu;
drivers/gpio/gpiolib.h +2 -0
@@ -37,6 +37,7 @@ struct fwnode_handle;
  * @valid_mask: If not %NULL, holds bitmask of GPIOs which are valid to be
  * used from the chip.
  * @desc_srcu: ensures consistent state of GPIO descriptors exposed to users
+ * @desc_lock: synchronizes the updates to descriptor labels
  * @ngpio: the number of GPIO lines on this GPIO device, equal to the size
  * of the @descs array.
  * @can_sleep: indicate whether the GPIO chip driver's callbacks can sleep
@@ -71,6 +72,7 @@ struct gpio_device {
 	struct gpio_desc	*descs;
 	unsigned long		*valid_mask;
 	struct srcu_struct	desc_srcu;
+	spinlock_t		desc_lock;
 	unsigned int		base;
 	u16			ngpio;
 	bool			can_sleep;
author maintainer
#823 lore raw

PATCH 822/1005 ovl: do not always clear absolute_redirect

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Giuseppe Scrivano <[email protected]>

commit 477449a7a5fd1b2fe973fe2978b0c921115a65f3 upstream.

ovl_check_redirect() clears d->absolute_redirect before it checks that the path element has a redirect xattr. An element without one, such as an intermediate directory in a lower layer, then clears the flag set by the absolute redirect of a metacopy file found in a higher layer. The lookup of the data in the data-only layers is not deferred any more and the lookup fails with -EIO:

  # l2/f: metacopy, redirect "/dir/file"; l1/dir/ exists, no "file"
  mount -t overlay none -o metacopy=on,redirect_dir=on,\
        lowerdir+=l2,lowerdir+=l1,datadir+=data m
  cat m/f   # Input/output error

Set d->absolute_redirect only when a redirect xattr was read.

---
 fs/overlayfs/namei.c |    5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
fs/overlayfs/namei.c +2 -3
@@ -39,13 +39,12 @@ static int ovl_check_redirect(const stru
 	char *buf;
 	struct ovl_fs *ofs = OVL_FS(d->sb);
 
-	d->absolute_redirect = false;
 	buf = ovl_get_redirect_xattr(ofs, path, prelen + strlen(post));
 	if (IS_ERR_OR_NULL(buf))
 		return PTR_ERR(buf);
 
-	if (buf[0] == '/') {
-		d->absolute_redirect = true;
+	d->absolute_redirect = buf[0] == '/';
+	if (d->absolute_redirect) {
 		/*
 		 * One of the ancestor path elements in an absolute path
 		 * lookup in ovl_lookup_layer() could have been opaque and
author maintainer
#824 lore raw

PATCH 823/1005 ovl: do not read the flags of a put upper dentry in lookup

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Amir Goldstein <[email protected]>

commit 7031366be218f291592a7ad38bc34a7cd1459737 upstream.

ovl_lookup_layers() passes ctx->upperdentry to ovl_get_inode(), which takes over the reference. If an overlay inode for the upper inode is already cached, as for a second hard link, ovl_get_inode() puts the dentry and returns the cached inode. ovl_lookup_layers() then passes the put dentry to ovl_dentry_init_reval(), which reads its d_flags.

With a local upper fs the put dentry usually stays in the dcache, but with a FUSE upper whose entry has timed out, dput() kills it, so this is a use-after-free.

Fix this by taking the revalidate flags from the upper dentry of the overlay inode, which is the one that ovl_dentry_revalidate_common() revalidates.

---
 fs/overlayfs/namei.c |   12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
fs/overlayfs/namei.c +10 -2
@@ -1381,9 +1381,17 @@ static int ovl_lookup_layers(struct ovl_
 
 		if (metacopy_size > OVL_METACOPY_MIN_SIZE)
 			ovl_set_flag(OVL_HAS_DIGEST, ctx->inode);
-	}
 
-	ovl_dentry_init_reval(dentry, ctx->upperdentry, OVL_I_E(ctx->inode));
+		/*
+		 * ovl_get_inode() puts ctx->upperdentry if it finds a cached
+		 * inode, e.g. for another hard link, so use the upper dentry
+		 * of the inode.
+		 */
+		ovl_dentry_init_reval(dentry, ovl_i_dentry_upper(inode),
+				      OVL_I_E(inode));
+	} else {
+		ovl_dentry_init_reval(dentry, NULL, NULL);
+	}
 
 	return 0;
 }
author maintainer
#825 lore raw

PATCH 824/1005 ovl: fix leak of lowerdata redirect on ovl_get_inode() failure

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Amir Goldstein <[email protected]>

commit f1b7e5534854043077bb72afc8d87ad1e0b283e0 upstream.

ovl_lookup_layers() moves d->redirect into oip.lowerdata_redirect and clears d->redirect before calling ovl_get_inode(). When ovl_get_inode() fails, it does not free oip.lowerdata_redirect, and ovl_lookup() frees the already cleared d->redirect, so the lowerdata redirect string is leaked.

Clear d->redirect only after ovl_get_inode() has succeeded, like d->upperredirect, so that ovl_lookup() frees it on failure.

Fixes 2b21da920866 ("ovl: prepare to store lowerdata redirect for lazy lowerdata lookup")
---
 fs/overlayfs/namei.c |    7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
fs/overlayfs/namei.c +4 -3
@@ -1366,15 +1366,16 @@ static int ovl_lookup_layers(struct ovl_
 		};
 
 		/* Store lowerdata redirect for lazy lookup */
-		if (ctx->ctr > 1 && !d->is_dir && !ctx->stack[ctx->ctr - 1].dentry) {
+		if (ctx->ctr > 1 && !d->is_dir && !ctx->stack[ctx->ctr - 1].dentry)
 			oip.lowerdata_redirect = d->redirect;
-			d->redirect = NULL;
-		}
 
 		inode = ovl_get_inode(dentry->d_sb, &oip);
 		if (IS_ERR(inode))
 			return PTR_ERR(inode);
 
+		if (oip.lowerdata_redirect)
+			d->redirect = NULL;
+
 		ctx->inode = inode;
 		if (ctx->upperdentry && !uppermetacopy)
 			ovl_set_flag(OVL_UPPERDATA, ctx->inode);
author maintainer
#826 lore raw

PATCH 825/1005 ovl: reject different lower idmaps on the same fs

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jérémy Jean <[email protected]>

commit 720f40c05b2785406121da0151543751204f2953 upstream.

Overayfs mounted with index=on or nfs_export=on require file handle support from backing filesystems.

Overlay file handles identify a backing filesystem, but not the lower mount used to decode it. If lower layers share a superblock and use different idmaps, a handle can decode through the wrong layer.

Record the first idmap on a private lower clone for each backing filesystem. Fail if another clone has a different idmap. Comparing the private clones prevents mount_setattr() from changing the checked state. Distinct idmap objects are treated as ambiguous.

---
 fs/overlayfs/ovl_entry.h |    2 ++
 fs/overlayfs/super.c     |   23 +++++++++++++++++++++++
 2 files changed, 25 insertions(+)
fs/overlayfs/ovl_entry.h +2 -0
@@ -24,6 +24,8 @@ struct ovl_config {
 struct ovl_sb {
 	struct super_block *sb;
 	dev_t pseudo_dev;
+	/* Idmap of the first lower layer on this fs */
+	const struct mnt_idmap *lower_idmap;
 	/* Unusable (conflicting) uuid */
 	bool bad_uuid;
 	/* Used as a lower layer (but maybe also as upper) */
fs/overlayfs/super.c +23 -0
@@ -1121,6 +1121,29 @@ static int ovl_get_layers(struct super_b
 		}
 
 		/*
+		 * Lower file handles identify the lower fs, but not the layer,
+		 * so with different idmaps on the same lower fs, index and
+		 * nfs_export may decode a file handle through a layer with the
+		 * wrong idmap.  Following copy up origin without index is only
+		 * used for st_ino, which does not depend on the idmap.
+		 */
+		if (i < nr_merged_lower &&
+		    (ofs->config.index || ofs->config.nfs_export)) {
+			const struct mnt_idmap *idmap = mnt_idmap(mnt);
+			struct ovl_sb *fs = &ofs->fs[fsid];
+
+			if (!fs->lower_idmap) {
+				fs->lower_idmap = idmap;
+			} else if (fs->lower_idmap != idmap) {
+				pr_err("lower layer '%pd2' conflicts with idmap of another lower layer on the same fs, mount with '-o index=off,nfs_export=off' to override.\n",
+				       l->path.dentry);
+				iput(trap);
+				kern_unmount(mnt);
+				return -EINVAL;
+			}
+		}
+
+		/*
 		 * Make lower layers R/O.  That way fchmod/fchown on lower file
 		 * will fail instead of modifying lower fs.
 		 */
author maintainer
#827 lore raw

PATCH 826/1005 ovl: report the requested redirect_dir mode in conflicting options

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Amir Goldstein <[email protected]>

commit 248503755b3cab89742edcc3cfd53adbcf7bfec2 upstream.

Since the redirect_dir mode is stored as an enum, "off" is translated to "follow" or "nofollow" when parsing the option and redirect_dir=follow is translated to "on" for a non-upper mount, so the errors about options that conflict with an explicit redirect_dir= report a mode that the user did not request.

Translate "off" when verifying the mount options instead of when parsing them and report the requested mode in those errors.

Fixes af5f2396b671 ("ovl: store enum redirect_mode in config instead of a string")
---
 fs/overlayfs/overlayfs.h |   10 +++++++---
 fs/overlayfs/params.c    |   43 ++++++++++++++++++++++++++++++-------------
 2 files changed, 37 insertions(+), 16 deletions(-)
fs/overlayfs/overlayfs.h +7 -3
@@ -74,9 +74,13 @@ enum ovl_entry_flag {
 };
 
 enum {
-	OVL_REDIRECT_OFF,	/* "off" mode is never used. In effect	*/
-	OVL_REDIRECT_FOLLOW,	/* ...it translates to either "follow"	*/
-	OVL_REDIRECT_NOFOLLOW,	/* ...or "nofollow".			*/
+	/*
+	 * "off" mode is never used after mount options are verified. In effect
+	 * it translates to either "follow" or "nofollow".
+	 */
+	OVL_REDIRECT_OFF,
+	OVL_REDIRECT_FOLLOW,
+	OVL_REDIRECT_NOFOLLOW,
 	OVL_REDIRECT_ON,
 };
 
fs/overlayfs/params.c +30 -13

99 lines not on this page · raw message

author maintainer
#828 lore raw

PATCH 827/1005 ovl: return EIO if the lowerdata is missing

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Giuseppe Scrivano <[email protected]>

commit 0d5e729c515f4ae4eacc179dbcf350d9b499a161 upstream.

The data of a metacopy file that redirects to a data-only layer is looked up when the file is opened, and the error of the lookup is returned as is. If the data file is missing, open() fails with ENOENT even though the file is there and stat() works.

This can be an integrity problem when using composefs: a data file that is changed or has the wrong fs-verity digest is reported with EIO, but a missing one is not reported, the file just looks like it does not exist, e.g. a configuration file that overrides the defaults.

Return EIO as it is already done in ovl_lookup() when no lower data is found for a metacopy file. ENOMEM is not changed.

Fixes 42dd69ae1af4 ("ovl: implement lazy lookup of lowerdata in data-only layers")
---
 fs/overlayfs/namei.c |    8 ++++++++
 1 file changed, 8 insertions(+)
fs/overlayfs/namei.c +8 -0
@@ -1046,6 +1046,14 @@ out:
 out_err:
 	pr_warn_ratelimited("lazy lowerdata lookup failed (%pd2, err=%i)\n",
 			    dentry, err);
+	/*
+	 * The data of a metacopy file is missing or is not a regular file in
+	 * the data-only layers: the layers are corrupted.  Do not return the
+	 * error of the lookup (e.g. ENOENT) to the caller, it would make the
+	 * file look like it does not exist.
+	 */
+	if (err != -ENOMEM)
+		err = -EIO;
 	goto out;
 }
 
author maintainer
#829 lore raw

PATCH 828/1005 ovl: bump the impure dir version when linking a file with origin

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Daejun Park <[email protected]>

commit 86e2facd8630cc2fdec6ea80c53e370b26b441d9 upstream.

Linking a file with copy up origin into a non-merge impure dir does not bump the dir version. readdir then reuses the impure dir cache built before the link. It reports the upper inode number as d_ino of the new link, not st_ino.

Pass whether the linked file has an origin to ovl_dir_modified(), as rename and unlink do.

---
 fs/overlayfs/dir.c |   20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)
fs/overlayfs/dir.c +11 -9
@@ -368,7 +368,7 @@ static bool ovl_type_origin(struct dentr
 }
 
 static int ovl_create_upper(struct dentry *dentry, struct inode *inode,
-			    struct ovl_cattr *attr)
+			    struct ovl_cattr *attr, bool origin)
 {
 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
 	struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent);
@@ -393,7 +393,7 @@ static int ovl_create_upper(struct dentr
 		ovl_set_opaque(dentry, newdentry);
 	}
 
-	ovl_dir_modified(dentry->d_parent, false);
+	ovl_dir_modified(dentry->d_parent, origin);
 	err = ovl_instantiate(dentry, inode, newdentry, !!attr->hardlink, NULL);
 	if (err)
 		goto out_cleanup;
@@ -491,7 +491,7 @@ static int ovl_set_upper_acl(struct ovl_
 }
 
 static int ovl_create_over_whiteout(struct dentry *dentry, struct inode *inode,
-				    struct ovl_cattr *cattr)
+				    struct ovl_cattr *cattr, bool origin)
 {
 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
 	struct dentry *workdir = ovl_workdir(dentry);
@@ -582,7 +582,7 @@ static int ovl_create_over_whiteout(stru
 		if (err)
 			goto out_cleanup_unlocked;
 	}
-	ovl_dir_modified(dentry->d_parent, false);
+	ovl_dir_modified(dentry->d_parent, origin);
 	err = ovl_instantiate(dentry, inode, newdentry, hardlink, NULL);
 	if (err) {
 		ovl_cleanup(ofs, upperdir, newdentry);
@@ -647,12 +647,12 @@ DEFINE_CLASS(ovl_override_creator_creds,
 
 static int ovl_create_handle_whiteouts(struct dentry *dentry,
 				       struct inode *inode,
-				       struct ovl_cattr *attr)
+				       struct ovl_cattr *attr, bool origin)
 {
 	if (!ovl_dentry_is_whiteout(dentry))
-		return ovl_create_upper(dentry, inode, attr);
+		return ovl_create_upper(dentry, inode, attr, origin);
 
-	return ovl_create_over_whiteout(dentry, inode, attr);
+	return ovl_create_over_whiteout(dentry, inode, attr, origin);
 }
 
 static int ovl_create_or_link(struct dentry *dentry, struct inode *inode,
@@ -687,12 +687,14 @@ static int ovl_create_or_link(struct den
 		 */
 
 		if (attr->hardlink)
-			return ovl_create_handle_whiteouts(dentry, inode, attr);
+			return ovl_create_handle_whiteouts(dentry, inode, attr,
+							   origin);
 
 		scoped_class(ovl_override_creator_creds, cred, original_creds, dentry, inode, attr->mode) {
 			if (IS_ERR(cred))
 				return PTR_ERR(cred);
-			return ovl_create_handle_whiteouts(dentry, inode, attr);
+			return ovl_create_handle_whiteouts(dentry, inode, attr,
+							   origin);
 		}
 	}
 	return err;
author maintainer
#830 lore raw

PATCH 829/1005 ovl: do not allow nfs_export with data-only layers

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Amir Goldstein <[email protected]>

commit fba955b070d13e2fdac097577ce3c6ffbeda4ea9 upstream.

Since data-only layers no longer require metacopy=on, which conflicts with nfs_export=on, an overlay with data-only layers can be mounted with nfs_export=on.

Decoding a file handle of a lower metacopy file whose data is in a data-only layer builds the inode only from the decoded lower dentry, without the lazy lowerdata redirect, so the data of the file would be read from the metacopy file in the lower layer.

Fail the mount with explicit nfs_export=on and data-only layers and otherwise disable nfs_export with data-only layers.

Fixes 5ef7bcdeecc9 ("ovl: relax redirect/metacopy requirements for lower -> data redirect")
---
 fs/overlayfs/params.c |   10 ++++++++++
 1 file changed, 10 insertions(+)
fs/overlayfs/params.c +10 -0
@@ -948,6 +948,16 @@ int ovl_fs_params_verify(const struct ov
 		}
 	}
 
+	/* Resolve nfs_export -> !data-only layers dependency */
+	if (config->nfs_export && ctx->nr_data) {
+		if (set.nfs_export) {
+			pr_err("NFS export is not supported with data-only layers\n");
+			return -EINVAL;
+		}
+		pr_info("disabling nfs_export due to data-only layers\n");
+		config->nfs_export = false;
+	}
+
 	/* Resolve nfs_export -> index dependency */
 	if (config->nfs_export && !config->index) {
 		if (!config->upperdir &&
author maintainer
#831 lore raw

PATCH 830/1005 ovl: do not check the deferred lowerdata redirect on index lookup

In reply to Greg Kroah-Hartman

7.3-stable review patch. If anyone has any objections, please let me know.

------------------

From: Amir Goldstein <[email protected]>

commit 011f67b2b5c366679af023261ee02e284d534a96 upstream.

When a lower metacopy has an absolute redirect into a data-only layer, ovl_lookup_layers() defers the data lookup and skips ovl_check_follow_redirect(), but leaves the redirect in d->redirect. If there is no upper dentry and a sibling hardlink was already copied up to the index dir, the index branch calls ovl_check_follow_redirect() again and, with redirect_dir=nofollow (e.g. forced by userxattr), fails the lookup with -EPERM because of the lower data redirect.

Take the lowerdata redirect out of d->redirect at the point where the data lookup is deferred, so that the index check only validates the redirect and metacopy state of the index entry.

Fixes 5ef7bcdeecc9 ("ovl: relax redirect/metacopy requirements for lower -> data redirect")
---
 fs/overlayfs/namei.c |   11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
fs/overlayfs/namei.c +7 -4
@@ -27,6 +27,7 @@ struct ovl_lookup_data {
 	bool last;
 	char *redirect;
 	char *upperredirect;
+	char *lowerdata_redirect;
 	int metacopy;
 	/* Referring to last redirect xattr */
 	bool absolute_redirect;
@@ -1258,6 +1259,8 @@ static int ovl_lookup_layers(struct ovl_
 	if (d->metacopy && ctx->ctr && ofs->numdatalayer && d->absolute_redirect) {
 		d->metacopy = 0;
 		ctx->ctr++;
+		d->lowerdata_redirect = d->redirect;
+		d->redirect = NULL;
 	} else if (!ovl_check_follow_redirect(d)) {
 		err = -EPERM;
 		return err;
@@ -1374,15 +1377,14 @@ static int ovl_lookup_layers(struct ovl_
 		};
 
 		/* Store lowerdata redirect for lazy lookup */
-		if (ctx->ctr > 1 && !d->is_dir && !ctx->stack[ctx->ctr - 1].dentry)
-			oip.lowerdata_redirect = d->redirect;
+		if (d->lowerdata_redirect)
+			oip.lowerdata_redirect = d->lowerdata_redirect;
 
 		inode = ovl_get_inode(dentry->d_sb, &oip);
 		if (IS_ERR(inode))
 			return PTR_ERR(inode);
 
-		if (oip.lowerdata_redirect)
-			d->redirect = NULL;
+		d->lowerdata_redirect = NULL;
 
 		ctx->inode = inode;
 		if (ctx->upperdentry && !uppermetacopy)
@@ -1435,6 +1437,7 @@ struct dentry *ovl_lookup(struct inode *
 	dput(ctx.index);
 	ovl_stack_free(ctx.stack, ctx.ctr);
 	kfree(d.redirect);
+	kfree(d.lowerdata_redirect);
 
 	if (err) {
 		ovl_free_entry(ctx.oe);