Skip to contentSkip to conversation

7.3.4-rc1 review

PATCH Applied Greg Kroah-Hartman 22 participants 1,287 messages Nov 7 – Nov 10 Page 5 of 10

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

PATCH 566/1257 ext4: fix out-of-bounds read in ext4_get_group_info()

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]>

[ Upstream commit b067d3c1f90b536e9aa9f48b19580475a0b34f0f ]

A plain read of s_groups_count in ext4_get_group_info() allows CPU load-load reordering. On weak memory models, speculative prefetch of s_group_info prior to the boundary check could lead to an out-of-bounds read if a concurrent online resize expands the array and increments s_groups_count.

The data race occurs between the ioctl configuration path (holding the resize lock via ext4_resize_begin) and the lockless metadata lookup path:

CPU 0 (Writer, Resize Lock) CPU 1 (Reader, Lockless)
--------------------------- ------------------------
ext4_ioctl()

     [EXT4_IOC_GROUP_ADD]
     ext4_ioctl_group_add()
       ext4_resize_begin() // Takes lock
       ext4_group_add()
         ext4_mb_alloc_groupinfo()
           // Publishes expanded array via RCU
           rcu_assign_pointer(s_group_info, ...)

         ext4_flex_group_add()
           ext4_update_super()
                                              ext4_get_group_info()
                                                // Speculative / out-of-order read
                                                [Loads old/smaller s_group_info pointer]
             [Plain C store / smp_wmb()]
             sbi->s_groups_count += ...;
                                                // Reads new s_groups_count,
                                                // boundary check passes
                                                if (group >= s_groups_count)

                                                // Out-of-bounds array access!
                                                sbi_array_rcu_deref(..., s_group_info)

Fix this by using ext4_get_groups_count() to enforce acquire semantics.

---
 fs/ext4/balloc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ext4/balloc.c +1 -1
index 52f4c5169f914..778fe8788f06e 100644
@@ -329,7 +329,7 @@ struct ext4_group_info *ext4_get_group_info(struct super_block *sb,
 	struct ext4_group_info **grp_info;
 	long indexv, indexh;
 
-	if (unlikely(group >= EXT4_SB(sb)->s_groups_count))
+	if (unlikely(group >= ext4_get_groups_count(sb)))
 		return NULL;
 	if (unlikely(!EXT4_SB(sb)->s_group_info))
 		return NULL;
Signature · 1 line
2.53.0
author maintainer
#570 lore raw

PATCH 567/1257 nilfs2: validate directory position after llseek in readdir

In reply to Greg Kroah-Hartman

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

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

From: Jake Labelle <[email protected]>

[ Upstream commit de7f49c12566cc5c7437a2f26c6c754b9d4d5648 ]

nilfs_readdir() uses ctx->pos, which userspace can set to an arbitrary value via llseek, as an offset into the directory folio and parses whatever bytes sit there as a directory entry. A position pointing into the middle of an entry -- or at unused bytes of a corrupted image that the page validator never inspected -- makes dir_emit() copy up to 255 (name_len) bytes from a bogus entry, possibly reading past the end of the folio and returning unrelated memory contents to userspace.

Snap unaligned positions onto a valid entry boundary by walking the rec_len chain from the chunk start before parsing, as ext2 does in ext2_validate_entry().

[ryusuke: fixed offset wrap-around in nilfs_validate_entry() and
conformed AI tag to guidelines]

Fixes 2ba466d74ed7 ("nilfs2: directory entry operations")
Assisted-by Claude:claude-mythos-5
---
 fs/nilfs2/dir.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
fs/nilfs2/dir.c +34 -0
index 8b53802b6ebd7..7686ca9228fc8 100644
@@ -231,11 +231,27 @@ static struct nilfs_dir_entry *nilfs_next_entry(struct nilfs_dir_entry *p)
 					  nilfs_rec_len_from_disk(p->rec_len));
 }
 
+static inline unsigned int
+nilfs_validate_entry(char *base, unsigned int offset, unsigned int mask)
+{
+	struct nilfs_dir_entry *de = (struct nilfs_dir_entry *)(base + offset);
+	struct nilfs_dir_entry *p =
+		(struct nilfs_dir_entry *)(base + (offset & mask));
+
+	while ((char *)p < (char *)de) {
+		if (p->rec_len == 0)
+			break;
+		p = nilfs_next_entry(p);
+	}
+	return (char *)p - base;
+}
+
 static int nilfs_readdir(struct file *file, struct dir_context *ctx)
 {
 	loff_t pos = ctx->pos;
 	struct inode *inode = file_inode(file);
 	struct super_block *sb = inode->i_sb;
+	unsigned int chunk_size = nilfs_chunk_size(inode);
 	unsigned int offset = pos & ~PAGE_MASK;
 	unsigned long n = pos >> PAGE_SHIFT;
 	unsigned long npages = dir_pages(inode);
@@ -254,6 +270,24 @@ static int nilfs_readdir(struct file *file, struct dir_context *ctx)
 			ctx->pos += PAGE_SIZE - offset;
 			return -EIO;
 		}
+		/*
+		 * ctx->pos comes from userspace via llseek and may point
+		 * into the middle of an entry -- or at unvalidated bytes
+		 * of a crafted image. offset is only nonzero here on the
+		 * very first iteration (subsequent pages always start at
+		 * offset 0, which -- like any chunk boundary -- is always
+		 * a legitimate entry start, since no rec_len chain crosses
+		 * a chunk boundary). Snap a non-chunk-aligned offset onto
+		 * a real entry boundary by walking the chain from the
+		 * enclosing chunk's start, as ext2 does; otherwise
+		 * dir_emit() copies name_len bytes from a fake entry,
+		 * reading past the end of the folio.
+		 */
+		if (offset & (chunk_size - 1)) {
+			offset = nilfs_validate_entry(kaddr, offset,
+					~(chunk_size - 1));
+			ctx->pos = ((loff_t)n << PAGE_SHIFT) + offset;
+		}
 		de = (struct nilfs_dir_entry *)(kaddr + offset);
 		limit = kaddr + nilfs_last_byte(inode, n) -
 			NILFS_DIR_REC_LEN(1);
Signature · 1 line
2.53.0
author maintainer
#571 lore raw

PATCH 568/1257 riscv: cfi: Bounds check restore token before swap

In reply to Greg Kroah-Hartman

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

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

From: Samuel Holland <[email protected]>

[ Upstream commit df333b72c0e14d6cffec72ce9a00503f12d1e28d ]

Currently the user-provided shadow stack restore token is not checked before being used as the address in ssamoswap.d. While an invalid restore token will be caught and raise SIGSEGV, this happens after writing 4 bytes of zeroes anywhere in the address space. Check that the restore token is at least a valid user address before the swap to ensure we do not scribble over kernel memory.

Fixes 66c9c713de59 ("riscv/signal: save and restore the shadow stack on a signal")
---
 arch/riscv/kernel/usercfi.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
arch/riscv/kernel/usercfi.c +4 -1
index dec0ba5eff5ea..23c4d6d9d8cbc 100644
@@ -206,10 +206,13 @@ int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
  */
 int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
 {
+	unsigned long __user *token_ptr = (unsigned long __user *)shstk_ptr;
 	unsigned long token = 0;
 
-	token = amo_user_shstk((unsigned long __user *)shstk_ptr, 0);
+	if (!access_ok(token_ptr, sizeof(token)))
+		return -EFAULT;
 
+	token = amo_user_shstk(token_ptr, 0);
 	if (token == -1)
 		return -EFAULT;
 
Signature · 1 line
2.53.0
author maintainer
#572 lore raw

PATCH 569/1257 riscv: cfi: Only write envcfg CSR when task is current

In reply to Greg Kroah-Hartman

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

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

From: Samuel Holland <[email protected]>

[ Upstream commit ca47e289113552fcbd7ab9268cee1f0c27d35590 ]

set_shstk_status() and set_indir_lp_status() take a task argument, which lets them operate on tasks other than current, but they always write the envcfg CSR for the current task. Fix this with the envcfg_update_bits() helper, which only writes the envcfg CSR when operating on current.

Fixes 61a0200211d31e ("riscv: Implement arch-agnostic shadow stack prctls")
Fixes 8a9e22d2ca5855 ("riscv: Implement indirect branch tracking prctls")
---
 arch/riscv/kernel/usercfi.c | 15 +++------------
 1 file changed, 3 insertions(+), 12 deletions(-)
arch/riscv/kernel/usercfi.c +3 -12
index 23c4d6d9d8cbc..86141e5bab822 100644
@@ -15,6 +15,7 @@
 #include <linux/syscalls.h>
 #include <linux/prctl.h>
 #include <asm/csr.h>
+#include <asm/switch_to.h>
 #include <asm/usercfi.h>
 
 unsigned long riscv_nousercfi __read_mostly;
@@ -66,12 +67,7 @@ void set_shstk_status(struct task_struct *task, bool enable)
 
 	task->thread_info.user_cfi_state.ubcfi_en = enable ? 1 : 0;
 
-	if (enable)
-		task->thread.envcfg |= ENVCFG_SSE;
-	else
-		task->thread.envcfg &= ~ENVCFG_SSE;
-
-	csr_write(CSR_ENVCFG, task->thread.envcfg);
+	envcfg_update_bits(task, ENVCFG_SSE, enable ? ENVCFG_SSE : 0);
 }
 
 void set_shstk_lock(struct task_struct *task, bool lock)
@@ -96,12 +92,7 @@ void set_indir_lp_status(struct task_struct *task, bool enable)
 
 	task->thread_info.user_cfi_state.ufcfi_en = enable ? 1 : 0;
 
-	if (enable)
-		task->thread.envcfg |= ENVCFG_LPE;
-	else
-		task->thread.envcfg &= ~ENVCFG_LPE;
-
-	csr_write(CSR_ENVCFG, task->thread.envcfg);
+	envcfg_update_bits(task, ENVCFG_LPE, enable ? ENVCFG_LPE : 0);
 }
 
 void set_indir_lp_lock(struct task_struct *task, bool lock)
Signature · 1 line
2.53.0
author maintainer
#573 lore raw

PATCH 570/1257 md: dont hand out the array before md_alloc() has added mddev->kobj

In reply to Greg Kroah-Hartman

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

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

From: Yogesh Gaur <[email protected]>

[ Upstream commit d1472ca2ca5de8ecd2b358411eb14c031404ecf0 ]

md_alloc() publishes the gendisk before it is done setting the mddev up:

	disk->private_data = mddev;
	...
	error = add_disk(disk);
	if (error)
		goto out_put_disk;

	kobject_init(&mddev->kobj, &md_ktype);
	error = kobject_add(&mddev->kobj, &disk_to_dev(disk)->kobj, "%s", "md");

add_disk() makes /dev/mdN openable. mddev comes from mddev_alloc() and is zeroed, so anything that gets in between add_disk() and kobject_add() sees an mddev->kobj that has never been through kobject_init() - no ktype, no kref, state_initialized clear.

syzbot opens the array in that window and issues ADD_NEW_DISK:

kobject: '(null)' (ffff8880120640f0): is not initialized, yet kobject_get() is being called.

  WARNING: lib/kobject.c:642 at kobject_add_internal+0xea/0xcd0 lib/kobject.c:225
   kobject_add_varg lib/kobject.c:374 [inline]
   kobject_add+0x163/0x240 lib/kobject.c:426
   bind_rdev_to_array+0x80c/0xdd0 drivers/md/md.c:2621
   md_add_new_disk+0xe3b/0x1850 drivers/md/md.c:7684
   md_ioctl+0x200a/0x2610 drivers/md/md.c:8499

bind_rdev_to_array() is not the only way in. md_run() calls sysfs_create_group(&mddev->kobj, &md_redundancy_group), and internal_create_group() has its own WARN_ON(!kobj->sd), so RUN_ARRAY in the same window warns too.

Every ioctl that can reach mddev->kobj runs under reconfig_mutex, so hold it across add_disk() and kobject_add(). An ioctl issued in the window now waits for md_alloc() to finish instead of seeing a half-built mddev, and opening the array still succeeds. The ioctls md_ioctl() serves without the mutex only read array state and return -ENODEV on an array with no disks.

Hoisting kobject_init() above add_disk() is not an option: commit ca39f7502425 ("md: fix mddev->kobj lifetime") moved it below add_disk() so that md_alloc()'s error paths, which free the mddev directly, never see an initialised kobject.

---
 drivers/md/md.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
drivers/md/md.c +11 -1
index 1caa92b40f9a7..d8ecf76d4a5f1 100644
@@ -6388,12 +6388,22 @@ struct mddev *md_alloc(dev_t dev, char *name)
 
 	disk->events |= DISK_EVENT_MEDIA_CHANGE;
 	mddev->gendisk = disk;
+
+	/*
+	 * add_disk() makes the array openable before mddev->kobj exists.
+	 * Hold reconfig_mutex until kobject_add() is done so that ioctls
+	 * issued in between wait instead of using an uninitialised kobj.
+	 */
+	mddev_lock_nointr(mddev);
 	error = add_disk(disk);
-	if (error)
+	if (error) {
+		mddev_unlock(mddev);
 		goto out_put_disk;
+	}
 
 	kobject_init(&mddev->kobj, &md_ktype);
 	error = kobject_add(&mddev->kobj, &disk_to_dev(disk)->kobj, "%s", "md");
+	mddev_unlock(mddev);
 	if (error) {
 		/*
 		 * The disk is already live at this point.  Clear the hold flag
Signature · 1 line
2.53.0
author maintainer
#574 lore raw

PATCH 571/1257 mm/hugetlb: charge folios to the target mms memcg

In reply to Greg Kroah-Hartman

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

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

From: Jinmeng Zhou <[email protected]>

[ Upstream commit c2deb1356d82c9d54bd2fcf1241cc97eb66fd81f ]

HugeTLB folios are currently charged to the memcg of the allocating task. This gives the wrong result when a userfaultfd handler populates a HugeTLB VMA that belongs to another process. The UFFDIO_COPY ioctl operates on the userfaultfd context's mm, but get_mem_cgroup_from_current() charges the folio to the handler's memcg instead.

This can be reproduced by placing the faulting process and its userfaultfd handler in different memory cgroups. Have the target process register a HugeTLB mapping with userfaultfd, trigger a missing fault, and let the handler resolve it with UFFDIO_COPY. The hugepage usage is then reported in the handler's memory.current instead of the target's.

The generic userfaultfd population path avoids this problem by charging folios to dst_vma->vm_mm.

Pass the target mm through hugetlb_alloc_folio() and charge the folio by using get_mem_cgroup_from_mm(). This preserves the existing charge timing and error handling while making HugeTLB userfaultfd population consistent with the generic path.

Fixes 8cba9576df60 ("hugetlb: memcg: account hugetlb-backed memory in memory controller")
Cc David Hildenbrand <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
---
 include/linux/hugetlb.h    | 3 ++-
 include/linux/memcontrol.h | 8 +++++---
 mm/hugetlb.c               | 9 ++++++---
 mm/memcontrol.c            | 6 ++++--
 4 files changed, 17 insertions(+), 9 deletions(-)
include/linux/hugetlb.h +2 -1
index 16c4c4caa126c..45ada75dc04e9 100644
@@ -699,7 +699,8 @@ enum hugetlb_alloc_flag {
 #define HUGETLB_ALLOC_USE_GLOBAL_RESERVATIONS BIT(HUGETLB_ALLOC_USE_GLOBAL_RESERVATIONS_BIT)
 
 struct folio *hugetlb_alloc_folio(struct hstate *h,
-		struct mempolicy_interpreted *mpoli, u8 alloc_flags);
+		struct mempolicy_interpreted *mpoli, struct mm_struct *mm,
+		u8 alloc_flags);
 struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
 				unsigned long addr, bool cow_from_owner);
 struct folio *alloc_hugetlb_folio_nodemask(struct hstate *h, int preferred_nid,
include/linux/memcontrol.h +5 -3
index 7d1c0ce189a88..362af58e50a43 100644
@@ -662,7 +662,8 @@ static inline int mem_cgroup_charge(struct folio *folio, struct mm_struct *mm,
 	return __mem_cgroup_charge(folio, mm, gfp);
 }
 
-int mem_cgroup_charge_hugetlb(struct folio* folio, gfp_t gfp);
+int mem_cgroup_charge_hugetlb(struct folio *folio, struct mm_struct *mm,
+			      gfp_t gfp);
 
 int mem_cgroup_swapin_charge_folio(struct folio *folio, unsigned short id,
 				   struct mm_struct *mm, gfp_t gfp);
@@ -1156,9 +1157,10 @@ static inline int mem_cgroup_charge(struct folio *folio,
 	return 0;
 }
 
-static inline int mem_cgroup_charge_hugetlb(struct folio* folio, gfp_t gfp)
+static inline int mem_cgroup_charge_hugetlb(struct folio *folio,
+					    struct mm_struct *mm, gfp_t gfp)
 {
-        return 0;
+	return 0;
 }
 
 static inline int mem_cgroup_swapin_charge_folio(struct folio *folio,
mm/hugetlb.c +6 -3
index 930e40ac77077..1c2b5825b5614 100644
@@ -2827,6 +2827,7 @@ void wait_for_freed_hugetlb_folios(void)
  * hugetlb_alloc_folio - Allocate a hugetlb folio.
  * @h: Hugetlb state control block.
  * @mpoli: Interpreted memory policy to use for allocation.
+ * @mm: Memory descriptor of the allocation target.
  * @alloc_flags: Flags controlling the allocation behavior.
  *
  * Allocates a hugetlb folio and handles cgroup charging and global hstate
@@ -2836,7 +2837,8 @@ void wait_for_freed_hugetlb_folios(void)
  *         -ENOSPC if cgroup charging fails or no folio is available.
  */
 struct folio *hugetlb_alloc_folio(struct hstate *h,
-		struct mempolicy_interpreted *mpoli, u8 alloc_flags)
+		struct mempolicy_interpreted *mpoli, struct mm_struct *mm,
+		u8 alloc_flags)
 {
 	bool charge_hugetlb_cgroup_rsvd = alloc_flags &
 					  HUGETLB_ALLOC_CHARG_CGROUP_RSVD;
@@ -2891,7 +2893,8 @@ struct folio *hugetlb_alloc_folio(struct hstate *h,
 
 	spin_unlock_irq(&hugetlb_lock);
 
-	ret = mem_cgroup_charge_hugetlb(folio, gfp | __GFP_RETRY_MAYFAIL);
+	ret = mem_cgroup_charge_hugetlb(folio, mm,
+					gfp | __GFP_RETRY_MAYFAIL);
 	/*
 	 * Unconditionally increment NR_HUGETLB here because if
 	 * mem_cgroup_charge_hugetlb failed, freeing the page will
@@ -3034,7 +3037,7 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
 		.nodemask = nodemask,
 	};
 
-	folio = hugetlb_alloc_folio(h, &mpoli, alloc_flags);
+	folio = hugetlb_alloc_folio(h, &mpoli, vma->vm_mm, alloc_flags);
 
 	mpol_cond_put(mpol);
 
mm/memcontrol.c +4 -2
index 259f9f43b38b1..1f03f5e775554 100644
@@ -5242,6 +5242,7 @@ int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
 /**
  * mem_cgroup_charge_hugetlb - charge the memcg for a hugetlb folio
  * @folio: folio being charged
+ * @mm: mm context of the allocation target
  * @gfp: reclaim mode
  *
  * This function is called when allocating a huge page folio, after the page has
@@ -5251,9 +5252,10 @@ int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
  * Returns ENOMEM if the memcg is already full.
  * Returns 0 if either the charge was successful, or if we skip the charging.
  */
-int mem_cgroup_charge_hugetlb(struct folio *folio, gfp_t gfp)
+int mem_cgroup_charge_hugetlb(struct folio *folio, struct mm_struct *mm,
+			      gfp_t gfp)
 {
-	struct mem_cgroup *memcg = get_mem_cgroup_from_current();
+	struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
 	int ret = 0;
 
 	/*
Signature · 1 line
2.53.0
author maintainer
#575 lore raw

PATCH 572/1257 mm/memory: constrain generic_access_phys() to page boundary

In reply to Greg Kroah-Hartman

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

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

From: Luxiao Xu <[email protected]>

[ Upstream commit ae0298a5fbeff32951c0d31398ccec97ec6aa0ea ]

This patch addresses an issue in generic_access_phys() where accessing memory across page boundaries in PFNMAP VMAs assumes physical pages are contiguous, which can lead to accessing unintended physical memory or exceeding VMA boundaries.

generic_access_phys() improperly validates the memory access range: it only validates the start address using follow_pfnmap_start() and passes PAGE_ALIGN(len + offset) to ioremap_prot().

This poses two problems:
1. In PFNMAP VMAs, consecutive virtual pages are not guaranteed to be physically contiguous, and individual PTEs may have different access permissions or writability.
2. The mapping may cross VMA boundaries if len extends beyond vma->vm_end.

Constrain the access in generic_access_phys() to at most the current page boundary (PAGE_SIZE - offset) and map only a single PAGE_SIZE via ioremap_prot(). Since the caller __access_remote_vm() already loops over the requested length and handles partial transfers, it will naturally iterate over the remaining pages.

Also add a missing (resource_size_t) cast during PFN re-validation to avoid truncation on 32-bit PAE systems.

Fixes 9cb12d7b4cca ("mm/memory.c: actually remap enough memory")
Assisted-by LLM
Cc Grazvydas Ignotas <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
---
 mm/memory.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
mm/memory.c +8 -2
index 8b0c2c735d3de..4f8199de44afb 100644
@@ -7164,6 +7164,12 @@ int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
 	bool writable;
 	struct follow_pfnmap_args args = { .vma = vma, .address = addr };
 
+	/*
+	 * Limit access to one page at a time, as that's what follow_pfnmap_start()
+	 * guarantees; expect the caller to retry to read larger ranges.
+	 */
+	len = min_t(int, len, PAGE_SIZE - offset);
+
 retry:
 	if (follow_pfnmap_start(&args))
 		return -EINVAL;
@@ -7175,7 +7181,7 @@ int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
 	if ((write & FOLL_WRITE) && !writable)
 		return -EINVAL;
 
-	maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
+	maddr = ioremap_prot(phys_addr, PAGE_SIZE, prot);
 	if (!maddr)
 		return -ENOMEM;
 
@@ -7183,7 +7189,7 @@ int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
 		goto out_unmap;
 
 	if ((pgprot_val(prot) != pgprot_val(args.pgprot)) ||
-	    (phys_addr != (args.pfn << PAGE_SHIFT)) ||
+	    (phys_addr != ((resource_size_t)args.pfn << PAGE_SHIFT)) ||
 	    (writable != args.writable)) {
 		follow_pfnmap_end(&args);
 		iounmap(maddr);
Signature · 1 line
2.53.0
author maintainer
#576 lore raw

PATCH 573/1257 mm: memcg: redirect stats updates of dying memcgs for all hierarchies

In reply to Greg Kroah-Hartman

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

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

From: Hui Zhu <[email protected]>

[ Upstream commit 7ee68fff2ba6740558cab195925b3a7ff7a1480f ]

Patch series "mm: workingset: fix the shadow node budget under MGLRU", v5.

Commit 7404bd37cfbe ("mm: workingset: use lruvec_lru_size() to get the number of lru pages") broke the workingset shadow node budget under MGLRU:
lruvec_lru_size() reads mz->lru_zone_size, which MGLRU never maintains, so count_shadow_nodes() sees the evictable LRU lists as empty and the shadow shrinker reclaims eviction tokens almost as fast as they are created, losing thrashing protection.

Patch 1 extends the dying-mcg stat redirection (previously cgroup v1 only) to all hierarchies, addressing the reparenting race that motivated 7404bd37cfbe.

Patch 2 then switches count_shadow_nodes() back to lruvec_page_state_local(), which both classic LRU and MGLRU maintain.

Patch 3 recovers the performance. Patch 1 added an unconditional rcu_read_lock() to the stat update fast path; patch 3 checks memcg_is_dying() first and takes the RCU lock only on the rare dying path.

Patch 4 closes an accounting gap that patch 2 makes visible: on cgroup v2, reparent_state_local() never moves the dying memcg's non-hierarchical lruvec stats to the parent, so the parent receives the uncharges without the matching charges and its state_local underflows. Patch 4 reparents those stats, mirroring cgroup v1.

Performance testing
===================

The test script and the raw results are available at [1].

Environment: 10-vCPU QEMU guest, 8 GiB RAM, cgroup v2; 7 runs per configuration, medians reported. Workloads:

w1-anon-churn: single-threaded anon fault/charge loop in a memcg
(MADV_DONTNEED + re-fault, no reclaim). Every touch is a real fault with charge and memcg stat updates, so it stresses exactly the fast path patch 1 changes. This is the meaningful signal: it is not reclaim-bound, so the small fast-path overhead is not drowned out.
w2-file-churn: file read loop under memory.high pressure
(reclaim-bound; the differences below are within run-to-run noise and are shown for completeness only).
w3-reparent: reparent accounting sanity check.

w1-anon-churn (pages/s):

                 classic LRU          MGLRU
base             4393028              4377122
patches 1-2      4385996   (-0.2%)    4352887   (-0.6%)
patches 1-3      4381832   (-0.3%)    4377053   (+0.0%)

w2-file-churn (MB/s):

                 classic LRU          MGLRU
base             8277                 8226
patches 1-2      8226      (-0.6%)    8123      (-1.3%)
patches 1-3      8157      (-1.4%)    8294      (+0.8%)

w3-reparent passed on all kernels.

The small overhead visible with patches 1-2 comes from the redirection added by patch 1; patch 3 brings w1 back to the base level in both LRU configurations. The w2-file-churn differences are within run-to-run
noise: that workload is reclaim-bound and too noisy to expose the small fast-path overhead, so w1-anon-churn is the meaningful signal. Patch 4 only touches the memcg offline path and is not exercised by these workloads.

This patch (of 4):

get_non_dying_memcg_start() redirects the stat updates of a dying memcg to its closest non-dying ancestor, but only on cgroup v1; on cgroup v2 the stats keep being accounted to the dying memcg itself.

A later patch in this series restores lruvec_page_state_local() in count_shadow_nodes() to fix the broken workingset shadow node budget under MGLRU. count_shadow_nodes() is the only reader of those non-hierarchical state_locals on cgroup v2: when a memcg is offlined, its pages are reparented to the ancestor but their stat updates keep being accounted to the dying memcg, so count_shadow_nodes() computes a wrong shadow node budget and workingset thrashing protection is lost. This is user visible as premature reclaim of hot page cache and degraded performance under memory pressure. Apply the redirection to all hierarchies to fix this.

Offlining is rare, so the added cost on the stat update fast path is limited to an rcu_read_lock() and a css_is_dying() check; the upward walk happens only while a memcg is dying.

---
 mm/memcontrol.c | 30 +++++-------------------------
 1 file changed, 5 insertions(+), 25 deletions(-)
mm/memcontrol.c +5 -25
index 1f03f5e775554..af61dacf0d180 100644
@@ -845,20 +845,14 @@ static long memcg_state_val_in_pages(int idx, long val)
 	return val < 0 ? -res : res;
 }
 
-#ifdef CONFIG_MEMCG_V1
 /*
- * Used in mod_memcg_state() and mod_memcg_lruvec_state() to avoid race with
- * reparenting of non-hierarchical state_locals.
+ * Used in mod_memcg_state() and mod_memcg_lruvec_state() to avoid race
+ * with reparenting of non-hierarchical state_locals.  Offlining a
+ * memcg is rare, so do the redirection for all cgroup hierarchies.
  */
-static inline struct mem_cgroup *get_non_dying_memcg_start(struct mem_cgroup *memcg,
-							   bool *rcu_locked)
+static inline struct mem_cgroup *
+get_non_dying_memcg_start(struct mem_cgroup *memcg, bool *rcu_locked)
 {
-	/* Rebinding can cause this value to be changed at runtime */
-	if (cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
-		*rcu_locked = false;
-		return memcg;
-	}
-
 	rcu_read_lock();
 	*rcu_locked = true;
 
@@ -870,22 +864,8 @@ static inline struct mem_cgroup *get_non_dying_memcg_start(struct mem_cgroup *me
 
 static inline void get_non_dying_memcg_end(bool rcu_locked)
 {
-	if (!rcu_locked)
-		return;
-
 	rcu_read_unlock();
 }
-#else
-static inline struct mem_cgroup *get_non_dying_memcg_start(struct mem_cgroup *memcg,
-							   bool *rcu_locked)
-{
-	return memcg;
-}
-
-static inline void get_non_dying_memcg_end(bool rcu_locked)
-{
-}
-#endif
 
 static void __mod_memcg_state(struct mem_cgroup *memcg,
 			      enum memcg_stat_item idx, long val)
Signature · 1 line
2.53.0
author maintainer
#577 lore raw

PATCH 574/1257 mm: workingset: use lruvec_page_state_local() to count lru pages

In reply to Greg Kroah-Hartman

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

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

From: Hui Zhu <[email protected]>

[ Upstream commit c7a37bac3ccc2732993705d3c3488b278b422ec6 ]

Commit 7404bd37cfbe ("mm: workingset: use lruvec_lru_size() to get the number of lru pages") switched count_shadow_nodes() to lruvec_lru_size(). With CONFIG_MEMCG enabled, lruvec_lru_size() reads mz->lru_zone_size, which only the classic LRU paths maintain. MGLRU accounts its pages through __update_lru_size(), which skips that array, so with MGLRU on the four evictable LRU lists are always seen as empty. The shadow node budget (pages >> 3) then collapses to slab plus unevictable pages, and the workingset shadow shrinker reclaims eviction tokens almost as fast as they are created, losing thrashing protection.

lruvec_page_state_local() reads lruvec_stats->state_local instead, which both classic LRU and MGLRU maintain. Switch back to it. The reparenting race this re-exposes on cgroup v2 is closed by the preceding patch that redirects dying-memcg stat updates for all hierarchies.

Fixes 7404bd37cfbe ("mm: workingset: use lruvec_lru_size() to get the number of lru pages")
Cc Axel Rasmussen <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Muchun Song <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Wei Xu <[email protected]>
Cc Yuanchu Xie <[email protected]>
---
 mm/workingset.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
mm/workingset.c +2 -3
index 7ac2b88c80ae5..8412f4840ae35 100644
@@ -688,10 +688,9 @@ static unsigned long count_shadow_nodes(struct shrinker *shrinker,
 
 		mem_cgroup_flush_stats_ratelimited(sc->memcg);
 		lruvec = mem_cgroup_lruvec(sc->memcg, NODE_DATA(sc->nid));
-
 		for (pages = 0, i = 0; i < NR_LRU_LISTS; i++)
-			pages += lruvec_lru_size(lruvec, i, MAX_NR_ZONES - 1);
-
+			pages += lruvec_page_state_local(lruvec,
+							 NR_LRU_BASE + i);
 		pages += lruvec_page_state_local(
 			lruvec, NR_SLAB_RECLAIMABLE_B) >> PAGE_SHIFT;
 		pages += lruvec_page_state_local(
Signature · 1 line
2.53.0
author maintainer
#578 lore raw

PATCH 575/1257 mm: memcg: skip the RCU lock when the memcg is not dying

In reply to Greg Kroah-Hartman

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

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

From: Hui Zhu <[email protected]>

[ Upstream commit 7c0a645068deaf4c3a8c619ddbb8b84c477f9a9a ]

get_non_dying_memcg_start() takes rcu_read_lock() on every stat update, but the lock only protects the upward walk to a non-dying ancestor, which happens solely while a memcg is being offlined. The dying check itself reads the CSS_DYING flag of a memcg the caller already holds a reference to, so it is safe without the lock.

Check memcg_is_dying() first and return immediately when the memcg is alive, taking the RCU lock only on the rare dying path. On an anon fault/charge churn workload in a memcg this recovers the ~0.6% overhead added by the previous patch (4368077 vs 4343159 pages/s before, back to ~4377000 pages/s after).

Fixes 7404bd37cfbe ("mm: workingset: use lruvec_lru_size() to get the number of lru pages")
Cc Axel Rasmussen <[email protected]>
Cc Barry Song <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Kairui Song <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Muchun Song <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Wei Xu <[email protected]>
Cc Yuanchu Xie <[email protected]>
---
 mm/memcontrol.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
mm/memcontrol.c +14 -0
index af61dacf0d180..ed371b1ddab87 100644
@@ -853,6 +853,17 @@ static long memcg_state_val_in_pages(int idx, long val)
 static inline struct mem_cgroup *
 get_non_dying_memcg_start(struct mem_cgroup *memcg, bool *rcu_locked)
 {
+	/*
+	 * Fast path: the caller holds a reference to @memcg, so reading
+	 * its CSS_DYING flag without the RCU lock is safe.  The RCU lock
+	 * is only needed to walk up to a non-dying ancestor, which
+	 * happens only while a memcg is actually being offlined.
+	 */
+	if (!memcg_is_dying(memcg)) {
+		*rcu_locked = false;
+		return memcg;
+	}
+
 	rcu_read_lock();
 	*rcu_locked = true;
 
@@ -864,6 +875,9 @@ get_non_dying_memcg_start(struct mem_cgroup *memcg, bool *rcu_locked)
 
 static inline void get_non_dying_memcg_end(bool rcu_locked)
 {
+	if (!rcu_locked)
+		return;
+
 	rcu_read_unlock();
 }
 
Signature · 1 line
2.53.0
author maintainer
#579 lore raw

PATCH 576/1257 mm: memcg: reparent non-hierarchical lruvec stats on cgroup v2

In reply to Greg Kroah-Hartman

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

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

From: Hui Zhu <[email protected]>

[ Upstream commit 154c16a783b75105347cf5ed7731afc887308120 ]

On cgroup v2, reparent_state_local() returns early and never moves the dying memcg's non-hierarchical state_local base counts to its parent. Meanwhile memcg_reparent_objcgs() rewrites objcg->memcg to the parent, so when the reparented folios are freed later, the negative deltas land on the parent's lruvec. The parent therefore receives the uncharges without ever having received the matching charges, and its state_local (NR_LRU_BASE + lru, MEMCG_SOCK, NR_SLAB_RECLAIMABLE_B, NR_SLAB_UNRECLAIMABLE_B) permanently underflows. Since lruvec_page_state_local() clamps negative values to zero, the underflow masks the parent's own legitimate pages.

count_shadow_nodes() is the only reader of these non-hierarchical state_locals on cgroup v2, so the underflow directly distorts the workingset shadow node budget.

Fix this by reparenting the lruvec state_locals on cgroup v2 as well, mirroring what cgroup v1 already does. Only the lruvec stats consumed by count_shadow_nodes() are moved; the memcg-level stats are left alone because on v2 they are exposed through the rstat hierarchical tree and are not read from state_local.

Fixes 8285917d6f38 ("mm: memcontrol: prepare for reparenting non-hierarchical stats")
Cc Axel Rasmussen <[email protected]>
Cc Barry Song <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Kairui Song <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Muchun Song <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Wei Xu <[email protected]>
Cc Yuanchu Xie <[email protected]>
---
 mm/memcontrol-v1.h |  5 +++--
 mm/memcontrol.c    | 42 ++++++++++++++++++++++++++++--------------
 2 files changed, 31 insertions(+), 16 deletions(-)
mm/memcontrol-v1.h +3 -2
index 1e394269c613d..0578b7076764d 100644
@@ -25,6 +25,9 @@ int memory_stat_show(struct seq_file *m, void *v);
 struct mem_cgroup *mem_cgroup_private_id_get_online(struct mem_cgroup *memcg,
 						    unsigned int n);
 
+void reparent_memcg_lruvec_state_local(struct mem_cgroup *memcg,
+				       struct mem_cgroup *parent, int idx);
+
 /* Cgroup v1-specific declarations */
 #ifdef CONFIG_MEMCG_V1
 
@@ -73,8 +76,6 @@ void reparent_memcg1_lruvec_state_local(struct mem_cgroup *memcg, struct mem_cgr
 
 void reparent_memcg_state_local(struct mem_cgroup *memcg,
 				struct mem_cgroup *parent, int idx);
-void reparent_memcg_lruvec_state_local(struct mem_cgroup *memcg,
-				       struct mem_cgroup *parent, int idx);
 
 void memcg1_account_kmem(struct mem_cgroup *memcg, int nr_pages);
 static inline bool memcg1_tcpmem_active(struct mem_cgroup *memcg)
mm/memcontrol.c +28 -14

73 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#580 lore raw

PATCH 577/1257 mm/execmem: free ROX cache chunks only when they span an entire vm area

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]>

[ Upstream commit 52d95a55a0113408acd2d4ce0294a72c527f5092 ]

Patch series "mm/execmem: fixes and cleanups for the ROX cache".

Sashiko review of the ROX cache refill path asked what happens when the PMD_SIZE allocation fails there. Pulling that thread uncovered a bit more than the fallback.

Patch 1 fixes a real bug, although rare bug: execmem_cache_clean() can free a chunk that is still partially in use, because a PMD sized and PMD aligned free range in the middle of a larger chunk looks exactly like a chunk that nobody uses.

Patch 2 handles maple tree allocation failures in the cache. They are unlikely, but silently dropping an area from the tree is not a great way to deal with them.

Patch 3 deals with the fallback that started all this. The cache exists to keep the direct map free of unnecessary splits, and the fallback happily filled it with base page mapped areas that could never be freed from the cache again. Ask vmalloc for a huge mapping or nothing, and serve whatever does not fit outside the cache.

Patches 4 and 5 convert the ROX cache to scope based cleanup.

The series was tested on x86 with module load/unload cycles, with PTDUMP confirming that the cache is using 2M mappings, and with nohugevmalloc to exercise the uncached fallback.

This patch (of 5):

When execmem refills the ROX cache, it vmalloc()s multiples of PMD_SIZE aligned to PMD_SIZE. For every such allocation vmalloc creates a vm area.

The first part of the vmalloc()ed chunk is returned to the allocation that triggered the cache refill and the remaining part is added to the cache and handed out for subsequent allocations with execmem_alloc().

When only the first part is freed, the entire vm area remains in the ROX cache and can be handed out again.

In the case when the first allocation is larger than PMD_SIZE and the second allocation from the freed first part of the chunk is exactly PMD_SIZE, execmem_cache_clean() will free the entire chunk while part of it is still in use.

For example:

	/*
	 * vmalloc(4M), return p0 to the caller
	 * add [p0 + 3M, p0 + 4M) to the cache
	 */
	p0 = execmem_alloc(3M);

	/* return p0 + 3M from the cache to the caller */
	p1 = execmem_alloc(1M);

	/* put [p0, p0 + 3M) back into the cache */
	execmem_free(p0);

	/* return p0 from the cache to the caller */
	p2 = execmem_alloc(2M);

	/* return p0 + 2M from the cache to the caller */
	p3 = execmem_alloc(1M);

	/* bah! execmem_cache_clean() frees the entire 4M chunk */
	execmem_free(p2);

Make sure that the ranges that execmem_cache_clean() frees cover the entire vm area.

Fixes 2e45474ab14f ("execmem: add support for cache of large ROX pages")
Assisted-by copilot:claude-opus-5
Cc Benjamin Tissoires <[email protected]>
Cc Jiri Kosina <[email protected]>
Cc Luis Chamberalin <[email protected]>
Cc "Uladzislau Rezki (Sony)" <[email protected]>
---
 mm/execmem.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/execmem.c +3 -1
index 74a178a87e758..33e4e68f655f0 100644
@@ -165,9 +165,11 @@ static void execmem_cache_clean(struct work_struct *work)
 
 	mutex_lock(mutex);
 	mas_for_each(&mas, area, ULONG_MAX) {
+		struct vm_struct *vm = find_vm_area(area);
 		size_t size = mas_range_len(&mas);
 
-		if (IS_ALIGNED(size, PMD_SIZE) &&
+		if (vm && get_vm_area_size(vm) == size &&
+		    IS_ALIGNED(size, PMD_SIZE) &&
 		    IS_ALIGNED(mas.index, PMD_SIZE)) {
 			struct vm_struct *vm = find_vm_area(area);
 
Signature · 1 line
2.53.0
author maintainer
#581 lore raw

PATCH 578/1257 mm/nommu: reject wrapping ranges in access_remote_vm()

In reply to Greg Kroah-Hartman

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

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

From: Anastasios Papagiannis <[email protected]>

[ Upstream commit 51a8de81fd2edbf87d8046e352060329bb216fad ]

The NOMMU implementation of access_process_vm() rejects address ranges whose end wraps around, but access_remote_vm() bypasses this check even though both functions delegate to __access_remote_vm().

Move the wraparound check into __access_remote_vm() so it applies to both entry points.

This is originally reported in [1].

---
 mm/nommu.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
mm/nommu.c +3 -3
index 498e01ee40b05..ed44510e37707 100644
@@ -1674,6 +1674,9 @@ static int __access_remote_vm(struct mm_struct *mm, unsigned long addr,
 	struct vm_area_struct *vma;
 	int write = gup_flags & FOLL_WRITE;
 
+	if (addr + len < addr)
+		return 0;
+
 	if (mmap_read_lock_killable(mm))
 		return 0;
 
@@ -1727,9 +1730,6 @@ int access_process_vm(struct task_struct *tsk, unsigned long addr, void *buf, in
 {
 	struct mm_struct *mm;
 
-	if (addr + len < addr)
-		return 0;
-
 	mm = get_task_mm(tsk);
 	if (!mm)
 		return 0;
Signature · 1 line
2.53.0
author maintainer
#582 lore raw

PATCH 579/1257 mm/hugetlb: fix subpool minimum reservation rollback

In reply to Greg Kroah-Hartman

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

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

From: Jinmeng Zhou <[email protected]>

[ Upstream commit e4949a80f3b07e52dca76c34ce353633927a28a5 ]

When a reservation request is partially covered by a subpool minimum and the remaining global reservation fails, the error path first calls hugepage_subpool_put_pages() for the subpool-backed portion. It removes the failed global portion from used_hpages only afterwards.

hugepage_subpool_put_pages() uses used_hpages to decide whether rsv_hpages should be restored. Since used_hpages still includes the global portion, it can remain at or above min_hpages and prevent that restoration. It then reports the subpool reservation as releasable, causing hugetlb_acct_memory() to incorrectly decrement h->resv_huge_pages.

This was reproduced with four 2 MB huge pages and a hugetlbfs mount with size=10M,min_size=8M. After a successful three-page reservation, a two-page reservation which needed one subpool page and one global page failed with -ENOMEM. HugePages_Rsvd incorrectly dropped from four to three even though the subpool minimum was still four pages.

Roll back the failed global portion from used_hpages first, so that hugepage_subpool_put_pages() evaluates the minimum reservation against the current usage and returns the correct global adjustment.

Fixes a833a693a490 ("mm: hugetlb: fix incorrect fallback for subpool")
Cc David Hildenbrand <[email protected]>
Cc Ma Wupeng <[email protected]>
Cc Oscar Salvador <[email protected]>
---
 mm/hugetlb.c | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)
mm/hugetlb.c +9 -9
index 1c2b5825b5614..8dec4f5fc1e6e 100644
@@ -6837,15 +6837,6 @@ long hugetlb_reserve_pages(struct inode *inode,
 
 out_put_pages:
 	spool_resv = chg - gbl_reserve;
-	if (spool_resv) {
-		/* put sub pool's reservation back, chg - gbl_reserve */
-		gbl_resv = hugepage_subpool_put_pages(spool, spool_resv);
-		/*
-		 * subpool's reserved pages can not be put back due to race,
-		 * return to hstate.
-		 */
-		hugetlb_acct_memory(h, -gbl_resv);
-	}
 	/* Restore used_hpages for pages that failed global reservation */
 	if (gbl_reserve && spool) {
 		unsigned long flags;
@@ -6855,6 +6846,15 @@ long hugetlb_reserve_pages(struct inode *inode,
 			spool->used_hpages -= gbl_reserve;
 		unlock_or_release_subpool(spool, flags);
 	}
+	if (spool_resv) {
+		/* put sub pool's reservation back, chg - gbl_reserve */
+		gbl_resv = hugepage_subpool_put_pages(spool, spool_resv);
+		/*
+		 * subpool's reserved pages can not be put back due to race,
+		 * return to hstate.
+		 */
+		hugetlb_acct_memory(h, -gbl_resv);
+	}
 out_uncharge_cgroup:
 	hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
 					    chg * pages_per_huge_page(h), h_cg);
Signature · 1 line
2.53.0
author maintainer
#583 lore raw

PATCH 580/1257 mm/zswap: publish the initial pool with list_add_rcu()

In reply to Greg Kroah-Hartman

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

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

From: Longlong Xia <[email protected]>

[ Upstream commit c1dd5e24a82d19bff8eef50ba8205d4776584aff ]

zswap_setup() publishes the pool on the zswap_pools list with a plain list_add(), but the list is walked by concurrent RCU readers holding nothing but rcu_read_lock() through zswap_total_pages(), e.g. /proc/meminfo and the shrinker count path.

    CPU 0 (writer)                          CPU 1 (reader)
    --------------                          --------------
    zswap_pool_create():
      pool->zs_pool = zs_create_pool(); (1)
    list_add() -> __list_add():
      WRITE_ONCE(zswap_pools.next,
          &pool->list);                (2)   zswap_total_pages():
                                                pool = READ_ONCE(     (a)
                                                    zswap_pools.next);
                                                zs_get_total_pages(   (b)
                                                    pool->zs_pool);

If (2) becomes visible to CPU 1 before (1), CPU 1 finds the pool at (a) but dereferences a wild pointer at (b). Publish the node with list_add_rcu().

---
 mm/zswap.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/zswap.c +1 -1
index 37f34e406c8e3..cb5a0855fd2a7 100644
@@ -1803,7 +1803,7 @@ static int zswap_setup(void)
 	pool = __zswap_pool_create_fallback();
 	if (pool) {
 		pr_info("loaded using pool %s\n", pool->tfm_name);
-		list_add(&pool->list, &zswap_pools);
+		list_add_rcu(&pool->list, &zswap_pools);
 		zswap_has_pool = true;
 		static_branch_enable(&zswap_ever_enabled);
 	} else {
Signature · 1 line
2.53.0
author maintainer
#584 lore raw

PATCH 581/1257 mm/memcg: clear folio memcg after changing per memcg stats

In reply to Greg Kroah-Hartman

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

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

From: Bingfang Guo <[email protected]>

[ Upstream commit 0b1b457ecc4f636d85e1a0fade05f3dee264f59a ]

I notice extremely high swapcached count in the per memcg level memory.stat when running tests with cgroupv1 setup by swapping pages in and out. It seems that the counter never gets decreased so the value is rather useless and confusing to users reading it. So I think fixing it so that the value can reflect the actual swapcache usage correctly could be helpful.

__memcg1_swapout() transfers the memsw charge of a folio to its swap entry and clears folio->memcg_data as part of that. In the vmscan swapout path it runs before __swap_cache_del_folio(), which then decrements the swapcache stats through lruvec_stat_mod_folio(). Since folio->memcg_data has already been cleared, folio_memcg() returns NULL and the NR_SWAPCACHE decrement only updates the node-level counter instead of the memcg's lruvec, leaking the per-memcg swapcache count.

Users using swaps will read totally meaningless swapcache value from per memcg memory.stat, like 200GB of swapcache on a 64GB setup, which is quite confusing and may trigger monitoring alerts, if any.

Move the __memcg1_swapout() call into __swap_cache_del_folio(), after the NR_FILE_PAGES and NR_SWAPCACHE updates but before __swap_cache_do_del_folio() removes the folio from the swap cache. This keeps the stats attributed to the folio's memcg while still recording the swap cgroup with a valid folio->swap. Add a swapout parameter so the plain swap_cache_del_folio() path is left unchanged.

Fixes 2732acda82c9 ("mm, swap: use swap cache as the swap in synchronize layer")
Cc Axel Rasmussen <[email protected]>
Cc Baoquan He <[email protected]>
Cc Barry Song <[email protected]>
Cc Chris Li <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Kemeng Shi <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Wei Xu <[email protected]>
Cc Yuanchu Xie <[email protected]>
---
 mm/swap.h       |  6 ++++--
 mm/swap_state.c | 13 ++++++++++---
 mm/vmscan.c     |  3 +--
 3 files changed, 15 insertions(+), 7 deletions(-)
mm/swap.h +4 -2
index 90a551a88df63..c9202516b413e 100644
@@ -319,7 +319,8 @@ struct folio *swap_cache_alloc_folio(swp_entry_t target_entry, gfp_t gfp_mask,
 void __swap_cache_add_folio(struct swap_cluster_info *ci,
 			    struct folio *folio, swp_entry_t entry);
 void __swap_cache_del_folio(struct swap_cluster_info *ci,
-			    struct folio *folio, swp_entry_t entry, void *shadow);
+			    struct folio *folio, swp_entry_t entry, void *shadow,
+			    bool swapout);
 void __swap_cache_replace_folio(struct swap_cluster_info *ci,
 				struct folio *old, struct folio *new);
 
@@ -453,7 +454,8 @@ static inline void swap_cache_del_folio(struct folio *folio)
 }
 
 static inline void __swap_cache_del_folio(struct swap_cluster_info *ci,
-		struct folio *folio, swp_entry_t entry, void *shadow)
+		struct folio *folio, swp_entry_t entry, void *shadow,
+		bool swapout)
 {
 }
 
mm/swap_state.c +10 -3
index f3961fdd857dc..cb574030b814f 100644
@@ -306,21 +306,28 @@ static void __swap_cache_do_del_folio(struct swap_cluster_info *ci,
  * @folio: The folio.
  * @entry: The first swap entry that the folio corresponds to.
  * @shadow: shadow value to be filled in the swap cache.
+ * @swapout: whether this folio is being reclaimed after swapout.
  *
  * Removes a folio from the swap cache and fills a shadow in place.
  * This won't put the folio's refcount. The caller has to do that.
  *
  * Context: Caller must ensure the folio is locked and in the swap cache
  * using the index of @entry, and lock the cluster that holds the entries.
+ * If @swapout is set, the folio should be in reclaim path and IRQs
+ * should be disabled.
  */
 void __swap_cache_del_folio(struct swap_cluster_info *ci, struct folio *folio,
-			    swp_entry_t entry, void *shadow)
+			    swp_entry_t entry, void *shadow, bool swapout)
 {
 	unsigned long nr_pages = folio_nr_pages(folio);
 
-	__swap_cache_do_del_folio(ci, folio, entry, shadow);
 	node_stat_mod_folio(folio, NR_FILE_PAGES, -nr_pages);
 	lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr_pages);
+
+	if (swapout)
+		__memcg1_swapout(folio, ci);
+
+	__swap_cache_do_del_folio(ci, folio, entry, shadow);
 }
 
 /**
@@ -339,7 +346,7 @@ void swap_cache_del_folio(struct folio *folio)
 	swp_entry_t entry = folio->swap;
 
 	ci = swap_cluster_lock(__swap_entry_to_info(entry), swp_offset(entry));
-	__swap_cache_del_folio(ci, folio, entry, NULL);
+	__swap_cache_del_folio(ci, folio, entry, NULL, false);
 	swap_cluster_unlock(ci);
 
 	folio_ref_sub(folio, folio_nr_pages(folio));
mm/vmscan.c +1 -2
index f11491ee9ed5c..17ab01693ae8d 100644
@@ -735,8 +735,7 @@ static int __remove_mapping(struct address_space *mapping, struct folio *folio,
 
 		if (reclaimed && !mapping_exiting(mapping))
 			shadow = workingset_eviction(folio, target_memcg);
-		__memcg1_swapout(folio, ci);
-		__swap_cache_del_folio(ci, folio, swap, shadow);
+		__swap_cache_del_folio(ci, folio, swap, shadow, true);
 		swap_cluster_unlock_irq(ci);
 	} else {
 		void (*free_folio)(struct folio *);
Signature · 1 line
2.53.0
author maintainer
#585 lore raw

PATCH 582/1257 mm/page_counter: avoid integer overflow in effective_protection()

In reply to Greg Kroah-Hartman

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

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

From: Ridong Chen <[email protected]>

[ Upstream commit 7809ce47b05671e1fa6d74bead892d6ad6c1403b ]

Patch series "mm/mglru: fix ineffective memory protection for non-kswapd reclaim", v4.

For MGLRU, memory.min/low is not honored during non-kswapd global reclaim (global direct reclaim and root-level memory.reclaim), because these paths shrink memcgs using stale protection (emin/elow).

Patch 2 is the actual fix. Patch 1 is a prerequisite: an integer overflow in effective_protection(), spotted by the sashiko review tool, which patch 2's new caller would also be exposed to.

This patch (of 2):

effective_protection() scales a parent's protection by a ratio of page counts, e.g. for recursive protection:

(parent_effective - siblings_protected) * (usage - protected)
/ (parent_usage - siblings_protected)

The multiply is done at unsigned long width before dividing. On systems with >= 16TB RAM the product can exceed 2^64 and wrap, giving a bogus protection value and silently breaking memory.min/low enforcement.

Use mul_u64_u64_div_u64() to multiply in a 128-bit intermediate. Because usage and parent_usage are not read atomically (a child is charged before its parent), usage - protected can briefly exceed the divisor, making the quotient overflow 64 bits and trap (#DE on x86). Cap it so the ratio stays <= 1.

Reported by the sashiko review tool [1].

Fixes bc50bcc6e00b ("mm: memcontrol: clean up and document effective low/min calculations")
Fixes 8a931f801340 ("mm: memcontrol: recursive memory.low protection")
Assisted-by Claude:claude-opus-4-8
Cc Axel Rasmussen <[email protected]>
Cc Chris Down <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Kairui Song <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Muchun Song <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Wei Xu <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Yu Zhao <[email protected]>
---
 mm/page_counter.c | 21 +++++++++++++++------
 1 file changed, 15 insertions(+), 6 deletions(-)
mm/page_counter.c +15 -6
index 661e0f2a5127a..ea0d1646cff85 100644
@@ -8,6 +8,7 @@
 #include <linux/page_counter.h>
 #include <linux/atomic.h>
 #include <linux/kernel.h>
+#include <linux/math64.h>
 #include <linux/string.h>
 #include <linux/sched.h>
 #include <linux/bug.h>
@@ -356,7 +357,8 @@ static unsigned long effective_protection(unsigned long usage,
 	 * otherwise get a smaller chunk than what they claimed.
 	 */
 	if (siblings_protected > parent_effective)
-		return protected * parent_effective / siblings_protected;
+		return mul_u64_u64_div_u64(protected, parent_effective,
+					   siblings_protected);
 
 	/*
 	 * Ok, utilized protection of all children is within what the
@@ -397,13 +399,20 @@ static unsigned long effective_protection(unsigned long usage,
 	if (parent_effective > siblings_protected &&
 	    parent_usage > siblings_protected &&
 	    usage > protected) {
-		unsigned long unclaimed;
+		unsigned long parent_unclaimed, parent_unprotected, unprotected;
 
-		unclaimed = parent_effective - siblings_protected;
-		unclaimed *= usage - protected;
-		unclaimed /= parent_usage - siblings_protected;
+		parent_unclaimed = parent_effective - siblings_protected;
+		parent_unprotected = parent_usage - siblings_protected;
 
-		ep += unclaimed;
+		/*
+		 * The usages aren't read atomically, so a child can transiently
+		 * appear to use more than its parent, making the ratio exceed 1
+		 * and the quotient overflow 64 bits (#DE on x86).  Cap it.
+		 */
+		unprotected = min(usage - protected, parent_unprotected);
+
+		ep += mul_u64_u64_div_u64(parent_unclaimed, unprotected,
+					  parent_unprotected);
 	}
 
 	return ep;
Signature · 1 line
2.53.0
author maintainer
#586 lore raw

PATCH 583/1257 mm/mglru: fix ineffective memory protection for non-kswapd reclaim

In reply to Greg Kroah-Hartman

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

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

From: Ridong Chen <[email protected]>

[ Upstream commit 15da1e4978dd4ea8f5faa6e15ee967ba4ad9a30a ]

For MGLRU, memory.min/low is not honored during global proactive reclaim (writing to the root memory.reclaim) and global direct reclaim, because these paths shrink memcgs using stale protection (emin/elow). It can be reproduced as follows:

  # echo 7 > /sys/kernel/mm/lru_gen/enabled
  # cd /sys/fs/cgroup
  # mkdir -p a/b
  # echo 100M > a/memory.min
  # echo +memory > a/cgroup.subtree_control
  # echo 100M > a/b/memory.min
  # echo $$ > a/b/cgroup.procs
  # dd if=/dev/zero of=/tmp/testfile bs=1M count=200
  # cat a/b/memory.current
  222650368
  # echo 500M > memory.reclaim
  -bash: echo: write error: Resource temporarily unavailable
  # cat a/b/memory.current
  6070272

memory.min is 100M, yet reclaim drops a/b down to 6M, breaking the protection. The traditional LRU path is not affected because shrink_node() calls mem_cgroup_calculate_protection() for each memcg it visits during a top-down tree walk.

Commit 30d77b7eef01 ("mm/mglru: fix ineffective protection calculation") moved the protection computation into lru_gen_age_node(), which only runs for kswapd. Non-kswapd global reclaim reaches shrink_one() through lru_gen_shrink_node() -> shrink_many() without any protection computation, so emin/elow are whatever a previous kswapd run left behind - or zero if kswapd never ran on this node. Relying on a prior kswapd pass is not correct either: a memcg's emin/elow are derived from its ancestors' memory.min/low settings and from children_min_usage, both of which change over time, so emin/elow go stale even after kswapd has run and must be recomputed at the point of reclaim.

Introduce mem_cgroup_calculate_protection_path() which computes emin/elow along the root-to-target path only, by iterating through the cgroup ancestors array top-down. This avoids the full tree traversal that would be needed with mem_cgroup_calculate_protection(), limiting the cost to O(depth) per memcg - typically 3-5 levels.

Call it from shrink_one() for the non-kswapd path so that each memcg about to be shrunk has correct protection values.

Fixes e4dde56cd208 ("mm: multi-gen LRU: per-node lru_gen_folio lists")
Assisted-by Claude:claude-opus-4-8
Cc Axel Rasmussen <[email protected]>
Cc Chris Down <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Kairui Song <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Muchun Song <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Wei Xu <[email protected]>
Cc Yuanchu Xie <[email protected]>
Cc Yu Zhao <[email protected]>
---
 include/linux/memcontrol.h | 10 +++++++++
 mm/memcontrol.c            | 45 ++++++++++++++++++++++++++++++++++++++
 mm/vmscan.c                |  8 ++++++-
 3 files changed, 62 insertions(+), 1 deletion(-)
include/linux/memcontrol.h +10 -0
index 362af58e50a43..bf057d80e2c6e 100644
@@ -1892,6 +1892,16 @@ static inline bool memcg_is_dying(struct mem_cgroup *memcg)
 }
 #endif /* CONFIG_MEMCG */
 
+#if defined(CONFIG_MEMCG) && defined(CONFIG_LRU_GEN)
+void mem_cgroup_calculate_protection_path(struct mem_cgroup *root,
+					  struct mem_cgroup *memcg);
+#else
+static inline void mem_cgroup_calculate_protection_path(struct mem_cgroup *root,
+							struct mem_cgroup *memcg)
+{
+}
+#endif
+
 #if defined(CONFIG_MEMCG) && defined(CONFIG_ZSWAP)
 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg);
 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size);
mm/memcontrol.c +45 -0

51 lines not on this page · raw message

mm/vmscan.c +7 -1
index 17ab01693ae8d..59f4a805fd53c 100644
@@ -5101,7 +5101,13 @@ static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
 
-	/* lru_gen_age_node() called mem_cgroup_calculate_protection() */
+	/*
+	 * For kswapd, mem_cgroup_calculate_protection() has already
+	 * been called during the top-down cgroup traversal.
+	 */
+	if (!current_is_kswapd())
+		mem_cgroup_calculate_protection_path(NULL, memcg);
+
 	if (mem_cgroup_below_min(NULL, memcg))
 		return MEMCG_LRU_YOUNG;
 
Signature · 1 line
2.53.0
author maintainer
#587 lore raw

PATCH 584/1257 mm/zswap: enable zswap_ever_enabled in zswap_pool_create()

In reply to Greg Kroah-Hartman

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

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

From: Longlong Xia <[email protected]>

[ Upstream commit 91b4edb993e1549afdc3c2495216734b9f13f00e ]

If zswap is enabled by default at boot and pool creation fails, then a pool is later created by updating the compressor, data written to zswap is corrupted on swapin.

Enable the static key in zswap_pool_create(), covering boot-time and runtime pool creation with a single site.

Verified with fault injection on a stock kernel (compressor builtin, CONFIG_ZSWAP_DEFAULT_ON=n):

1. Boot with zswap.enabled=1; pool creation fails, init completes pool-less (static key off).
2. Echo an available compressor name to zswap.compressor.
3. Enable zswap.
4. madvise(MADV_PAGEOUT) a pattern-verified 512 MiB region, then fault it back in and verify.

Step 4 reads back 131072/131072 zeroed pages (zswpin=0, zswpout=131072) without this patch; all pages intact (zswpin=131072) with it.

Fixes 2d4d2b1cfb85 ("mm: zswap: add zswap_never_enabled()")
Assisted-by Zcode:GLM-5.3
Cc Chengming Zhou <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Nhat Pham <[email protected]>
---
 mm/zswap.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/zswap.c +2 -1
index cb5a0855fd2a7..e6e6377a62a0b 100644
@@ -324,6 +324,8 @@ static struct zswap_pool *zswap_pool_create(char *compressor)
 
 	zswap_pool_debug("created", pool);
 
+	static_branch_enable(&zswap_ever_enabled);
+
 	return pool;
 
 ref_fail:
@@ -1805,7 +1807,6 @@ static int zswap_setup(void)
 		pr_info("loaded using pool %s\n", pool->tfm_name);
 		list_add_rcu(&pool->list, &zswap_pools);
 		zswap_has_pool = true;
-		static_branch_enable(&zswap_ever_enabled);
 	} else {
 		pr_err("pool creation failed\n");
 		zswap_enabled = false;
Signature · 1 line
2.53.0
author maintainer
#588 lore raw

PATCH 585/1257 mm/mempolicy: use vm_normal_folio_pmd() in queue_folios_pmd()

In reply to Greg Kroah-Hartman

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

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

From: Gregory Price <[email protected]>

[ Upstream commit 9057170a941f0c5f4058f6fb9ab5d5fc9fcc9e83 ]

Patch series "mm: stop calling pmd_folio() on special PMDs", v3.

Two page table walkers resolve the folio behind a PMD with pmd_folio(), which is only valid for a PMD mapping a refcounted struct page:

madvise_cold_or_pageout_pte_range() mm/madvise.c queue_folios_pmd() mm/mempolicy.c

vmf_insert_pfn_pmd() installs special PMDs holding a raw pfn that need not have a memmap entry at all. Both walkers can reach one and fault on the first folio field read. The PTE halves of both already use vm_normal_folio(); these two patches make the PMD halves match.

The four callers of vmf_insert_pfn_pmd(), and which walker each reaches:

  drivers/vfio/pci/vfio_pci_core.c        VM_PFNMAP     mempolicy
  drivers/gpu/drm/drm_gem_shmem_helper.c  VM_PFNMAP     mempolicy
  drivers/gpu/drm/panthor/panthor_gem.c   VM_PFNMAP     mempolicy
  drivers/hv/mshv_vtl_main.c              VM_MIXEDMAP   both

can_madv_lru_vma() rejects VM_PFNMAP, so only mshv_vtl_low reaches the madvise walker, and that needs CAP_SYS_ADMIN. queue_pages_walk_ops supplies its own ->test_walk, so walk_page_test()'s generic VM_PFNMAP skip never runs and vfio-pci is reachable by any process holding the device fd. Hence the different stable tags.

One behaviour change: mbind(MPOL_MF_STRICT) over a PMD mapped VM_PFNMAP region now returns 0 rather than -EIO. The PTE loop already returned 0 there. drm_gem_shmem and panthor are where this is observable, since they PMD map pages that do have a memmap entry and so never faulted.

Reproducer
==========

No hardware needed. An out of tree module stands in for the drivers
above: three misc devices, each with a ->huge_fault calling vmf_insert_pfn_pmd(), plus VM_HUGEPAGE so the fault path takes the PMD branch.

  /dev/pmdspec_mixed    VM_MIXEDMAP, pfn at the 1 TiB mark, no memmap
  /dev/pmdspec_pfnmap   VM_PFNMAP,   pfn at the 1 TiB mark, no memmap
  /dev/pmdspec_real     VM_PFNMAP,   real alloc_pages(PMD_ORDER) on node 0

Userspace maps the device into a PMD aligned window, reads one byte to fault the PMD in, checks a module parameter to confirm it went in, then issues the operation.

  vng --run <bzImage> --user root --memory 4G --verbose \
      --append "numa=fake=2" \
      --exec "insmod pmdspec.ko && ./pmdspec_test <subtest>"

numa=fake=2 gives a node 1 to bind to; the module allocates its real page on node 0, which is what makes queue_folio_required() true.

subtest operation parent series
--------------------------------------------------------------------

  madv_cold      madvise(MADV_COLD)                     oops     ret=0
  madv_pageout   madvise(MADV_PAGEOUT)                  oops     ret=0
  mbind_mixed    mbind(MPOL_BIND, n1, MPOL_MF_MOVE)     oops     ret=0
  mbind_pfnmap   mbind(MPOL_BIND, n1, MPOL_MF_STRICT)   oops     ret=0
  mbind_real     mbind(MPOL_BIND, n1, MPOL_MF_STRICT)   -EIO     ret=0

Two things the table shows that are easy to miss in the code:

- mbind_mixed passes only MPOL_MF_MOVE. MPOL_MF_STRICT is not needed for a VM_MIXEDMAP vma: walk_page_test() only skips VM_PFNMAP, and vma_migratable() is true for VM_MIXEDMAP.

- mbind_real demonstrates the user visible change (-EIO -> 0)

This patch (of 2):

mmap a VM_PFNMAP region whose ->huge_fault installs a PMD through vmf_insert_pfn_pmd() - a vfio-pci MMIO BAR does this - then

	mbind(p, len, MPOL_BIND, &mask, maxnode, MPOL_MF_STRICT);

With a stand-in module for the driver:

  BUG: unable to handle page fault for address: fffff96dc0000008
  RIP: 0010:queue_folios_pte_range+0xaf/0x440
   walk_pgd_range+0x52b/0xaf0
   __walk_page_range+0x6a/0x1d0
   walk_page_range_mm_unsafe+0x193/0x230
   queue_pages_range+0x64/0xa0
   do_mbind+0x25e/0x640

queue_folios_pmd(), inlined above, calls pmd_folio() on that PMD. The pfn is raw MMIO with no memmap entry, so the folio lands in unpopulated vmemmap. Neither guard stops the walk:

walk_page_test() skips VM_PFNMAP, but queue_pages_walk_ops

                           supplies ->test_walk, so it never runs

queue_pages_test_walk() honours vma_migratable(), but only while
MPOL_MF_STRICT is clear

A VM_MIXEDMAP vma needs neither flag, being vma_migratable(), so plain mbind(MPOL_MF_MOVE) reaches this too - and there the bad folio carries on into migrate_folio_add() and folio_isolate_lru(). mshv_vtl_low is such a mapping.

Use vm_normal_folio_pmd() and skip on NULL, as the PTE loop in queue_folios_pte_range() already does with vm_normal_folio(). This also filters the huge zero PMD, so its separate check is no longer needed.

mbind(MPOL_MF_STRICT) over a PMD mapped VM_PFNMAP region now returns 0 rather than -EIO. The PTE loop already returned 0 there.

---
 mm/mempolicy.c | 13 +++++--------
 1 file changed, 5 insertions(+), 8 deletions(-)
mm/mempolicy.c +5 -8
index 7627d33e509c3..b63d7f410d145 100644
@@ -650,7 +650,8 @@ static inline bool queue_folio_required(struct folio *folio,
 	return node_isset(nid, *qp->nmask) == !(flags & MPOL_MF_INVERT);
 }
 
-static void queue_folios_pmd(pmd_t *pmd, struct mm_walk *walk)
+static void queue_folios_pmd(pmd_t *pmd, unsigned long addr,
+		struct mm_walk *walk)
 {
 	struct folio *folio;
 	struct queue_pages *qp = walk->private;
@@ -661,13 +662,9 @@ static void queue_folios_pmd(pmd_t *pmd, struct mm_walk *walk)
 			qp->nr_failed++;
 		return;
 	}
-	folio = pmd_folio(pmdval);
-	if (folio_is_zone_device(folio))
+	folio = vm_normal_folio_pmd(walk->vma, addr, pmdval);
+	if (!folio || folio_is_zone_device(folio))
 		return;
-	if (is_huge_zero_folio(folio)) {
-		walk->action = ACTION_CONTINUE;
-		return;
-	}
 	if (!queue_folio_required(folio, qp))
 		return;
 	if (!(qp->flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ||
@@ -700,7 +697,7 @@ static int queue_folios_pte_range(pmd_t *pmd, unsigned long addr,
 
 	ptl = pmd_trans_huge_lock(pmd, vma);
 	if (ptl) {
-		queue_folios_pmd(pmd, walk);
+		queue_folios_pmd(pmd, addr, walk);
 		spin_unlock(ptl);
 		goto out;
 	}
Signature · 1 line
2.53.0
author maintainer
#589 lore raw

PATCH 586/1257 mm/madvise: use vm_normal_folio_pmd() in cold/pageout PMD range

In reply to Greg Kroah-Hartman

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

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

From: Gregory Price <[email protected]>

[ Upstream commit 0bd719cb607ef14bcd554e044bbd80dd901b9996 ]

mmap a VM_MIXEDMAP region whose ->huge_fault installs a PMD through vmf_insert_pfn_pmd() - mshv_vtl_low does this, and needs CAP_SYS_ADMIN to open - then:

  madvise(p, PMD_SIZE, MADV_PAGEOUT);

With a stand-in module for the driver:

  BUG: unable to handle page fault for address: fffff587c0000008
  RIP: 0010:madvise_cold_or_pageout_pte_range+0x410/0x9b0
   walk_pgd_range+0x52b/0xaf0
   __walk_page_range+0x6a/0x1d0
   walk_page_range_vma_unsafe+0x8e/0x120
   madvise_pageout+0xb2/0x180
   madvise_vma_behavior+0x46b/0xa90
   do_madvise+0x108/0x190
   __x64_sys_madvise+0x26/0x30

Nothing validates the pfn on the way in:

  can_madv_lru_vma()     rejects VM_PFNMAP, but not VM_MIXEDMAP
  can_fault()            *pfn = vmf->pgoff & ~(mask >> PAGE_SHIFT);
  vmf_insert_pfn_pmd()   no pfn_valid() check
  pmd_folio()            pfn_to_page() -> unpopulated vmemmap

Even with a valid pfn the path is wrong. The mapping carries no rmap, so folio_maybe_mapped_shared() sees mapcount 0, and the walker goes on to folio_deactivate(), or folio_isolate_lru() plus reclaim_pages(), against a folio this mapping does not own.

Use vm_normal_folio_pmd() and skip on NULL, as the PTE half of this same walker already does with vm_normal_folio(). This also filters the huge zero PMD, so its separate check is no longer needed.

---
 mm/madvise.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
mm/madvise.c +3 -4
index 73c2901b9adbf..95287c495e462 100644
@@ -393,16 +393,15 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 			return 0;
 
 		orig_pmd = *pmd;
-		if (is_huge_zero_pmd(orig_pmd))
-			goto huge_unlock;
-
 		if (unlikely(!pmd_present(orig_pmd))) {
 			VM_WARN_ON_ONCE(!pmd_is_migration_entry(orig_pmd) &&
 					!pmd_is_device_private_entry(orig_pmd));
 			goto huge_unlock;
 		}
 
-		folio = pmd_folio(orig_pmd);
+		folio = vm_normal_folio_pmd(vma, addr, orig_pmd);
+		if (!folio)
+			goto huge_unlock;
 
 		if (folio_is_zone_device(folio))
 			goto huge_unlock;
Signature · 1 line
2.53.0
author maintainer
#590 lore raw

PATCH 587/1257 clk: imx: Fix clock reference leak in imx_get_clk_hw_by_name()

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]>

[ Upstream commit 8e177ca735761a1f03e1dedffd7ab00d6d0540ae ]

imx_get_clk_hw_by_name() obtains a consumer clock with of_clk_get_by_name(), extracts the hardware pointer with __clk_get_hw() and returns it without ever calling clk_put(), leaking the consumer reference on both return paths.

Extract the hardware pointer first and drop the clock reference with clk_put() before returning.

Fixes 3b315214e091 ("clk: imx: implement new clk_hw based APIs")
---
 drivers/clk/imx/clk.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/clk/imx/clk.c +5 -1
index f38506830ccf3..e113e30514fa2 100644
@@ -119,12 +119,16 @@ struct clk_hw *imx_obtain_fixed_of_clock(struct device_node *np,
 struct clk_hw *imx_get_clk_hw_by_name(struct device_node *np, const char *name)
 {
 	struct clk *clk;
+	struct clk_hw *hw;
 
 	clk = of_clk_get_by_name(np, name);
 	if (IS_ERR(clk))
 		return ERR_PTR(-ENOENT);
 
-	return __clk_get_hw(clk);
+	hw = __clk_get_hw(clk);
+	clk_put(clk);
+
+	return hw;
 }
 EXPORT_SYMBOL_GPL(imx_get_clk_hw_by_name);
 
Signature · 1 line
2.53.0
author maintainer
#591 lore raw

PATCH 588/1257 clk: imx: Fix clock reference leak in imx_obtain_fixed_clock_hw()

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]>

[ Upstream commit 52d4d1b26a5bc64de95099d0a3dd8b90dba1f3a3 ]

imx_obtain_fixed_clock_hw() obtains the clock through imx_obtain_fixed_clock_from_dt(), which creates a consumer reference via of_clk_get_from_provider(). The reference is discarded right after __clk_get_hw() returns the hardware pointer, leaking it.

Keep the imx_clk_fixed() fallback unchanged and drop the DT-obtained consumer reference with clk_put() once the hardware pointer has been extracted.

Fixes a4a4069f4523 ("clk: imx: Add imx_obtain_fixed_clock clk_hw based variant")
---
 drivers/clk/imx/clk.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/clk/imx/clk.c +7 -2
index e113e30514fa2..49e51e949f71d 100644
@@ -95,11 +95,16 @@ struct clk_hw *imx_obtain_fixed_clock_hw(
 			const char *name, unsigned long rate)
 {
 	struct clk *clk;
+	struct clk_hw *hw;
 
 	clk = imx_obtain_fixed_clock_from_dt(name);
 	if (IS_ERR(clk))
-		clk = imx_clk_fixed(name, rate);
-	return __clk_get_hw(clk);
+		return __clk_get_hw(imx_clk_fixed(name, rate));
+
+	hw = __clk_get_hw(clk);
+	clk_put(clk);
+
+	return hw;
 }
 
 struct clk_hw *imx_obtain_fixed_of_clock(struct device_node *np,
Signature · 1 line
2.53.0
author maintainer
#592 lore raw

PATCH 589/1257 xen/gntdev: prevent private mappings from becoming writable

In reply to Greg Kroah-Hartman

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

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

From: Abdifatah Suruur <[email protected]>

[ Upstream commit 2176dea8d8c19cb43a9b3651bfa1cb21eab1b31a ]

gntdev_mmap() rejects writable private (non-shared) mappings of foreign grant pages, because a private writable mapping takes the COW path on pages that have no proper struct-page backing. However, VM_MAYWRITE is left set, so userspace can map the grant read-only and then upgrade the mapping to writable with mprotect(), hitting the same COW path the check was written to prevent.

Clear VM_MAYWRITE for private mappings, as i915 does for its read-only objects and as fixed in drm/vc4 (CVE-2026-68445) and drm/panthor (CVE-2024-53071) and ptp: vmclock (commit a5edadbae57e2298a56cf7a4e774a027905a331f).

Fixes ab31523c2fcac ("xen/gntdev: allow usermode to map granted pages")

Message-ID: <[email protected]>

---
 drivers/xen/gntdev.c | 7 +++++++
 1 file changed, 7 insertions(+)
drivers/xen/gntdev.c +7 -0
index 1dcc4675580ed..b71f5bae25b63 100644
@@ -1066,6 +1066,13 @@ static int gntdev_mmap(struct file *flip, struct vm_area_struct *vma)
 	if ((vma->vm_flags & VM_WRITE) && !(vma->vm_flags & VM_SHARED))
 		return -EINVAL;
 
+	/*
+	 * Private mappings of foreign grant pages must never become
+	 * writable: they would take the COW path on granted pages.
+	 */
+	if (!(vma->vm_flags & VM_SHARED))
+		vm_flags_clear(vma, VM_MAYWRITE);
+
 	pr_debug("map %d+%d at %lx (pgoff %lx)\n",
 		 index, count, vma->vm_start, vma->vm_pgoff);
 
Signature · 1 line
2.53.0
author maintainer
#593 lore raw

PATCH 590/1257 soc: fsl: cpm1: tsa: Fix clock leak in tsa_of_parse_tdms()

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]>

[ Upstream commit 46201d760c48e771fa2febfcb0787f22c3b71387 ]

The error cleanup loop puts l1rsync_clk and l1rclk_clk a second time and never puts l1tsync_clk or l1tclk_clk, because the branches that guard the transmit clocks use the receive clock field names.

Use the matching field in each branch so every clock acquired by tsa_of_parse_tdms() is released exactly once.

Fixes 1d4ba0b81c1c ("soc: fsl: cpm1: Add support for TSA")
[chleroy: Fixed the same in tsa_remove()]
---
 drivers/soc/fsl/qe/tsa.c | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)
drivers/soc/fsl/qe/tsa.c +8 -8
index 4a88e54d25b94..502e2ffe86898 100644
@@ -865,12 +865,12 @@ static int tsa_of_parse_tdms(struct tsa *tsa, struct device_node *np)
 			clk_put(tsa->tdm[i].l1rclk_clk);
 		}
 		if (tsa->tdm[i].l1tsync_clk) {
-			clk_disable_unprepare(tsa->tdm[i].l1rsync_clk);
-			clk_put(tsa->tdm[i].l1rsync_clk);
+			clk_disable_unprepare(tsa->tdm[i].l1tsync_clk);
+			clk_put(tsa->tdm[i].l1tsync_clk);
 		}
 		if (tsa->tdm[i].l1tclk_clk) {
-			clk_disable_unprepare(tsa->tdm[i].l1rclk_clk);
-			clk_put(tsa->tdm[i].l1rclk_clk);
+			clk_disable_unprepare(tsa->tdm[i].l1tclk_clk);
+			clk_put(tsa->tdm[i].l1tclk_clk);
 		}
 	}
 	return ret;
@@ -1039,12 +1039,12 @@ static void tsa_remove(struct platform_device *pdev)
 			clk_put(tsa->tdm[i].l1rclk_clk);
 		}
 		if (tsa->tdm[i].l1tsync_clk) {
-			clk_disable_unprepare(tsa->tdm[i].l1rsync_clk);
-			clk_put(tsa->tdm[i].l1rsync_clk);
+			clk_disable_unprepare(tsa->tdm[i].l1tsync_clk);
+			clk_put(tsa->tdm[i].l1tsync_clk);
 		}
 		if (tsa->tdm[i].l1tclk_clk) {
-			clk_disable_unprepare(tsa->tdm[i].l1rclk_clk);
-			clk_put(tsa->tdm[i].l1rclk_clk);
+			clk_disable_unprepare(tsa->tdm[i].l1tclk_clk);
+			clk_put(tsa->tdm[i].l1tclk_clk);
 		}
 	}
 }
Signature · 1 line
2.53.0
author maintainer
#594 lore raw

PATCH 591/1257 soc: fsl: dpio: Fix cleanup on IRQ registration failure

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit 45ecea8c55521d424513178fb612cefffb09a9f5 ]

IRQ registration happens after dpaa2_io_create(), but its failure path only releases the IRQ resources and the MC portal. The I/O object stays allocated and published in the service list and per-CPU lookup table, while devres unmaps its portal registers after probe fails.

Call dpaa2_io_down() on IRQ registration failure to remove the object from those lookup structures and free it. Reorder the error labels so that a failed dpaa2_io_create() still skips this cleanup.

Remove unregister_dpio_irq_handlers() from the probe error path, since no IRQ handler or affinity hint has been installed when registration fails.

This issue was identified during our ongoing static-analysis research while reviewing kernel code.

Fixes fe8fe7723a3a ("soc: fsl: dpio: register dpio irq handlers after dpio create")
Assisted-by LLM
---
 drivers/soc/fsl/dpio/dpio-driver.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/soc/fsl/dpio/dpio-driver.c +2 -2
index d5198ffc44550..8d3134622a285 100644
@@ -244,9 +244,9 @@ static int dpaa2_dpio_probe(struct fsl_mc_device *dpio_dev)
 
 	return 0;
 
-err_dpaa2_io_create:
-	unregister_dpio_irq_handlers(dpio_dev);
 err_register_dpio_irq:
+	dpaa2_io_down(priv->io);
+err_dpaa2_io_create:
 	fsl_mc_free_irqs(dpio_dev);
 err_allocate_irqs:
 	dpio_disable(dpio_dev->mc_io, 0, dpio_dev->mc_handle);
Signature · 1 line
2.53.0
author maintainer
#595 lore raw

PATCH 592/1257 soc: fsl: dpio: Free the IRQ before releasing the I/O object

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit a7831c657c90e8f9165f6bbe0cc56262fee075e8 ]

The DPIO interrupt handler accesses priv->io, but dpaa2_dpio_remove() releases that object before tearing down the interrupts. The IRQ was requested with devm_request_irq(), and unregister_dpio_irq_handlers() only clears its affinity hint. fsl_mc_free_irqs() returns IRQ resources to the MC resource pool without freeing the handler. An interrupt can therefore access the freed I/O object before devres releases the IRQ.

Explicitly free the managed IRQ in unregister_dpio_irq_handlers() before returning its resource to the pool, and perform IRQ teardown before releasing the I/O object. This also waits for an in-flight handler while the object is still valid.

This issue was identified during our ongoing static-analysis research while reviewing kernel code.

---
 drivers/soc/fsl/dpio/dpio-driver.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/soc/fsl/dpio/dpio-driver.c +3 -2
index 8d3134622a285..d8f28fb7c37aa 100644
@@ -88,6 +88,7 @@ static void unregister_dpio_irq_handlers(struct fsl_mc_device *dpio_dev)
 
 	/* clear the affinity hint */
 	irq_set_affinity_hint(irq->virq, NULL);
+	devm_free_irq(&dpio_dev->dev, irq->virq, &dpio_dev->dev);
 }
 
 static int register_dpio_irq_handlers(struct fsl_mc_device *dpio_dev, int cpu)
@@ -276,10 +277,10 @@ static void dpaa2_dpio_remove(struct fsl_mc_device *dpio_dev)
 	priv = dev_get_drvdata(dev);
 	cpu = dpaa2_io_get_cpu(priv->io);
 
-	dpaa2_io_down(priv->io);
-
 	dpio_teardown_irqs(dpio_dev);
 
+	dpaa2_io_down(priv->io);
+
 	cpumask_set_cpu(cpu, cpus_unused_mask);
 
 	err = dpio_open(dpio_dev->mc_io, 0, dpio_dev->obj_desc.id,
Signature · 1 line
2.53.0
author maintainer
#596 lore raw

PATCH 593/1257 xen/privcmd: Only claim ioreqs matching an ioeventfd

In reply to Greg Kroah-Hartman

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

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

From: Koichiro Den <[email protected]>

[ Upstream commit 908019e5999161ca89da310c05ddbf7fc89c129e ]

The ioeventfd handler shares its event channel with the userspace device model. It must only claim requests that match a registered ioeventfd. Other requests are left for userspace.

ioeventfd_interrupt() currently marks every MMIO write INPROCESS before looking for a match. For an unmatched request it drops the lock and restores READY. Userspace may see INPROCESS and skip it. Restoring READY does not send another notification. If userspace handles the request at the same time, the READY store may overwrite its state.

Find a matching ioeventfd before changing the request state.

The lock now protects only the ioeventfd list. Use explicit virt_*mb() barriers for the ioreq shared with Xen.

Fixes f0d7db7b3324 ("xen: privcmd: Add support for ioeventfd")

Message-ID: <[email protected]>

---
 drivers/xen/privcmd.c | 47 +++++++++++++++++--------------------------
 1 file changed, 18 insertions(+), 29 deletions(-)
drivers/xen/privcmd.c +18 -29
index 7cfc28f1bb86f..c67ec6d282cf5 100644
@@ -1169,51 +1169,40 @@ static irqreturn_t ioeventfd_interrupt(int irq, void *dev_id)
 	struct privcmd_kernel_ioreq *kioreq = port->kioreq;
 	struct ioreq *ioreq = &kioreq->ioreq[port->vcpu];
 	struct privcmd_kernel_ioeventfd *kioeventfd;
-	unsigned int state = STATE_IOREQ_READY;
+	bool matched = false;
 
-	if (ioreq->state != STATE_IOREQ_READY ||
-	    ioreq->type != IOREQ_TYPE_COPY || ioreq->dir != IOREQ_WRITE)
+	if (ioreq->state != STATE_IOREQ_READY)
 		return IRQ_NONE;
 
-	/*
-	 * We need a barrier, smp_mb(), here to ensure reads are finished before
-	 * `state` is updated. Since the lock implementation ensures that
-	 * appropriate barrier will be added anyway, we can avoid adding
-	 * explicit barrier here.
-	 *
-	 * Ideally we don't need to update `state` within the locks, but we do
-	 * that here to avoid adding explicit barrier.
-	 */
+	/* Xen publishes the request before changing its state to READY. */
+	virt_rmb();
 
-	spin_lock(&kioreq->lock);
-	ioreq->state = STATE_IOREQ_INPROCESS;
+	if (ioreq->type != IOREQ_TYPE_COPY || ioreq->dir != IOREQ_WRITE)
+		return IRQ_NONE;
 
+	spin_lock(&kioreq->lock);
 	list_for_each_entry(kioeventfd, &kioreq->ioeventfds, list) {
 		if (ioreq->addr == kioeventfd->addr + VIRTIO_MMIO_QUEUE_NOTIFY &&
 		    ioreq->size == kioeventfd->addr_len &&
 		    (ioreq->data & QUEUE_NOTIFY_VQ_MASK) == kioeventfd->vq) {
+			/* Finish reading the request before claiming it. */
+			virt_mb();
+			ioreq->state = STATE_IOREQ_INPROCESS;
 			eventfd_signal(kioeventfd->eventfd);
-			state = STATE_IORESP_READY;
+			matched = true;
 			break;
 		}
 	}
 	spin_unlock(&kioreq->lock);
 
-	/*
-	 * We need a barrier, smp_mb(), here to ensure writes are finished
-	 * before `state` is updated. Since the lock implementation ensures that
-	 * appropriate barrier will be added anyway, we can avoid adding
-	 * explicit barrier here.
-	 */
-
-	ioreq->state = state;
-
-	if (state == STATE_IORESP_READY) {
-		notify_remote_via_evtchn(port->port);
-		return IRQ_HANDLED;
-	}
+	if (!matched)
+		return IRQ_NONE;
 
-	return IRQ_NONE;
+	/* Publish the response only after signaling the eventfd. */
+	virt_wmb();
+	ioreq->state = STATE_IORESP_READY;
+	notify_remote_via_evtchn(port->port);
+	return IRQ_HANDLED;
 }
 
 static void ioreq_free(struct privcmd_kernel_ioreq *kioreq)
Signature · 1 line
2.53.0
author maintainer
#597 lore raw

PATCH 594/1257 xen/gntdev: Fix gntdev_dmabuf ref leak in dmabuf_exp_wait_released()

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]>

[ Upstream commit 6f165abe2b40ede71c98956cd74cd17c18505e75 ]

dmabuf_exp_wait_released() takes a reference on the exported gntdev_dmabuf with dmabuf_exp_wait_obj_get_dmabuf() and passes it to dmabuf_exp_wait_obj_new(), which drops that reference after adding the wait object to the wait list. When the wait object allocation fails, dmabuf_exp_wait_obj_new() returns ERR_PTR(-ENOMEM) early and the reference is never dropped, leaking a reference to the exported gntdev_dmabuf.

Drop the reference on the allocation failure path so the reference is consumed whether the wait object is created or not.

Fixes 932d6562179e ("xen/gntdev: Add initial support for dma-buf UAPI")

Message-ID: <[email protected]>

---
 drivers/xen/gntdev-dmabuf.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/xen/gntdev-dmabuf.c +3 -1
index 83b0df4608941..df1883aca850e 100644
@@ -96,8 +96,10 @@ dmabuf_exp_wait_obj_new(struct gntdev_dmabuf_priv *priv,
 	struct gntdev_dmabuf_wait_obj *obj;
 
 	obj = kzalloc_obj(*obj);
-	if (!obj)
+	if (!obj) {
+		kref_put(&gntdev_dmabuf->u.exp.refcount, dmabuf_exp_release);
 		return ERR_PTR(-ENOMEM);
+	}
 
 	init_completion(&obj->completion);
 	obj->gntdev_dmabuf = gntdev_dmabuf;
Signature · 1 line
2.53.0
author maintainer
#598 lore raw

PATCH 595/1257 xen/pcifront: check that an AER callback exists before calling it

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]>

[ Upstream commit 3b4854b69ee70fffb2fa7acac09e715a7efcbae1 ]

pcifront_common_process() handles an AER request from the backend by dispatching on aer_op.cmd to the bound driver's PCI error handler. It only checks that err_handler and err_handler->error_detected are present, then for the mmio_enabled, slot_reset and resume commands it calls the corresponding callback unconditionally. Those three callbacks are optional -- the PCI core NULL-checks each of them individually before use -- and many drivers (for example igb, igc, ice and ixgbevf) install error_detected without all of them.

aer_op.cmd comes from the shared ring, so a malicious or buggy backend can send XEN_PCI_OP_aer_mmio (or _slotreset/_resume) for a device whose driver leaves that callback NULL and make the frontend call through a NULL pointer, crashing the guest.

Check each callback before calling it. When mmio_enabled or slot_reset is absent, return PCI_ERS_RESULT_RECOVERED so recovery proceeds, as the PCI core does for a missing callback; returning PCI_ERS_RESULT_NONE would instead make xen-pciback tear the guest domain down.

Fixes 956a9202cd12 ("xen-pcifront: Xen PCI frontend driver.")

Message-ID: <[email protected]>

---
 drivers/pci/xen-pcifront.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
drivers/pci/xen-pcifront.c +8 -3
index cffc32d660327..5c6f7796d204a 100644
@@ -599,11 +599,16 @@ static pci_ers_result_t pcifront_common_process(int cmd,
 		case XEN_PCI_OP_aer_detected:
 			return pdrv->err_handler->error_detected(pcidev, state);
 		case XEN_PCI_OP_aer_mmio:
-			return pdrv->err_handler->mmio_enabled(pcidev);
+			if (pdrv->err_handler->mmio_enabled)
+				return pdrv->err_handler->mmio_enabled(pcidev);
+			return PCI_ERS_RESULT_RECOVERED;
 		case XEN_PCI_OP_aer_slotreset:
-			return pdrv->err_handler->slot_reset(pcidev);
+			if (pdrv->err_handler->slot_reset)
+				return pdrv->err_handler->slot_reset(pcidev);
+			return PCI_ERS_RESULT_RECOVERED;
 		case XEN_PCI_OP_aer_resume:
-			pdrv->err_handler->resume(pcidev);
+			if (pdrv->err_handler->resume)
+				pdrv->err_handler->resume(pcidev);
 			return PCI_ERS_RESULT_NONE;
 		default:
 			dev_err(&pdev->xdev->dev,
Signature · 1 line
2.53.0
author maintainer
#599 lore raw

PATCH 596/1257 xen-pciback: Fix pcistub_device ref leak in pcistub_get_gsi_from_sbdf()

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]>

[ Upstream commit cfaf31becde901f7a2376d36db628f8be0bc7283 ]

pcistub_get_gsi_from_sbdf() obtains the stub device with pcistub_device_find(), which returns it with its kref incremented, and returns psdev->gsi without dropping that reference again. The caller cannot release it either, so every lookup leaks one reference to the stub device.

Release the reference after reading gsi.

Fixes 2fae6bb7be32 ("xen/privcmd: Add new syscall to get gsi from dev")

Message-ID: <[email protected]>

---
 drivers/xen/xen-pciback/pci_stub.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/xen/xen-pciback/pci_stub.c +5 -2
index 79a2b5dfd6941..d1a335233aab0 100644
@@ -234,13 +234,16 @@ static int pcistub_get_gsi_from_sbdf(unsigned int sbdf)
 	int bus = PCI_BUS_NUM(sbdf);
 	int slot = PCI_SLOT(sbdf);
 	int func = PCI_FUNC(sbdf);
+	int gsi;
 
 	psdev = pcistub_device_find(domain, bus, slot, func);
-
 	if (!psdev)
 		return -ENODEV;
 
-	return psdev->gsi;
+	gsi = psdev->gsi;
+	pcistub_device_put(psdev);
+
+	return gsi;
 }
 #endif
 
Signature · 1 line
2.53.0
author maintainer
#600 lore raw

PATCH 597/1257 iommu/dma: Catch scatterlist length overflows

In reply to Greg Kroah-Hartman

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

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

From: Krzysztof Karas <[email protected]>

[ Upstream commit 1c8f6308e557f32412e9d4678b3f029f47f6d9aa ]

It is possible, when a very large mapping uses only one scatterlist, that padding overflows scatterlist's length field. This results in:
1) silently wrapping the value
2) smaller than desired mappings produced by iommu_map_sg
3) leaving mapped bytes in memory (no iommu_unmap)

Address this issue by adding overflow detection for scatterlist length field.

Fixes 809eac54cdd6 ("iommu/dma: Implement scatterlist segment merging")
Assisted-by LLM
---
 drivers/iommu/dma-iommu.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
drivers/iommu/dma-iommu.c +19 -1
index 68ee57800fefc..795a0d6248ceb 100644
@@ -1477,6 +1477,11 @@ int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
 		sg_dma_len(s) = s_length;
 		s->offset -= s_iova_off;
 		s_length = iova_align(iovad, s_length + s_iova_off);
+		if (overflows_type(s_length, s->length)) {
+			ret = -EOVERFLOW;
+
+			goto out_restore_sg;
+		}
 		s->length = s_length;
 
 		/*
@@ -1493,7 +1498,20 @@ int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
 		 *   time through here (i.e. before it has a meaningful value).
 		 */
 		if (pad_len && pad_len < s_length - 1) {
-			prev->length += pad_len;
+			unsigned int new_prev_len;
+
+			/*
+			 * For large mappings spanning multiple GBs we
+			 * may not be able to fit all needed padding into
+			 * sg->length.
+			 */
+			if (check_add_overflow(prev->length, pad_len, &new_prev_len)) {
+				ret = -EOVERFLOW;
+
+				goto out_restore_sg;
+			}
+
+			prev->length = new_prev_len;
 			iova_len += pad_len;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#601 lore raw

PATCH 598/1257 drm/ttm: return an error when kmapping a BO without pages

In reply to Greg Kroah-Hartman

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

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

From: Jesse Zhang <[email protected]>

[ Upstream commit fd485d47437ba1700dd47205a63b9f389a00aa36 ]

ttm_tt objects for imported sg tables (ttm_bo_type_sg, set up by ttm_sg_tt_init() with TTM_TT_FLAG_EXTERNAL) only have DMA addresses and no pages array. ttm_bo_kmap() and ttm_bo_vmap() still dereference ttm->pages for them, so a driver that tries to CPU map such a BO oopses instead of getting an error:

  BUG: kernel NULL pointer dereference, address: 0000000000000000
  RIP: 0010:ttm_bo_kmap+0x26c/0x300 [ttm]
  Call Trace:
   amdgpu_bo_kmap+0x89/0xb0 [amdgpu]
   amdgpu_userq_fence_read_wptr+0x116/0x170 [amdgpu]
   amdgpu_userq_signal_ioctl+0x3fe/0xbb0 [amdgpu]

Return -EINVAL in that case, like ttm_bo_kmap_try_from_panic() already checks for a missing pages array.

---
 drivers/gpu/drm/ttm/ttm_bo_util.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/gpu/drm/ttm/ttm_bo_util.c +9 -2
index bd0b23ac2cc4b..f9458a4d5a09d 100644
@@ -356,6 +356,10 @@ static int ttm_bo_kmap_ttm(struct ttm_buffer_object *bo,
 	if (ret)
 		return ret;
 
+	/* Imported sg tables only come with DMA addresses, no pages to map. */
+	if (!ttm->pages)
+		return -EINVAL;
+
 	if (num_pages == 1 && ttm->caching == ttm_cached &&
 	    !(man->use_tt && (ttm->page_flags & TTM_TT_FLAG_DECRYPTED))) {
 		/*
@@ -419,7 +423,7 @@ EXPORT_SYMBOL(ttm_bo_kmap_try_from_panic);
  *
  * Returns
  * -ENOMEM: Out of memory.
- * -EINVAL: Invalid range.
+ * -EINVAL: Invalid range or the BO has no pages to map.
  */
 int ttm_bo_kmap(struct ttm_buffer_object *bo,
 		unsigned long start_page, unsigned long num_pages,
@@ -493,7 +497,7 @@ EXPORT_SYMBOL(ttm_bo_kunmap);
  *
  * Returns
  * -ENOMEM: Out of memory.
- * -EINVAL: Invalid range.
+ * -EINVAL: Invalid range or the BO has no pages to map.
  */
 int ttm_bo_vmap(struct ttm_buffer_object *bo, struct iosys_map *map)
 {
@@ -537,6 +541,9 @@ int ttm_bo_vmap(struct ttm_buffer_object *bo, struct iosys_map *map)
 		if (ret)
 			return ret;
 
+		if (!ttm->pages)
+			return -EINVAL;
+
 		/*
 		 * We need to use vmap to get the desired page protection
 		 * or to make the buffer object look contiguous.
Signature · 1 line
2.53.0
author maintainer
#602 lore raw

PATCH 599/1257 ALSA: usb-audio: Add mic resolution quirk for Logitech Webcam C200

In reply to Greg Kroah-Hartman

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

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

From: Olivier Kaloudoff <[email protected]>

[ Upstream commit 874323b68c93c6808e034dc0113681e822e6fb42 ]

The C200 (046d:0802) reports a mic capture volume range of 1536..7680 with a resolution of 1 (6144 steps), triggering "Warning! Unlikely big volume step count (=6144), linear volume or wrong cval->res?" at probe and exposing a uselessly fine-grained mixer control. This is the same firmware behavior as the other UVC-era Logitech webcams already carrying QUIRK_FLAG_MIC_RES_384 (C500, C600, C210, C270, C310, C510, C525, ...), so apply the same
quirk: CTL_MSG_DELAY_1M (which the Logitech VENDOR_FLG would provide if the device-specific entry did not short-circuit the lookup) plus MIC_RES_384.

Verified on real hardware: with the quirk the warning disappears and the driver logs "set resolution quirk: cval->res = 384".

---
 sound/usb/quirks.c | 2 ++
 1 file changed, 2 insertions(+)
sound/usb/quirks.c +2 -0
index a54fabce7920d..b9e89e94e95f5 100644
@@ -2251,6 +2251,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = {
 		   QUIRK_FLAG_DISABLE_AUTOSUSPEND),
 	DEVICE_FLG(0x045e, 0x070f, /* MS LifeChat LX-3000 Headset */
 		   QUIRK_FLAG_MIXER_PLAYBACK_MIN_MUTE),
+	DEVICE_FLG(0x046d, 0x0802, /* Logitech Webcam C200 */
+		   QUIRK_FLAG_CTL_MSG_DELAY_1M | QUIRK_FLAG_MIC_RES_384),
 	DEVICE_FLG(0x046d, 0x0807, /* Logitech Webcam C500 */
 		   QUIRK_FLAG_CTL_MSG_DELAY_1M | QUIRK_FLAG_MIC_RES_384),
 	DEVICE_FLG(0x046d, 0x0808, /* Logitech Webcam C600 */
Signature · 1 line
2.53.0
author maintainer
#603 lore raw

PATCH 600/1257 wifi: ath12k: validate MAC/PHY capability count before saving

In reply to Greg Kroah-Hartman

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

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

From: Jiale Yao <[email protected]>

[ Upstream commit 86f2537877d6029487811bc3e0cd9e086a196000 ]

Firmware supplies the hardware mode count and the PHY bitmap for each mode in the service-ready-ext event. ath12k_wmi_save_all_mac_phy_info() uses those bitmaps to populate svc_ext_info->mac_phy_info, but the destination is a fixed array of ATH12K_MAX_MAC_PHY_CAP elements.

If the total number of advertised PHY entries exceeds that limit, the loop writes beyond mac_phy_info and corrupts adjacent memory.

ath12k_wmi_mac_phy_caps_parse() allocates the source array for tot_phy_id entries and rejects excess capability TLVs. However, if the event contains fewer capability TLVs than advertised, the remaining allocated entries stay zeroed and are saved as invalid PHY information.

After parsing the MAC/PHY capability TLVs, validate the destination capacity and reject an incomplete capability list before saving any entries.

Fixes 062ade23991e ("wifi: ath12k: parse and save hardware mode info from WMI_SERVICE_READY_EXT_EVENTID event for later use")
---
 drivers/net/wireless/ath/ath12k/wmi.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
drivers/net/wireless/ath/ath12k/wmi.c +17 -0
index d5160af60e00d..3e812c79a649d 100644
@@ -5050,6 +5050,7 @@ static int ath12k_wmi_svc_rdy_ext_parse(struct ath12k_base *ab,
 					u16 tag, u16 len,
 					const void *ptr, void *data)
 {
+	struct ath12k_svc_ext_info *svc_ext_info = &ab->wmi_ab.svc_ext_info;
 	struct ath12k_wmi_pdev *wmi_handle = &ab->wmi_ab.wmi[0];
 	struct ath12k_wmi_svc_rdy_ext_parse *svc_rdy_ext = data;
 	int ret;
@@ -5094,6 +5095,22 @@ static int ath12k_wmi_svc_rdy_ext_parse(struct ath12k_base *ab,
 				return ret;
 			}
 
+			if (svc_rdy_ext->tot_phy_id >
+			    ARRAY_SIZE(svc_ext_info->mac_phy_info)) {
+				ath12k_warn(ab, "too many PHY entries %u (max %zu)\n",
+					    svc_rdy_ext->tot_phy_id,
+					    ARRAY_SIZE(svc_ext_info->mac_phy_info));
+				return -EINVAL;
+			}
+
+			if (svc_rdy_ext->n_mac_phy_caps < svc_rdy_ext->tot_phy_id) {
+				ath12k_warn(ab,
+					    "not enough MAC/PHY caps %u, expected %u\n",
+					    svc_rdy_ext->n_mac_phy_caps,
+					    svc_rdy_ext->tot_phy_id);
+				return -EINVAL;
+			}
+
 			ath12k_wmi_save_all_mac_phy_info(ab, svc_rdy_ext);
 
 			svc_rdy_ext->mac_phy_done = true;
Signature · 1 line
2.53.0
author maintainer
#604 lore raw

PATCH 601/1257 USB: cdc-acm: fix urb leak on disconnect

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

[ Upstream commit 648b08aa37c1b24a61662ad78964f2bca659ca26 ]

Make sure to drop the reference taken by usb_anchor_urb() when removing URBs from the delayed URB anchor to prevent them from leaking when the device is later disconnected.

---
 drivers/usb/class/cdc-acm.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/usb/class/cdc-acm.c +2 -1
index 0d3f815b2f1e8..6a1c574634949 100644
@@ -782,6 +782,7 @@ static void acm_port_shutdown(struct tty_port *port)
 		urb = usb_get_from_anchor(&acm->delayed);
 		if (!urb)
 			break;
+		usb_put_urb(urb);
 		wb = urb->context;
 		wb->use = false;
 		usb_autopm_put_interface_async(acm->control);
@@ -1710,7 +1711,7 @@ static int acm_resume(struct usb_interface *intf)
 			urb = usb_get_from_anchor(&acm->delayed);
 			if (!urb)
 				break;
-
+			usb_put_urb(urb);
 			acm_start_wb(acm, urb->context);
 		}
 
Signature · 1 line
2.53.0
author maintainer
#605 lore raw

PATCH 602/1257 USB: serial: option: add Rolling Wireless RN947R

In reply to Greg Kroah-Hartman

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

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

From: Reinhard Speyerer <[email protected]>

[ Upstream commit 931aad81f3f2d26276fff6b7bda6793267a65725 ]

Add Rolling Wireless RN947R 0x9300 compositions:

Standard mode: DIAG + ADB + NMEA + MODEM + RMNET + QDSS + ADPL

T:  Bus=01 Lev=01 Prnt=01 Port=02 Cnt=02 Dev#=  6 Spd=480  MxCh= 0
D:  Ver= 2.10 Cls=ef(misc ) Sub=02 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=33f8 ProdID=9300 Rev= 0.00
S:  Manufacturer=Rolling Wireless
S:  Product=RN947R
S:  SerialNumber=xxxxxxxxxxx
C:* #Ifs= 7 Cfg#= 1 Atr=a0 MxPwr=500mA
I:* If#= 0 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=ff Prot=30 Driver=option
E:  Ad=01(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=81(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#= 1 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=42 Prot=01 Driver=usbfs
E:  Ad=02(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=82(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#= 2 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=ff Prot=40 Driver=option
E:  Ad=84(I) Atr=03(Int.) MxPS=  10 Ivl=32ms
E:  Ad=83(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=03(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#= 3 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=ff Prot=40 Driver=option
E:  Ad=86(I) Atr=03(Int.) MxPS=  10 Ivl=32ms
E:  Ad=85(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=04(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#= 8 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=ff Prot=50 Driver=qmi_wwan
E:  Ad=88(I) Atr=03(Int.) MxPS=   8 Ivl=32ms
E:  Ad=87(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=05(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms

I:* If#=21 Alt= 0 #EPs= 1 Cls=ff(vend.) Sub=ff Prot=70 Driver=(none)
E: Ad=89(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#=22 Alt= 0 #EPs= 1 Cls=ff(vend.) Sub=ff Prot=80 Driver=(none)
E: Ad=8a(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms

QDL mode:

T:  Bus=01 Lev=01 Prnt=01 Port=02 Cnt=02 Dev#= 12 Spd=480  MxCh= 0
D:  Ver= 2.10 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=33f8 ProdID=9300 Rev= 0.00
S:  Manufacturer=Rolling Wireless
S:  Product=RN947R
S:  SerialNumber=xxxxxxxxxxx
C:* #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=  2mA
I:* If#= 0 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=ff Prot=10 Driver=option
E:  Ad=81(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=01(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
---
 drivers/usb/serial/option.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/usb/serial/option.c +4 -0
index 828b1be3fee2d..dc8f459ca3995 100644
@@ -2510,6 +2510,10 @@ static const struct usb_device_id option_ids[] = {
 	  .driver_info = RSVD(5) },
 	{ USB_DEVICE_INTERFACE_CLASS(0x33f8, 0x1003, 0xff),			/* Rolling RW135R-GL (laptop MBIM) */
 	  .driver_info = RSVD(5) },
+	{ USB_DEVICE_AND_INTERFACE_INFO(0x33f8, 0x9300, 0xff, 0xff, 0x30) },	/* Rolling RN947R */
+	{ USB_DEVICE_AND_INTERFACE_INFO(0x33f8, 0x9300, 0xff, 0xff, 0x40) },
+	{ USB_DEVICE_AND_INTERFACE_INFO(0x33f8, 0x9300, 0xff, 0xff, 0x10),
+	  .driver_info = ZLP },
 	{ USB_DEVICE_INTERFACE_CLASS(0x3466, 0x3301, 0xff) },			/* TDTECH MT5710-CN */
 	{ USB_DEVICE_AND_INTERFACE_INFO(0x3731, 0x0100, 0xff, 0xff, 0x30) },	/* NetPrisma LCUK54-WWD for Global */
 	{ USB_DEVICE_AND_INTERFACE_INFO(0x3731, 0x0100, 0xff, 0x00, 0x40) },
Signature · 1 line
2.53.0
author maintainer
#606 lore raw

PATCH 603/1257 USB: serial: option: add support for ASR 1286:4e3c modem

In reply to Greg Kroah-Hartman

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

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

From: Michael Wyraz <[email protected]>

[ Upstream commit 87c56085bcdfec305f5c350fe1c58a62a7f65843 ]

The ASR modem used in the Tuoshi LT22M exposes an RNDIS function on interfaces 0 and 1, a diagnostic port on interface 2, and AT ports on interfaces 3 and 4. Match only the vendor-specific serial interfaces so option does not bind to the RNDIS function.

---
 drivers/usb/serial/option.c | 1 +
 1 file changed, 1 insertion(+)
drivers/usb/serial/option.c +1 -0
index dc8f459ca3995..65506f6e1502e 100644
@@ -2443,6 +2443,7 @@ static const struct usb_device_id option_ids[] = {
 	{ USB_DEVICE_AND_INTERFACE_INFO(0x04b7, 0x8217, 0xff, 0xff, 0x30) },	/* Compal EXM-G1x */
 	{ USB_DEVICE_AND_INTERFACE_INFO(0x04b7, 0x8217, 0xff, 0xff, 0x40) },
 	{ USB_DEVICE_AND_INTERFACE_INFO(0x04b7, 0x8217, 0xff, 0xff, 0x60) },
+	{ USB_DEVICE_INTERFACE_CLASS(0x1286, 0x4e3c, 0xff) },			/* ASR modem */
 	{ USB_DEVICE(0x1508, 0x1001),						/* Fibocom NL668 (IOT version) */
 	  .driver_info = RSVD(4) | RSVD(5) | RSVD(6) },
 	{ USB_DEVICE(0x1782, 0x4d10) },						/* Fibocom L610 (AT mode) */
Signature · 1 line
2.53.0
author maintainer
#607 lore raw

PATCH 604/1257 USB: serial: usb_wwan: fix urb leak on disconnect

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

[ Upstream commit c78dd373b5c56a5a02da591b583c6b48d0d62954 ]

Make sure to drop the reference taken by usb_anchor_urb() when removing URBs from the delayed URB anchor to prevent them from leaking when the device is later disconnected.

Fixes 383cedc3bb43 ("USB: serial: full autosuspend support for the option driver")
Cc [email protected] # 2.6.32
Cc Oliver Neukum <[email protected]>
---
 drivers/usb/serial/usb_wwan.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/usb/serial/usb_wwan.c +3 -0
index a183cc4515edb..6beb4062bda3a 100644
@@ -401,6 +401,7 @@ void usb_wwan_close(struct usb_serial_port *port)
 		urb = usb_get_from_anchor(&portdata->delayed);
 		if (!urb)
 			break;
+		usb_put_urb(urb);
 		unbusy_queued_urb(urb, portdata);
 		usb_autopm_put_interface_async(serial->interface);
 	}
@@ -578,6 +579,8 @@ static int usb_wwan_submit_delayed_urbs(struct usb_serial_port *port)
 		if (!urb)
 			break;
 
+		usb_put_urb(urb);
+
 		err = usb_submit_urb(urb, GFP_ATOMIC);
 		if (err) {
 			dev_err(&port->dev, "%s: submit urb failed: %d\n",
Signature · 1 line
2.53.0
author maintainer
#608 lore raw

PATCH 605/1257 misc: fastrpc: fix double-free in fastrpc_map_attach() error path

In reply to Greg Kroah-Hartman

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

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

From: Yifei Gao <[email protected]>

[ Upstream commit 09fa66ec1b4896ab841da085ca58b6433f28f07f ]

map->table is assigned right after dma_buf_map_attachment_unlocked() succeeds. The two failure checks that follow, the len > map->size test and, where subsystem VMIDs are configured, a failed qcom_scm_assign_mem(), jump to map_err with map->table already set.

map_err manually calls dma_buf_detach() and dma_buf_put() and then falls through to fastrpc_map_put(). Since that change the error path tail is fastrpc_map_put() -> fastrpc_free_map(), and fastrpc_free_map() already unmaps, detaches and puts the dma-buf whenever map->table is set. The two operations therefore run twice: the second dma_buf_put() drops an extra reference on map->buf, and dma_buf_unmap_attachment_unlocked() dereferences the map->attach already freed by the manual dma_buf_detach(). kref_init() sets the refcount to 1 with no intervening get, so the final fastrpc_map_put() frees the map synchronously and the redundant cleanup is deterministic.

The len > map->size branch is reachable by an unprivileged process via FASTRPC_IOCTL_MEM_MAP with an fd whose dma-buf is smaller than the requested length, before any DSP invocation.

Route both map->table-is-set failure branches to get_err instead of map_err, so fastrpc_free_map() is the single owner of the unmap/detach/put sequence. map_err is retained for the dma_buf_map_attachment_unlocked() failure, which is reached with map->table still NULL and an attachment that fastrpc_free_map() will not clean up, so its dma_buf_detach()/dma_buf_put() must still run manually.

Fixes 334f1a1cbe03 ("misc: fastrpc: Use fastrpc_map_put in fastrpc_map_create on fail")
Assisted-by Claude:claude-opus-4-8
---
 drivers/misc/fastrpc.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/misc/fastrpc.c +2 -2
index d4fac2caca867..b35751212095d 100644
@@ -927,7 +927,7 @@ static int fastrpc_map_attach(struct fastrpc_user *fl, int fd,
 		dev_dbg(sess->dev, "Bad size passed len 0x%llx map size 0x%llx\n",
 				len, map->size);
 		err = -EINVAL;
-		goto map_err;
+		goto get_err;
 	}
 	map->va = sg_virt(map->table->sgl);
 	map->len = len;
@@ -950,7 +950,7 @@ static int fastrpc_map_attach(struct fastrpc_user *fl, int fd,
 			dev_err(sess->dev,
 				"Failed to assign memory with dma_addr %pad size 0x%llx err %d\n",
 				&map->dma_addr, map->len, err);
-			goto map_err;
+			goto get_err;
 		}
 	}
 	spin_lock(&fl->lock);
Signature · 1 line
2.53.0
author maintainer
#609 lore raw

PATCH 606/1257 misc: fastrpc: Allocate entire reserved memory for Audio PD in probe

In reply to Greg Kroah-Hartman

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

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

From: Jianping Li <[email protected]>

[ Upstream commit 9e47ad9c562e82cabfbb9afa6c2b0dcdf2702a39 ]

Allocating and freeing Audio PD memory from userspace is unsafe because the kernel cannot reliably determine when the DSP has finished using the memory. Userspace may free buffers while they are still in use by the DSP, and remote free requests cannot be safely trusted.

Additionally, the current implementation allows userspace to repeatedly grow the Audio PD heap, but does not support shrinking it. This can lead to unbounded memory usage over time, effectively causing a memory leak.

Fix this by allocating the entire Audio PD reserved-memory region during rpmsg probe and tying its lifetime to the rpmsg channel. This removes userspace-controlled alloc/free and ensures that memory is reclaimed only when the DSP process is torn down.

The reserved-memory region is now mandatory for the Audio PD domain. Rather than failing rpmsg probe when it is missing, validate it in fastrpc_init_create_static_process() and reject only the static-process creation. This keeps the fastrpc device probing for all other domains even on a misconfigured device tree.

---
 drivers/misc/fastrpc.c | 188 ++++++++++++++++++++++-------------------
 1 file changed, 101 insertions(+), 87 deletions(-)
drivers/misc/fastrpc.c +101 -87
index b35751212095d..adc6f850e7536 100644
@@ -70,8 +70,6 @@
 #define ADSP_MMAP_HEAP_ADDR  4
 /* MAP static DMA buffer on DSP User PD */
 #define ADSP_MMAP_DMA_BUFFER  6
-/* Add memory to static PD pool protection thru hypervisor */
-#define ADSP_MMAP_REMOTE_HEAP_ADDR  8
 /* Add memory to userPD pool, for user heap */
 #define ADSP_MMAP_ADD_PAGES 0x1000
 /* Add memory to userPD pool, for LLC heap */
@@ -314,10 +312,14 @@ struct fastrpc_channel_ctx {
 	struct kref refcount;
 	/* Flag if dsp attributes are cached */
 	bool valid_attributes;
+	/* Flag if audio PD init mem was allocated */
+	bool audio_init_mem;
+	/* Audio PD reserved remote heap region */
+	phys_addr_t remote_heap_addr;
+	u64 remote_heap_size;
 	u32 dsp_attributes[FASTRPC_MAX_DSP_ATTRIBUTES];
 	struct fastrpc_device *secure_fdevice;
 	struct fastrpc_device *fdevice;
-	struct fastrpc_buf *remote_heap;
 	struct list_head invoke_interrupted_mmaps;
 	bool secure;
 	bool unsigned_support;
@@ -1454,15 +1456,24 @@ static int fastrpc_init_create_static_process(struct fastrpc_user *fl,
 	struct fastrpc_init_create_static init;
 	struct fastrpc_invoke_args *args;
 	struct fastrpc_phy_page pages[1];
+	struct fastrpc_channel_ctx *cctx = fl->cctx;
 	char *name;
 	int err;
-	bool scm_done = false;
 	struct {
 		int client_id;
 		u32 namelen;
 		u32 pageslen;
 	} inbuf;
 	u32 sc;
+	unsigned long flags;
+	bool sent_heap = false;
+
+	if (!cctx->remote_heap_addr || !cctx->remote_heap_size) {
+		err = -ENOMEM;
+		dev_err(fl->sctx->dev,
+			"remote heap memory region is not added\n");
+		return err;
+	}
 
 	args = kzalloc_objs(*args, FASTRPC_CREATE_STATIC_PROCESS_NARGS);
 	if (!args)
@@ -1486,31 +1497,6 @@ static int fastrpc_init_create_static_process(struct fastrpc_user *fl,
 	inbuf.client_id = fl->client_id;
 	inbuf.namelen = init.namelen;
 	inbuf.pageslen = 0;
-	if (!fl->cctx->remote_heap) {
-		err = fastrpc_remote_heap_alloc(fl, fl->sctx->dev, init.memlen,
-						&fl->cctx->remote_heap);
-		if (err)
-			goto err_name;
-
-		/* Map if we have any heap VMIDs associated with this ADSP Static Process. */
-		if (fl->cctx->vmcount) {
-			u64 src_perms = BIT(QCOM_SCM_VMID_HLOS);
-
-			err = qcom_scm_assign_mem(fl->cctx->remote_heap->dma_addr,
-							(u64)fl->cctx->remote_heap->size,
-							&src_perms,
-							fl->cctx->vmperms, fl->cctx->vmcount);
-			if (err) {
-				dev_err(fl->sctx->dev,
-					"Failed to assign memory with dma_addr %pad size 0x%llx err %d\n",
-					&fl->cctx->remote_heap->dma_addr,
-					fl->cctx->remote_heap->size, err);
-				goto err_map;
-			}
-			scm_done = true;
-			inbuf.pageslen = 1;
-		}
-	}
 
 	fl->pd = USER_PD;
 
@@ -1522,8 +1508,25 @@ static int fastrpc_init_create_static_process(struct fastrpc_user *fl,
 	args[1].length = inbuf.namelen;
 	args[1].fd = -1;
 
-	pages[0].addr = fl->cctx->remote_heap->dma_addr;
-	pages[0].size = fl->cctx->remote_heap->size;
+	/*
+	 * Audio PD is a static PD and retains the remote heap
+	 * information across daemon restarts. Therefore only
+	 * the first attach should provide heap information to
+	 * DSP. Subsequent attaches reuse the previously
+	 * initialized memory pool.
+	 */
+	spin_lock_irqsave(&cctx->lock, flags);
+	if (!cctx->audio_init_mem) {
+		pages[0].addr = cctx->remote_heap_addr;
+		pages[0].size = cctx->remote_heap_size;
+		cctx->audio_init_mem = true;
+		inbuf.pageslen = 1;
+		sent_heap = true;
+	} else {
+		pages[0].addr = 0;
+		pages[0].size = 0;
+	}
+	spin_unlock_irqrestore(&cctx->lock, flags);
 
 	args[2].ptr = (u64)(uintptr_t) pages;
 	args[2].length = sizeof(*pages);
@@ -1541,27 +1544,11 @@ static int fastrpc_init_create_static_process(struct fastrpc_user *fl,
 
 	return 0;
 err_invoke:
-	if (fl->cctx->vmcount && scm_done) {
-		u64 src_perms = 0;
-		struct qcom_scm_vmperm dst_perms;
-		u32 i;
-
-		for (i = 0; i < fl->cctx->vmcount; i++)
-			src_perms |= BIT(fl->cctx->vmperms[i].vmid);
-
-		dst_perms.vmid = QCOM_SCM_VMID_HLOS;
-		dst_perms.perm = QCOM_SCM_PERM_RWX;
-		err = qcom_scm_assign_mem(fl->cctx->remote_heap->dma_addr,
-						(u64)fl->cctx->remote_heap->size,
-						&src_perms, &dst_perms, 1);
-		if (err)
-			dev_err(fl->sctx->dev, "Failed to assign memory dma_addr %pad size 0x%llx err %d\n",
-				&fl->cctx->remote_heap->dma_addr, fl->cctx->remote_heap->size, err);
+	if (sent_heap) {
+		spin_lock_irqsave(&cctx->lock, flags);
+		cctx->audio_init_mem = false;
+		spin_unlock_irqrestore(&cctx->lock, flags);
 	}
-err_map:
-	fastrpc_buf_free(fl->cctx->remote_heap);
-	fl->cctx->remote_heap = NULL;
-err_name:
 	kfree(name);
 err:
 	kfree(args);
@@ -2086,7 +2073,7 @@ static int fastrpc_req_mmap(struct fastrpc_user *fl, char __user *argp)
 	if (copy_from_user(&req, argp, sizeof(req)))
 		return -EFAULT;
 
-	if (req.flags != ADSP_MMAP_ADD_PAGES && req.flags != ADSP_MMAP_REMOTE_HEAP_ADDR) {
+	if (req.flags != ADSP_MMAP_ADD_PAGES) {
 		dev_err(dev, "flag not supported 0x%x\n", req.flags);
 
 		return -EINVAL;
@@ -2097,10 +2084,7 @@ static int fastrpc_req_mmap(struct fastrpc_user *fl, char __user *argp)
 		return -EINVAL;
 	}
 
-	if (req.flags == ADSP_MMAP_REMOTE_HEAP_ADDR)
-		err = fastrpc_remote_heap_alloc(fl, dev, req.size, &buf);
-	else
-		err = fastrpc_buf_alloc(fl, dev, req.size, &buf);
+	err = fastrpc_buf_alloc(fl, dev, req.size, &buf);
 
 	if (err) {
 		dev_err(dev, "failed to allocate buffer\n");
@@ -2139,20 +2123,6 @@ static int fastrpc_req_mmap(struct fastrpc_user *fl, char __user *argp)
 	/* let the client know the address to use */
 	req.vaddrout = rsp_msg.vaddr;
 
-	/* Add memory to static PD pool, protection thru hypervisor */
-	if (req.flags == ADSP_MMAP_REMOTE_HEAP_ADDR && fl->cctx->vmcount) {
-		u64 src_perms = BIT(QCOM_SCM_VMID_HLOS);
-
-		err = qcom_scm_assign_mem(buf->dma_addr, (u64)buf->size,
-			&src_perms, fl->cctx->vmperms, fl->cctx->vmcount);
-		if (err) {
-			dev_err(fl->sctx->dev,
-				"Failed to assign memory dma_addr %pad size 0x%llx err %d",
-				&buf->dma_addr, buf->size, err);
-			goto err_assign;
-		}
-	}
-
 	spin_lock(&fl->lock);
 	list_add_tail(&buf->node, &fl->mmaps);
 	spin_unlock(&fl->lock);
@@ -2533,6 +2503,45 @@ static const struct of_device_id fastrpc_poll_supported_machines[] __maybe_unuse
 	{},
 };
 
+static int fastrpc_init_reserved_mem(struct fastrpc_channel_ctx *cctx,
+				     struct device *rdev, u32 domain_id)
+{
+	struct resource res;
+	u64 src_perms;
+	int err;
+
+	/* Only SDSP and ADSP domains use a reserved remote heap region */
+	if (domain_id != SDSP_DOMAIN_ID && domain_id != ADSP_DOMAIN_ID)
+		return 0;
+
+	err = of_reserved_mem_region_to_resource(rdev->of_node, 0, &res);
+	if (err) {
+		/*
+		 * The reserved-memory region is optional at probe time. For
+		 * the Audio PD (ADSP) domain its absence is validated later in
+		 * fastrpc_init_create_static_process(), so keep probing here.
+		 */
+		return 0;
+	}
+
+	/*
+	 * Audio PD (ADSP) is a static PD: cache the region so its lifetime
+	 * is tied to the rpmsg channel instead of being controlled by
+	 * userspace.
+	 */
+	if (domain_id == ADSP_DOMAIN_ID) {
+		cctx->remote_heap_addr = res.start;
+		cctx->remote_heap_size = resource_size(&res);
+	}
+
+	if (!cctx->vmcount)
+		return 0;
+
+	src_perms = BIT(QCOM_SCM_VMID_HLOS);
+	return qcom_scm_assign_mem(res.start, resource_size(&res), &src_perms,
+				  cctx->vmperms, cctx->vmcount);
+}
+
 static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 {
 	struct device *rdev = &rpdev->dev;
@@ -2580,21 +2589,9 @@ static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev)
 		}
 	}
 
-	if (domain_id == SDSP_DOMAIN_ID) {
-		struct resource res;
-		u64 src_perms;
-
-		err = of_reserved_mem_region_to_resource(rdev->of_node, 0, &res);
-		if (!err) {
-			src_perms = BIT(QCOM_SCM_VMID_HLOS);
-
-			err = qcom_scm_assign_mem(res.start, resource_size(&res), &src_perms,
-				    data->vmperms, data->vmcount);
-			if (err)
-				goto err_free_data;
-		}
-
-	}
+	err = fastrpc_init_reserved_mem(data, rdev, domain_id);
+	if (err)
+		goto err_free_data;
 
 	secure_dsp = !(of_property_read_bool(rdev->of_node, "qcom,non-secure-domain"));
 	data->secure = secure_dsp;
@@ -2694,8 +2691,25 @@ static void fastrpc_rpmsg_remove(struct rpmsg_device *rpdev)
 	list_for_each_entry_safe(buf, b, &cctx->invoke_interrupted_mmaps, node)
 		list_del(&buf->node);
 
-	if (cctx->remote_heap)
-		fastrpc_buf_free(cctx->remote_heap);
+	if (cctx->remote_heap_size && cctx->vmcount) {
+		u64 src_perms = 0;
+		int err, i;
+		struct qcom_scm_vmperm dst_perms;
+
+		for (i = 0; i < cctx->vmcount; i++)
+			src_perms |= BIT(cctx->vmperms[i].vmid);
+
+		dst_perms.vmid = QCOM_SCM_VMID_HLOS;
+		dst_perms.perm = QCOM_SCM_PERM_RWX;
+
+		err = qcom_scm_assign_mem(cctx->remote_heap_addr,
+					  cctx->remote_heap_size, &src_perms,
+					  &dst_perms, 1);
+		if (err)
+			dev_err(&rpdev->dev,
+				"Failed to assign memory back to HLOS: addr %pa size %#llx err %d\n",
+				&cctx->remote_heap_addr, cctx->remote_heap_size, err);
+	}
 
 	of_platform_depopulate(&rpdev->dev);
 
Signature · 1 line
2.53.0
author maintainer
#610 lore raw

PATCH 607/1257 nvmem: rockchip-otp: Serialize reads

In reply to Greg Kroah-Hartman

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

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

From: Alexey Charkov <[email protected]>

[ Upstream commit 9fc6a1592d844c0397f115ee8cbd935169b9a71e ]

The OTP controller is driven through a single set of registers holding a state machine which has to be stepped through for every word read, yet nothing keeps two readers out of each other's way. Concurrent reads interleave, and the outcome is either a reader bailing out:

rockchip-otp 2a580000.otp: timeout during read setup

or, worse, one of them silently taking delivery of the other's data.

Reading two cells in parallel from userspace on RK3576 reproduces both within 150 iterations - 53 read errors and 9 corrupted results, the latter either losing their first word or, in one case, ending in the two bytes which belong to the other reader's cell - whereas the same reads issued sequentially never fail. Concurrency is not hypothetical here, as six thermal sensors source their trim values from the OTP and reach the driver straight from asynchronous driver probing.

Guard the read path with a mutex. Reads are the only way into the hardware, as the driver registers no write callback, and they always run in process context, so a plain mutex spanning the whole clock-enable, read, clock-disable sequence is enough.

---
 drivers/nvmem/rockchip-otp.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/nvmem/rockchip-otp.c +14 -1
index 2c0feb036f3fd..f8a8c7cece98d 100644
@@ -12,6 +12,7 @@
 #include <linux/io.h>
 #include <linux/iopoll.h>
 #include <linux/module.h>
+#include <linux/mutex.h>
 #include <linux/nvmem-provider.h>
 #include <linux/reset.h>
 #include <linux/slab.h>
@@ -80,6 +81,8 @@ struct rockchip_otp {
 	void __iomem *base;
 	struct reset_control *rst;
 	const struct rockchip_data *data;
+	/* Serializes access to the OTP controller state machine */
+	struct mutex mutex;
 	struct clk_bulk_data clks[];
 };
 
@@ -272,10 +275,12 @@ static int rockchip_otp_read(void *context, unsigned int offset,
 	if (!otp->data || !otp->data->reg_read)
 		return -EINVAL;
 
+	mutex_lock(&otp->mutex);
+
 	ret = clk_bulk_prepare_enable(otp->data->num_clks, otp->clks);
 	if (ret < 0) {
 		dev_err(otp->dev, "failed to prepare/enable clks\n");
-		return ret;
+		goto unlock;
 	}
 
 	offset += otp->data->read_offset;
@@ -308,6 +313,9 @@ static int rockchip_otp_read(void *context, unsigned int offset,
 err:
 	clk_bulk_disable_unprepare(otp->data->num_clks, otp->clks);
 
+unlock:
+	mutex_unlock(&otp->mutex);
+
 	return ret;
 }
 
@@ -431,6 +439,11 @@ static int rockchip_otp_probe(struct platform_device *pdev)
 
 	otp->data = data;
 	otp->dev = dev;
+
+	ret = devm_mutex_init(dev, &otp->mutex);
+	if (ret)
+		return ret;
+
 	otp->base = devm_platform_ioremap_resource(pdev, 0);
 	if (IS_ERR(otp->base))
 		return dev_err_probe(dev, PTR_ERR(otp->base),
Signature · 1 line
2.53.0
author maintainer
#611 lore raw

PATCH 608/1257 slimbus: messaging: fix leaked PM vote on tid allocation failure

In reply to Greg Kroah-Hartman

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

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

From: Zongmin Zhou <[email protected]>

[ Upstream commit c26cc979e28f5193310e4379e14aa6417375c565 ]

In slim_do_transfer(), when a transaction needs a tid and slim_alloc_txn_tid() fails, the function returns directly instead of jumping to slim_xfer_err. The runtime PM vote taken earlier with pm_runtime_get_sync() is then never released, leaving the controller permanently powered up.

As txn->tid is still 0 at that point, jumping to slim_xfer_err drops the vote exactly like it is done for other failed transactions.

---
 drivers/slimbus/messaging.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/slimbus/messaging.c +1 -1
index e2dbe4a66b703..ee127ef42046b 100644
@@ -139,7 +139,7 @@ int slim_do_transfer(struct slim_controller *ctrl, struct slim_msg_txn *txn)
 	if (need_tid) {
 		ret = slim_alloc_txn_tid(ctrl, txn);
 		if (ret)
-			return ret;
+			goto slim_xfer_err;
 
 		if (!txn->msg->comp)
 			txn->comp = &done;
Signature · 1 line
2.53.0
author maintainer
#612 lore raw

PATCH 609/1257 xen-blkfront: Fix IO race during unplug

In reply to Greg Kroah-Hartman

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

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

From: Ross Lagerwall <[email protected]>

[ Upstream commit 61b6d1df1d6234c38a6ea7e4f58e7da035ef6ab4 ]

During unplug, blkfront stops the hw queues and marks the disk as dead, then later during removal calls del_gendisk(). However, IO issued after the hw queues are stopped but before the call to del_gendisk() will be queued but never handled. This causes del_gendisk() to hang forever waiting for the queue refcount to drop to zero.

This can be reproduced by issuing IO during an artificial delay after stopping the hw queues.

Fix this by simply not stopping the hw queues directly. Marking the disk as dead already freezes the queue which prevents new requests being added and it synchronously runs the hw queues to clear anything pending. If the hw queues are stopped when calling blk_mark_disk_dead(), running the hw queues is a no-op and can leave queued requests unprocessed.

Message-ID: <[email protected]>

---
 drivers/block/xen-blkfront.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/block/xen-blkfront.c +1 -3
index 86f5dd3aced13..ad0cb42c10197 100644
@@ -2142,10 +2142,8 @@ static void blkfront_closing(struct blkfront_info *info)
 		return;
 
 	/* No more blkif_request(). */
-	if (info->rq && info->gd) {
-		blk_mq_stop_hw_queues(info->rq);
+	if (info->gd)
 		blk_mark_disk_dead(info->gd);
-	}
 
 	for_each_rinfo(info, rinfo, i) {
 		/* No more gnttab callback work. */
Signature · 1 line
2.53.0
author maintainer
#613 lore raw

PATCH 610/1257 RISC-V: KVM: Fix IPI delivery for out-of-order vcpu_id

In reply to Greg Kroah-Hartman

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

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

From: Xiaofeng Yuan <[email protected]>

[ Upstream commit c367d3bf721f2bc391d6cfb47f6884e99d563df0 ]

The SBI IPI handler walks vCPUs with kvm_for_each_vcpu(), which iterates by vcpu_idx (creation order) rather than vcpu_id order. Since vcpu_id can be assigned out of order by userspace, a vCPU whose hart_bit falls outside the XLEN-bit hart_mask range may be reached before vCPUs the mask actually targets. In that case the handler jumps to "done" and stops sending IPIs, leaving valid target vCPUs without an interrupt.

Replace the early "goto done" with "continue" so vCPUs outside the hart_mask range are skipped without aborting the loop.

Reproduced with a minimal userspace VMM driving KVM inside a QEMU (RISC-V virt) guest: three vCPUs are created with ids 100, 0, 1 (in creation order) and sbi_send_ipi(hart_mask=bit0, hbase=0) is called from vcpu_id 1. Before this change the IPI is dropped and the ecall returns SBI_ERR_INVALID_PARAM; with this change the IPI is delivered and the ecall returns SBI_SUCCESS.

---
 arch/riscv/kvm/vcpu_sbi_replace.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
arch/riscv/kvm/vcpu_sbi_replace.c +10 -2
index 506a510b6bff3..c2f1f7f264423 100644
@@ -64,8 +64,17 @@ static int kvm_sbi_ext_ipi_handler(struct kvm_vcpu *vcpu, struct kvm_run *run,
 			if (tmp->vcpu_id < hbase)
 				continue;
 			hart_bit = tmp->vcpu_id - hbase;
+			/*
+			 * kvm_for_each_vcpu() walks kvm->vcpus[] by
+			 * vcpu_idx, i.e. the creation order, which has
+			 * nothing to do with the vcpu_id (hart id) space
+			 * that the SBI IPI operates on. vcpu_ids need not
+			 * increase along the iteration, so harts outside
+			 * the hart_mask window must be skipped instead of
+			 * aborting the loop.
+			 */
 			if (hart_bit >= __riscv_xlen)
-				goto done;
+				continue;
 			if (!(hmask & (1UL << hart_bit)))
 				continue;
 		}
@@ -76,7 +85,6 @@ static int kvm_sbi_ext_ipi_handler(struct kvm_vcpu *vcpu, struct kvm_run *run,
 		kvm_riscv_vcpu_pmu_incr_fw(tmp, SBI_PMU_FW_IPI_RCVD);
 	}
 
-done:
 	if (hbase != -1UL && (hmask ^ sentmask))
 		retdata->err_val = SBI_ERR_INVALID_PARAM;
 
Signature · 1 line
2.53.0
author maintainer
#614 lore raw

PATCH 611/1257 vfio/mlx5: Fix boundary check in set_report_output()

In reply to Greg Kroah-Hartman

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

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

From: Seongjun Hong <[email protected]>

[ Upstream commit 37b2ee6747b7857920ebc71eabc25208a39164a4 ]

Use > instead of >= on boundary check of recv_buf to avoid the bug which the full message in the last slot of recv_buf is ignored even though the received data size does not overflow the recv_buf.

---
 drivers/vfio/pci/mlx5/cmd.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/vfio/pci/mlx5/cmd.c +1 -1
index 5fe0621b5fbd8..04180035a7fea 100644
@@ -1644,7 +1644,7 @@ set_report_output(u32 size, int index, struct mlx5_vhca_qp *qp,
 	int i;
 
 	buf_offset = index * qp->max_msg_size;
-	if (WARN_ON(buf_offset + size >= qp->recv_buf.npages * PAGE_SIZE ||
+	if (WARN_ON(buf_offset + size > qp->recv_buf.npages * PAGE_SIZE ||
 		    (nent > qp->max_msg_size / entry_size)))
 		return;
 
Signature · 1 line
2.53.0
author maintainer
#615 lore raw

PATCH 612/1257 cxl/port: Clear cached dport pointers when a dport is removed

In reply to Greg Kroah-Hartman

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

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

From: Dave Jiang <[email protected]>

[ Upstream commit 019560d23450a320f4060ff235563a5277ea8033 ]

Switch decoders cache dport pointers in cxlsd->target[], and nothing clears them when a dport is freed. Readers then dereference freed memory.

KASAN caught it under a cxl_test load/unload loop with concurrent sysfs reads (abbreviated).

Clear the matching slots from cxl_dport_remove(), walking the port's decoders the way cxl_port_update_decoder_targets() does on the add side. Scan all nr_targets slots, the target[] allocation size, and clear every hit.

---
 drivers/cxl/core/port.c | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
drivers/cxl/core/port.c +29 -0
index 625e4aa427db0..6ff3353865e39 100644
@@ -1089,11 +1089,40 @@ static void cond_cxl_root_unlock(struct cxl_port *port)
 		device_unlock(&port->dev);
 }
 
+static int clear_decoder_target(struct device *dev, void *data)
+{
+	struct cxl_dport *dport = data;
+	struct cxl_switch_decoder *cxlsd;
+
+	if (!is_switch_decoder(dev))
+		return 0;
+
+	cxlsd = to_cxl_switch_decoder(dev);
+	guard(rwsem_write)(&cxl_rwsem.region);
+
+	/*
+	 * A dport can occupy more than one position of an interleave, so
+	 * scan the whole target list rather than stopping at the first hit.
+	 */
+	for (int i = 0; i < cxlsd->nr_targets; i++) {
+		if (cxlsd->target[i] != dport)
+			continue;
+		cxlsd->target[i] = NULL;
+		dev_dbg(dev, "dport%d removed from target list, index %d\n",
+			dport->port_id, i);
+	}
+
+	return 0;
+}
+
 static void cxl_dport_remove(void *data)
 {
 	struct cxl_dport *dport = data;
 	struct cxl_port *port = dport->port;
 
+	/* counterpart of cxl_port_update_decoder_targets() */
+	device_for_each_child(&port->dev, dport, clear_decoder_target);
+
 	port->nr_dports--;
 	xa_erase(&port->dports, (unsigned long) dport->dport_dev);
 	put_device(dport->dport_dev);
Signature · 1 line
2.53.0
author maintainer
#616 lore raw

PATCH 613/1257 cxl/pci: Use the Device GPF DVSEC for restricted endpoints

In reply to Greg Kroah-Hartman

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

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

From: Guixin Liu <[email protected]>

[ Upstream commit d2654fa0d841fa36ffa76577f83a2810d643ae19 ]

cxl_gpf_get_dvsec() picks between the Port and the Device GPF DVSEC from the PCIe type of the given device, and only a plain endpoint counts as a device. A restricted CXL device is an endpoint too, but it falls into the port case and is probed for the Port GPF DVSEC instead of the Device GPF DVSEC.

On an RCD, dirty shutdown tracking therefore never arms: the DVSEC lookup in cxl_nvdimm_arm_dirty_shutdown_tracking() fails, the dirty shutdown count stays invalid, and the warning complains about a missing Port GPF DVSEC on a device.

Treat restricted endpoints as devices.

Fixes 36aace15d9bd ("cxl/pci: Drop the parameter is_port of cxl_gpf_get_dvsec()")
Assisted-by LLM
---
 drivers/cxl/core/pci.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/cxl/core/pci.c +2 -1
index 9d807c1a002ca..e31aad7a525a2 100644
@@ -804,7 +804,8 @@ u16 cxl_gpf_get_dvsec(struct device *dev)
 		return 0;
 
 	pdev = to_pci_dev(dev);
-	if (pci_pcie_type(pdev) == PCI_EXP_TYPE_ENDPOINT)
+	if (pci_pcie_type(pdev) == PCI_EXP_TYPE_ENDPOINT ||
+	    is_cxl_restricted(pdev))
 		is_port = false;
 
 	dvsec = pci_find_dvsec_capability(pdev, PCI_VENDOR_ID_CXL,
Signature · 1 line
2.53.0
author maintainer
#617 lore raw

PATCH 614/1257 cxl/pci: Program the Port GPF timeouts before caching the DVSEC

In reply to Greg Kroah-Hartman

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

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

From: Guixin Liu <[email protected]>

[ Upstream commit ec2e30a682945616d194d7999cf96606b7ee5a88 ]

cxl_gpf_port_setup() caches the Port GPF DVSEC offset in the dport before programming the phase timeouts, and ignores the return value of both update_gpf_port_dvsec() calls: the function always reports success.

A failing config write is therefore not only silent, it is also
permanent: the timeouts stay at the hardware defaults instead of the maximum flush window the kernel is asking for, and the cached offset keeps any later endpoint attach from retrying the update.

Propagate the errors and cache the offset only after both phases are programmed, so the next endpoint attach retries the setup.

Fixes 6af941db6a60 ("cxl/pci: Update Port GPF timeout only when the first EP attaching")
Assisted-by LLM
---
 drivers/cxl/core/pci.c | 30 +++++++++++++++++++++---------
 1 file changed, 21 insertions(+), 9 deletions(-)
drivers/cxl/core/pci.c +21 -9
index e31aad7a525a2..1f470ab0df3b7 100644
@@ -840,7 +840,7 @@ static int update_gpf_port_dvsec(struct pci_dev *pdev, int dvsec, int phase)
 
 	rc = pci_read_config_word(pdev, dvsec + offset, &ctrl);
 	if (rc)
-		return rc;
+		return pcibios_err_to_errno(rc);
 
 	if (FIELD_GET(base, ctrl) == GPF_TIMEOUT_BASE_MAX &&
 	    FIELD_GET(scale, ctrl) == GPF_TIMEOUT_SCALE_MAX)
@@ -850,11 +850,17 @@ static int update_gpf_port_dvsec(struct pci_dev *pdev, int dvsec, int phase)
 	ctrl |= FIELD_PREP(scale, GPF_TIMEOUT_SCALE_MAX);
 
 	rc = pci_write_config_word(pdev, dvsec + offset, ctrl);
-	if (!rc)
-		pci_dbg(pdev, "Port GPF phase %d timeout: %d0 secs\n",
-			phase, GPF_TIMEOUT_BASE_MAX);
+	if (rc) {
+		rc = pcibios_err_to_errno(rc);
+		pci_warn(pdev, "Port GPF phase %d timeout write failed: %d\n",
+			 phase, rc);
+		return rc;
+	}
 
-	return rc;
+	pci_dbg(pdev, "Port GPF phase %d timeout: %d0 secs\n",
+		phase, GPF_TIMEOUT_BASE_MAX);
+
+	return 0;
 }
 
 int cxl_gpf_port_setup(struct cxl_dport *dport)
@@ -864,16 +870,22 @@ int cxl_gpf_port_setup(struct cxl_dport *dport)
 
 	if (!dport->gpf_dvsec) {
 		struct pci_dev *pdev;
-		int dvsec;
+		int dvsec, rc;
 
 		dvsec = cxl_gpf_get_dvsec(dport->dport_dev);
 		if (!dvsec)
 			return -EINVAL;
 
-		dport->gpf_dvsec = dvsec;
 		pdev = to_pci_dev(dport->dport_dev);
-		update_gpf_port_dvsec(pdev, dport->gpf_dvsec, 1);
-		update_gpf_port_dvsec(pdev, dport->gpf_dvsec, 2);
+		rc = update_gpf_port_dvsec(pdev, dvsec, 1);
+		if (rc)
+			return rc;
+
+		rc = update_gpf_port_dvsec(pdev, dvsec, 2);
+		if (rc)
+			return rc;
+
+		dport->gpf_dvsec = dvsec;
 	}
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#618 lore raw

PATCH 615/1257 cxl/port: Convert PCIe link latency to nanoseconds

In reply to Greg Kroah-Hartman

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

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

From: Koichiro Den <[email protected]>

[ Upstream commit 16440d6e4bf1175cda83438d9f9a8ae84bfcf0ee ]

Commit 51293c565cf4 ("cxl: Fix incorrect region perf data calculation") converted CDAT latencies to nanoseconds and removed the conversion in cxl_region_perf_data_calculate(), but left PCIe link latencies in picoseconds.

This inflates the FlitLatency contribution to region and node latencies by a factor of 1000, exposing incorrect values in sysfs. The resulting abstract distances can incorrectly reverse the memory tier ordering of nodes.

Convert the FlitLatency contribution to nanoseconds before adding it to the access coordinates, rounding up as cdat_normalize() does.

---
 drivers/cxl/core/port.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/cxl/core/port.c +3 -0
index 6ff3353865e39..cd9e58d8144f1 100644
@@ -2349,6 +2349,9 @@ EXPORT_SYMBOL_NS_GPL(schedule_cxl_memdev_detach, "CXL");
 
 static void add_latency(struct access_coordinate *c, long latency)
 {
+	/* Convert link latency from picoseconds to nanoseconds. */
+	latency = DIV_ROUND_UP(latency, 1000);
+
 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++) {
 		c[i].write_latency += latency;
 		c[i].read_latency += latency;
Signature · 1 line
2.53.0
author maintainer
#619 lore raw

PATCH 616/1257 cxl: Account for link width in latency calculation

In reply to Greg Kroah-Hartman

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

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

From: Koichiro Den <[email protected]>

[ Upstream commit db4503d4575cdd2fad7e8a13a8a8ffcbc86d152d ]

cxl_pci_get_latency() derives bandwidth from the per-lane speed returned by pcie_link_speed_mbps(), ignoring the negotiated link width. This overestimates the FlitLatency contribution for multi-lane links. Sections 2.11.3 and 2.11.4 of the Intel CXL Memory Device Software Guide describe the link bandwidth as the product of the negotiated speed and width.

Replace pcie_link_speed_mbps() with pcie_link_bandwidth_mbps() and migrate both CXL callers (the only users of the API). The new helper obtains speed and width from a single Link Status read. The CXL bandwidth calculation no longer needs a separate width read and multiplication.

While at it, make error handling more robust by converting PCI config read errors to negative errno values and checking for zero bandwidth before calculating latency.

---
 drivers/cxl/core/pci.c | 22 ++++++++--------------
 drivers/pci/pci.c      | 23 ++++++++++++++++++-----
 include/linux/pci.h    |  2 +-
 3 files changed, 27 insertions(+), 20 deletions(-)
drivers/cxl/core/pci.c +8 -14
index 1f470ab0df3b7..bb6ad0753a421 100644
@@ -660,8 +660,8 @@ long cxl_pci_get_latency(struct pci_dev *pdev)
 {
 	long bw;
 
-	bw = pcie_link_speed_mbps(pdev);
-	if (bw < 0)
+	bw = pcie_link_bandwidth_mbps(pdev);
+	if (bw <= 0)
 		return 0;
 	bw /= BITS_PER_BYTE;
 
@@ -756,18 +756,12 @@ EXPORT_SYMBOL_NS_GPL(cxl_pci_setup_regs, "CXL");
 
 int cxl_pci_get_bandwidth(struct pci_dev *pdev, struct access_coordinate *c)
 {
-	int speed, bw;
-	u16 lnksta;
-	u32 width;
-
-	speed = pcie_link_speed_mbps(pdev);
-	if (speed < 0)
-		return speed;
-	speed /= BITS_PER_BYTE;
-
-	pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnksta);
-	width = FIELD_GET(PCI_EXP_LNKSTA_NLW, lnksta);
-	bw = speed * width;
+	int bw;
+
+	bw = pcie_link_bandwidth_mbps(pdev);
+	if (bw < 0)
+		return bw;
+	bw /= BITS_PER_BYTE;
 
 	for (int i = 0; i < ACCESS_COORDINATE_MAX; i++) {
 		c[i].read_bandwidth = bw;
drivers/pci/pci.c +18 -5
index d79d2ee4ac69b..38c7cb8221223 100644
@@ -6000,18 +6000,31 @@ static enum pci_bus_speed to_pcie_link_speed(u16 lnksta)
 	return pcie_link_speed[FIELD_GET(PCI_EXP_LNKSTA_CLS, lnksta)];
 }
 
-int pcie_link_speed_mbps(struct pci_dev *pdev)
+/**
+ * pcie_link_bandwidth_mbps - get the current bandwidth of a single PCIe link
+ * @pdev: PCI device to query
+ *
+ * The bandwidth includes all negotiated lanes and does not account for
+ * encoding overhead. A negotiated width of zero gives zero bandwidth.
+ *
+ * Return: Bandwidth in Mb/s, or a negative errno on failure.
+ */
+int pcie_link_bandwidth_mbps(struct pci_dev *pdev)
 {
 	u16 lnksta;
-	int err;
+	int speed, err;
 
 	err = pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &lnksta);
 	if (err)
-		return err;
+		return pcibios_err_to_errno(err);
+
+	speed = pcie_dev_speed_mbps(to_pcie_link_speed(lnksta));
+	if (speed < 0)
+		return speed;
 
-	return pcie_dev_speed_mbps(to_pcie_link_speed(lnksta));
+	return speed * FIELD_GET(PCI_EXP_LNKSTA_NLW, lnksta);
 }
-EXPORT_SYMBOL(pcie_link_speed_mbps);
+EXPORT_SYMBOL(pcie_link_bandwidth_mbps);
 
 /**
  * pcie_bandwidth_available - determine minimum link settings of a PCIe
include/linux/pci.h +1 -1
index 5ffcf5ce8c966..272378dd8973b 100644
@@ -1478,7 +1478,7 @@ int pcie_set_mps(struct pci_dev *dev, int mps);
 u32 pcie_bandwidth_available(struct pci_dev *dev, struct pci_dev **limiting_dev,
 			     enum pci_bus_speed *speed,
 			     enum pcie_link_width *width);
-int pcie_link_speed_mbps(struct pci_dev *pdev);
+int pcie_link_bandwidth_mbps(struct pci_dev *pdev);
 void pcie_print_link_status(struct pci_dev *dev);
 int pcie_reset_flr(struct pci_dev *dev, bool probe);
 int pcie_flr(struct pci_dev *dev);
Signature · 1 line
2.53.0
author maintainer
#620 lore raw

PATCH 617/1257 cxl/acpi: Convert QTG _DSM latencies to picoseconds

In reply to Greg Kroah-Hartman

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

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

From: Koichiro Den <[email protected]>

[ Upstream commit 2658c66a5efb5f30f5ced708a5de831845b43f6d ]

The QTG _DSM expects read and write latencies in picoseconds, as specified in CXL 3.0, Table 9-30.

The code base originally kept the latencies passed to the QTG _DSM in picoseconds in effect. Commit 51293c565cf4 ("cxl: Fix incorrect region perf data calculation") normalized CDAT and host bridge latencies to nanoseconds, but did not add a conversion back to picoseconds when constructing the _DSM input. Firmware can therefore select QTG IDs using understated latencies.

Convert the latencies to picoseconds when constructing the _DSM input package. Multiply in 64 bits and reject latencies that cannot fit in the DWORD inputs defined by the specification.

---
 drivers/cxl/acpi.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/cxl/acpi.c +8 -2
index fb09a5ff48c16..b7ce6b59c680b 100644
@@ -231,9 +231,10 @@ cxl_acpi_evaluate_qtg_dsm(acpi_handle handle, struct access_coordinate *coord,
 			  int entries, int *qos_class)
 {
 	union acpi_object *out_obj, *out_buf, *obj;
+	/* QTG _DSM expects latencies in picoseconds. */
 	union acpi_object in_array[4] = {
-		[0].integer = { ACPI_TYPE_INTEGER, coord->read_latency },
-		[1].integer = { ACPI_TYPE_INTEGER, coord->write_latency },
+		[0].integer = { ACPI_TYPE_INTEGER, coord->read_latency * 1000ULL },
+		[1].integer = { ACPI_TYPE_INTEGER, coord->write_latency * 1000ULL },
 		[2].integer = { ACPI_TYPE_INTEGER, coord->read_bandwidth },
 		[3].integer = { ACPI_TYPE_INTEGER, coord->write_bandwidth },
 	};
@@ -251,6 +252,11 @@ cxl_acpi_evaluate_qtg_dsm(acpi_handle handle, struct access_coordinate *coord,
 	if (!entries)
 		return -EINVAL;
 
+	/* Latency inputs must fit in the DWORD fields defined by the spec. */
+	if (coord->read_latency > U32_MAX / 1000 ||
+	    coord->write_latency > U32_MAX / 1000)
+		return -ERANGE;
+
 	out_obj = acpi_evaluate_dsm(handle, &acpi_cxl_qtg_id_guid, 1, 1, &in_obj);
 	if (!out_obj)
 		return -ENXIO;
Signature · 1 line
2.53.0
author maintainer
#621 lore raw

PATCH 618/1257 ALSA: hda/realtek: Enable all four speaker amps on Lenovo ThinkBook X G2 IAH

In reply to Greg Kroah-Hartman

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

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

From: Evgeny Akhtimirov <[email protected]>

[ Upstream commit f2293e7b2ddd803b1461e0490f9b2f32089c1dd0 ]

The Lenovo ThinkBook X G2 IAH (MTM 21TU) has an ALC287 codec with four CS35L41 amplifiers on I2C (CSC3551). It reports codec SSID 17aa:3929, which it shares with the ThinkBook 13x Gen 5, and PCI SSID 17aa:3842.

Since PCI SSID 17aa:3842 has no quirk entry, the codec SSID matches ALC287_FIXUP_MG_RTKC_CSAMP_CS35L41_I2C_THINKPAD. That fixup binds only two amps (cs35l41-hda.0 and .1), while the CS35L41 configuration table describes four for 17AA3929. Amps .2 and .3 probe and load firmware, but they are never bound to the codec, so half of the speakers stay silent.

Add a ThinkPad-style fixup chain that binds four I2C amps, and match the laptop by its PCI SSID so the ThinkBook 13x Gen 5 is not affected.

Tested with hda_model=1028:0c4d (alias to ALC287_FIXUP_CS35L41_I2C_4):
all four amps bind, apply their calibration and are runtime-active during playback.

---
 sound/hda/codecs/realtek/alc269.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
sound/hda/codecs/realtek/alc269.c +15 -0
index c66dd4a003f39..980e5029b2dbf 100644
@@ -4339,6 +4339,8 @@ enum {
 	ALC245_FIXUP_HP_X360_MUTE_LEDS,
 	ALC287_FIXUP_THINKPAD_I2S_SPK,
 	ALC287_FIXUP_MG_RTKC_CSAMP_CS35L41_I2C_THINKPAD,
+	ALC287_FIXUP_CS35L41_I2C_4_THINKPAD_ACPI,
+	ALC287_FIXUP_MG_RTKC_CSAMP_CS35L41_I2C_4_THINKPAD,
 	ALC2XX_FIXUP_HEADSET_MIC,
 	ALC289_FIXUP_DELL_CS35L41_SPI_2,
 	ALC256_FIXUP_ACER_SFG16_MICMUTE_LED,
@@ -6906,6 +6908,18 @@ static const struct hda_fixup alc269_fixups[] = {
 		.chained = true,
 		.chain_id = ALC287_FIXUP_CS35L41_I2C_2_THINKPAD_ACPI,
 	},
+	[ALC287_FIXUP_CS35L41_I2C_4_THINKPAD_ACPI] = {
+		.type = HDA_FIXUP_FUNC,
+		.v.func = cs35l41_fixup_i2c_four,
+		.chained = true,
+		.chain_id = ALC285_FIXUP_THINKPAD_NO_BASS_SPK_HEADSET_JACK,
+	},
+	[ALC287_FIXUP_MG_RTKC_CSAMP_CS35L41_I2C_4_THINKPAD] = {
+		.type = HDA_FIXUP_FUNC,
+		.v.func = alc287_fixup_tb_vmaster_led,
+		.chained = true,
+		.chain_id = ALC287_FIXUP_CS35L41_I2C_4_THINKPAD_ACPI,
+	},
 	[ALC2XX_FIXUP_HEADSET_MIC] = {
 		.type = HDA_FIXUP_FUNC,
 		.v.func = alc2xx_fixup_headset_mic,
@@ -8236,6 +8250,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x17aa, 0x3827, "Ideapad S740", ALC285_FIXUP_IDEAPAD_S740_COEF),
 	SND_PCI_QUIRK(0x17aa, 0x3834, "Lenovo IdeaPad Slim 9i 14ITL5", ALC287_FIXUP_YOGA7_14ITL_SPEAKERS),
 	SND_PCI_QUIRK(0x17aa, 0x383d, "Legion Y9000X 2019", ALC285_FIXUP_LEGION_Y9000X_SPEAKERS),
+	SND_PCI_QUIRK(0x17aa, 0x3842, "ThinkBook X G2 IAH", ALC287_FIXUP_MG_RTKC_CSAMP_CS35L41_I2C_4_THINKPAD),
 	SND_PCI_QUIRK(0x17aa, 0x3843, "Lenovo Yoga 9i / Yoga Book 9i", ALC287_FIXUP_LENOVO_YOGA_BOOK_9I),
 	/* Yoga Pro 7 14IMH9 shares PCI SSID 17aa:3847 with Legion 7 16ACHG6;
 	 * use codec SSID to distinguish them
Signature · 1 line
2.53.0
author maintainer
#622 lore raw

PATCH 619/1257 KVM: arm64: Prevent 64-bit overflow when computing hyp clock rate

In reply to Greg Kroah-Hartman

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

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

From: Vincent Donnefort <[email protected]>

[ Upstream commit 6164ce3491bcc3a27a2e2e9260a286eb2df2301e ]

The hypervisor clock rate is delta_cycles * NSEC_PER_SEC / delta_boot. It is computed whenever a deviation occurs. If the delta between two rate updates is big enough, delta_cycles * NSEC_PER_SEC will overflow.

Prevent overflow with mul_u64_u64_div_u64(). And as a bonus, simplify the clock estimation with mul_u64_u32_shr().

---
 arch/arm64/kvm/hyp_trace.c | 12 +++---------
 1 file changed, 3 insertions(+), 9 deletions(-)
arch/arm64/kvm/hyp_trace.c +3 -9
index 9644c424819b7..c60d7dfbf5e26 100644
@@ -59,14 +59,8 @@ static void __hyp_clock_work(struct work_struct *work)
 	if (hyp_clock->mult) {
 		u64 err, cur = delta_cycles;
 
-		if (WARN_ON_ONCE(cur >= hyp_clock->cyc_overflow64)) {
-			__uint128_t tmp = (__uint128_t)cur * hyp_clock->mult;
-
-			cur = tmp >> hyp_clock->shift;
-		} else {
-			cur *= hyp_clock->mult;
-			cur >>= hyp_clock->shift;
-		}
+		WARN_ON_ONCE(cur >= hyp_clock->cyc_overflow64);
+		cur = mul_u64_u32_shr(cur, hyp_clock->mult, hyp_clock->shift);
 		cur += hyp_clock->boot;
 
 		err = abs_diff(cur, boot);
@@ -84,7 +78,7 @@ static void __hyp_clock_work(struct work_struct *work)
 					    err / NSEC_PER_USEC);
 	}
 
-	rate = div64_u64(delta_cycles * NSEC_PER_SEC, delta_boot);
+	rate = mul_u64_u64_div_u64(delta_cycles, NSEC_PER_SEC, delta_boot);
 
 	clocks_calc_mult_shift(&hyp_clock->mult, &hyp_clock->shift,
 			       rate, NSEC_PER_SEC, CLOCK_MAX_CONVERSION_S);
Signature · 1 line
2.53.0
author maintainer
#623 lore raw

PATCH 620/1257 lib/plist: fix plist_requeue() corrupting order in the last bucket

In reply to Greg Kroah-Hartman

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

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

From: Adam Harshbarger <[email protected]>

[ Upstream commit 43c91b1522435429a63d175f5a953e6f727a4f88 ]

plist_requeue() is meant to move a node to the end of its own priority run. When the node heads the *last* priority bucket it is instead placed at the head of the whole list, leaving the plist unsorted:

built: A(prio 0) B(prio 1) C(prio 1)
requeue(B): B(prio 1) A(prio 0) C(prio 1)
expected: A(prio 0) C(prio 1) B(prio 1)

prio_list is a *headless* circular ring of the nodes that lead each priority bucket. The shortcut added by commit 95d4b3450ebe ("lib/plist.c:
add shortcut for plist_requeue()") takes

	iter = list_entry(iter->prio_list.next, struct plist_node,
			  prio_list);
	node_next = &iter->node_list;

which from the last bucket wraps round to the *first* bucket, so node_next ends up pointing at the head of the list rather than at its end. The plist_for_each_continue() loop immediately below it computes the correct answer (&head->node_list) for that case.

With any bucket after it the shortcut is correct, which is why this went
unnoticed: the benchmark in that commit measured elapsed time and never checked the resulting order.

Keep the shortcut -- it is a real win -- but exclude the case where iter's bucket is the last one, which is exactly when its ring successor is the first bucket again.

Reachable from mm/swapfile.c, which rotates swap_avail_heads[] with plist_requeue(). It takes three or more swap devices: at least two distinct priorities, so that a later bucket exists for the ring to wrap round from, and two or more devices sharing the lowest priority, so that plist_requeue() does not return early. One device per priority returns early at the node->prio != iter->prio test. A single priority is also safe, but for a different reason worth stating: with one bucket no node is ever linked onto prio_list at all -- plist_add() skips it for the first node and for every node whose predecessor shares its priority -- so list_empty(&iter->prio_list) holds and the shortcut is never entered.

Tested by driving three implementations -- the pre-95d4b3450ebe code, current mainline, and this patch -- through 1,084,492 identical random add/del/requeue operations over 24 nodes and 1..5 distinct priorities, comparing the resulting node_list node for node after every operation:

variant differs from pre-95d4b3450ebe left list unsorted
pre-95d4b3450ebe -- (reference) 0
mainline 289,297 276,660
this patch 0 0

Fixes 95d4b3450ebe ("lib/plist.c: add shortcut for plist_requeue()")
Assisted-by Claude:claude-opus-5
Cc I Hsin Cheng <[email protected]>
Cc <[email protected]> # v6.15+
---
 lib/plist.c | 7 +++++++
 1 file changed, 7 insertions(+)
lib/plist.c +7 -0
index a5bef38add431..b0273533c04d2 100644
@@ -174,8 +174,15 @@ void plist_requeue(struct plist_node *node, struct plist_head *head)
 	/*
 	 * After plist_del(), iter is the replacement of the node.  If the node
 	 * was on prio_list, take shortcut to find node_next instead of looping.
+	 *
+	 * prio_list is a headless ring, so from the LAST bucket ->next wraps
+	 * round to the first one; in that case node_next is the list head.
 	 */
 	if (!list_empty(&iter->prio_list)) {
+		struct plist_node *first = plist_first(head);
+
+		if (iter->prio_list.next == &first->prio_list)
+			goto queue;
 		iter = list_entry(iter->prio_list.next, struct plist_node,
 				  prio_list);
 		node_next = &iter->node_list;
Signature · 1 line
2.53.0
author maintainer
#624 lore raw

PATCH 621/1257 usb: core: dont set drvdata to NULL in usb_unbind_interface()

In reply to Greg Kroah-Hartman

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

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

From: Danilo Krummrich <[email protected]>

[ Upstream commit 8f0d16174102863936d583c90258ea02bf06205c ]

usb_unbind_interface() serves as the remove() callback of struct usb_driver and calls usb_set_intfdata(intf, NULL) to clear the bus device private data pointer.

However, the driver core code already sets the bus device private data pointer to NULL in device_unbind_cleanup() *after* devres_release_all(), which makes the call redundant.

In addition, it can create unexpected NULL pointer dereference scenarios when drivers use managed APIs.

	int probe(struct usb_interface *intf,
		  const struct usb_device_id *id)
	{
		struct data *data;
		int ret;

		data = devm_kzalloc(&intf->dev, sizeof(*data), GFP_KERNEL);
		if (!data)
			return -ENOMEM;

		ret = devm_device_add_group(&intf->dev, &foo_attr_group);
		if (ret)
			return ret;

		...
	}

	ssize_t foo_value_show(struct device *dev, struct device_attribute *attr,
			       char *buf)
	{
		struct usb_interface *intf = to_usb_interface(dev);
		struct data *data = usb_get_intfdata(intf);

		/* Potential NULL pointer dereference */
		return sysfs_emit(buf, "%u\n", data->value);
	}

Nothing prevents usb_unbind_interface() to race with foo_value_show() and set usb_set_intfdata(intf, NULL).

The same applies to the unwind path of usb_probe_interface(), which also calls usb_set_intfdata(intf, NULL).

Besides that, the Rust driver core code manages a driver's bus device private data and destroys it in device_unbind_cleanup().

If usb_unbind_interface() sets the pointer to NULL prematurely, the Rust driver core code sees NULL, and hence skips the destructor of the bus device private data, which leaks all its resources.

Thus, drop usb_set_intfdata(intf, NULL) from usb_probe_interface() and usb_unbind_interface(), and move it to usb_driver_release_interface(), which manually calls the remove() callback of struct usb_driver and hence can't rely on the driver core.

---
 drivers/usb/core/driver.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/usb/core/driver.c +1 -2
index bf660b15a0f60..9af0184276c10 100644
@@ -410,7 +410,6 @@ static int usb_probe_interface(struct device *dev)
 	return error;
 
  err:
-	usb_set_intfdata(intf, NULL);
 	intf->needs_remote_wakeup = 0;
 	intf->condition = USB_INTERFACE_UNBOUND;
 
@@ -497,7 +496,6 @@ static int usb_unbind_interface(struct device *dev)
 	} else {
 		intf->needs_altsetting0 = 1;
 	}
-	usb_set_intfdata(intf, NULL);
 
 	intf->condition = USB_INTERFACE_UNBOUND;
 	intf->needs_remote_wakeup = 0;
@@ -644,6 +642,7 @@ void usb_driver_release_interface(struct usb_driver *driver,
 	} else {
 		device_lock(dev);
 		usb_unbind_interface(dev);
+		dev_set_drvdata(dev, NULL);
 		dev->driver = NULL;
 		device_unlock(dev);
 	}
Signature · 1 line
2.53.0
author maintainer
#625 lore raw

PATCH 622/1257 usb: octeon-hcd: release the USB block when initialization fails

In reply to Greg Kroah-Hartman

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

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

From: Orgad Shaneh <[email protected]>

[ Upstream commit b8c063059f304abebc11039195f5b28298aeddbb ]

cvmx_usb_initialize() gets as far as selecting the reference clock, enabling USBN_CLK_CTL and taking the PHY out of reset (steps 2b-2e) before anything can go wrong, and its only caller frees the HCD and returns without touching the hardware. Both of its error returns therefore leave the USB block clocked and out of reset on a failed probe.

Release it on the way out with cvmx_usb_shutdown(), which is the undo the retry path a few lines above already uses. It cannot refuse with -EBUSY here: the pipe lists it checks are initialised by octeon_usb_probe() before cvmx_usb_initialize() is called, and no pipe can have been opened yet.

Fixes 22bce6d2b3fd ("usb: octeon-hcd: fail the probe when the USB core does not respond")
Cc stable <[email protected]>
Assisted-by LLM
---
 drivers/usb/host/octeon-hcd.c | 21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)
drivers/usb/host/octeon-hcd.c +18 -3
index 256e459ff6d8d..4d6558e5492c2 100644
@@ -708,6 +708,7 @@ static int cvmx_usb_initialize(struct device *dev,
 	int channel;
 	int divisor;
 	int retries = 0;
+	int status;
 	union cvmx_usbcx_hcfg usbcx_hcfg;
 	union cvmx_usbnx_clk_ctl usbn_clk_ctl;
 	union cvmx_usbcx_gintsts usbc_gintsts;
@@ -872,7 +873,8 @@ static int cvmx_usb_initialize(struct device *dev,
 	if (usbcx_gahbcfg.u32 == 0xffffffff || usbcx_gahbcfg.u32 == 0) {
 		dev_err(dev, "USB core is not responding (GHWCFG3=0x%08x)\n",
 			usbcx_gahbcfg.u32);
-		return -ENODEV;
+		status = -ENODEV;
+		goto err_shutdown;
 	}
 
 	usbcx_gahbcfg.u32 = 0;
@@ -961,14 +963,27 @@ static int cvmx_usb_initialize(struct device *dev,
 	dev_dbg(dev, "gintsts after reset: 0x%x\n", (int)usbc_gintsts.u32);
 	if (!usbc_gintsts.s.disconnint && !usbc_gintsts.s.prtint)
 		return 0;
-	if (retries++ >= 5)
-		return -EAGAIN;
+	if (retries++ >= 5) {
+		status = -EAGAIN;
+		goto err_shutdown;
+	}
 	dev_info(dev, "controller reset failed (gintsts=0x%x) - retrying\n",
 		 (int)usbc_gintsts.u32);
 	msleep(50);
 	cvmx_usb_shutdown(usb);
 	msleep(50);
 	goto retry;
+
+err_shutdown:
+	/*
+	 * Steps 2b-2e above selected the reference clock, enabled
+	 * USBN_CLK_CTL and took the PHY out of reset, and the caller only
+	 * frees the HCD, so hand the block back before giving up. The pipe
+	 * lists cvmx_usb_shutdown() checks are initialised by the caller
+	 * before it gets here, so it cannot refuse with -EBUSY.
+	 */
+	cvmx_usb_shutdown(usb);
+	return status;
 }
 
 /**
Signature · 1 line
2.53.0
author maintainer
#626 lore raw

PATCH 623/1257 usb: octeon-hcd: keep SOF interrupts while a pipe needs them

In reply to Greg Kroah-Hartman

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

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

From: Orgad Shaneh <[email protected]>

[ Upstream commit 68ee2f70d0257aa327ebf8406cd28475574585f2 ]

cvmx_usb_schedule() now sleeps on an hrtimer until the nearest future periodic deadline instead of counting frames down on every SOF. The scan that finds that deadline only looks at pipes with

	next_tx_frame > usb->frame_number

which is right for picking the deadline, but two kinds of pipe that need a SOF to make progress are invisible to the decision:

- A periodic pipe that is due and was *not* started: no idle hardware channel this round, its split window is closed (cvmx_usb_find_ready_pipe() rejects both), or another pipe owns usb->active_split. cvmx_usb_next_pipe() looks at the isochronous and interrupt lists only when is_sof is true.

- Any pipe that has sent its start split and waits for the frame its split complete may go out in (split_sc_frame, also checked by cvmx_usb_find_ready_pipe()). A control or bulk pipe on a full or low speed device behind a hub is in this state between its two halves, and with SOF masked nothing guarantees an interrupt that brings frame_number there.

When some other periodic pipe sets a far deadline - a hub's status pipe, whenever a hub is attached - the driver masks SOF, arms the timer for that deadline and these pipes wait for it. That is hundreds of frames; the code allows up to 8000 (one second) before it falls back to SOF.

Before the hrtimer this could not happen: any pipe with a future deadline set need_sof, so SOF stayed enabled every frame and the pipe was retried on the next one.

Note such a pipe and keep SOF enabled while there is one, whether or not another pipe has a future deadline. Nothing changes when there is none, which is the case the timer was added for.

Other control and bulk pipes are excluded deliberately: their next_tx_frame is not updated on completion, so they are almost always "due" and would keep SOF enabled permanently.

Fixes aebbc7d63407 ("usb: octeon-hcd: sleep on an hrtimer for far-off periodic transfers")
Cc stable <[email protected]>
Assisted-by LLM
---
 drivers/usb/host/octeon-hcd.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
drivers/usb/host/octeon-hcd.c +19 -1
index 4d6558e5492c2..4929c6a8e733b 100644
@@ -1938,6 +1938,7 @@ static void cvmx_usb_schedule(struct octeon_hcd *usb, int is_sof)
 	struct cvmx_usb_pipe *pipe;
 	int need_sof;
 	u64 min_due;
+	bool due_now;
 	enum cvmx_usb_transfer ttype;
 
 	if (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA) {
@@ -1979,15 +1980,32 @@ static void cvmx_usb_schedule(struct octeon_hcd *usb, int is_sof)
 	 */
 	need_sof = 0;
 	min_due = ~0ull;
+	due_now = false;
 	for (ttype = CVMX_USB_TRANSFER_CONTROL;
 	     ttype <= CVMX_USB_TRANSFER_INTERRUPT; ttype++) {
 		list_for_each_entry(pipe, &usb->active_pipes[ttype], node) {
+			/*
+			 * Do not sleep past a pipe that is only retried from a
+			 * SOF: a periodic one that is due but was not started
+			 * (no idle channel, closed split window, another pipe's
+			 * split active), or any pipe waiting for the frame its
+			 * split complete may go out in. Other control and bulk
+			 * pipes are left out: their next_tx_frame is not updated
+			 * on completion, so they always look due.
+			 */
+			if (pipe->split_sc_frame != -1 ||
+			    (pipe->next_tx_frame <= usb->frame_number &&
+			     (ttype == CVMX_USB_TRANSFER_ISOCHRONOUS ||
+			      ttype == CVMX_USB_TRANSFER_INTERRUPT)))
+				due_now = true;
 			if (pipe->next_tx_frame > usb->frame_number &&
 			    pipe->next_tx_frame < min_due)
 				min_due = pipe->next_tx_frame;
 		}
 	}
-	if (min_due != ~0ull) {
+	if (due_now) {
+		need_sof = 1;
+	} else if (min_due != ~0ull) {
 		u64 delta = min_due - usb->frame_number;
 
 		/*
Signature · 1 line
2.53.0
author maintainer
#627 lore raw

PATCH 624/1257 USB: cdc-acm: add VeriFone VX820 device ID

In reply to Greg Kroah-Hartman

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

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

From: Drobyshev Vladimir <[email protected]>

[ Upstream commit ddbddee6592ecf6cf6c24d888780f9ad45a3e30b ]

Add USB ID 11ca:0219 for the VeriFone VX820 to the cdc-acm device table and apply the SINGLE_RX_URB quirk.

---
 drivers/usb/class/cdc-acm.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/usb/class/cdc-acm.c +3 -0
index 6a1c574634949..489575d40bd14 100644
@@ -1819,6 +1819,9 @@ static const struct usb_device_id acm_ids[] = {
 	{ USB_DEVICE(0x11ca, 0x0201), /* VeriFone Mx870 Gadget Serial */
 	.driver_info = SINGLE_RX_URB,
 	},
+	{ USB_DEVICE(0x11ca, 0x0219), /* VeriFone Vx820 Gadget Serial */
+	.driver_info = SINGLE_RX_URB,
+	},
 	{ USB_DEVICE(0x1901, 0x0006), /* GE Healthcare Patient Monitor UI Controller */
 	.driver_info = DISABLE_ECHO, /* DISABLE ECHO in termios flag */
 	},
Signature · 1 line
2.53.0
author maintainer
#628 lore raw

PATCH 625/1257 USB: quirks: add USB_QUIRK_WINDOWS_CONFIG_REQ_SIZE for GameSir G7 SE

In reply to Greg Kroah-Hartman

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

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

From: Ali Resool Tuama <[email protected]>

[ Upstream commit 40224df29729618ecd88c5c0077e71b1e82c7a3a ]

The GameSir G7 SE wired controller first enumerates as 3537:10a0 and then re-enumerates in a mode it picks from how the host enumerated it.

When the configuration descriptor is fetched the Linux way, 9 bytes followed by the full 80, the controller disconnects about 1 ms after its string descriptors have been read, before SET_CONFIGURATION, and comes back as 3537:1082, a generic HID gamepad without force feedback.

When the configuration descriptor is fetched in one 255-byte request, as Windows does, it comes back as 3537:1010 in Xbox One (GIP) mode, which xpad already supports, including rumble.

Skipping the device qualifier requests (USB_QUIRK_DEVICE_QUALIFIER) makes no difference; the configuration descriptor request size alone decides the mode. Add USB_QUIRK_WINDOWS_CONFIG_REQ_SIZE for the 10a0 identity, as is already done for the ShanWan Wireless Gamepad.

---
 drivers/usb/core/quirks.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/usb/core/quirks.c +3 -0
index b5b577f0b931c..a4bcbe9c913cf 100644
@@ -612,6 +612,9 @@ static const struct usb_device_id usb_quirk_list[] = {
 	/* ezcap401 - BOS descriptor fetch hangs at SuperSpeed Plus */
 	{ USB_DEVICE(0x32ed, 0x0401), .driver_info = USB_QUIRK_NO_BOS },
 
+	/* GameSir G7 SE */
+	{ USB_DEVICE(0x3537, 0x10a0), .driver_info = USB_QUIRK_WINDOWS_CONFIG_REQ_SIZE },
+
 	/* DELL USB GEN2 */
 	{ USB_DEVICE(0x413c, 0xb062), .driver_info = USB_QUIRK_NO_LPM | USB_QUIRK_RESET_RESUME },
 
Signature · 1 line
2.53.0
author maintainer
#629 lore raw

PATCH 626/1257 usb: typec: ucsi: Skip CAM query when partner has no alt modes

In reply to Greg Kroah-Hartman

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

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

From: Gris Ge <[email protected]>

[ Upstream commit 7c590f0716ed3c9ae9809dbc6d488d76c19fdf52 ]

Since Thunderbolt alternate mode support was added, ucsi_altmode_update_active() is called on every Connector Partner Changed event. This made the driver send UCSI_GET_CURRENT_CAM to PPMs even when the partner had no alternate modes registered. Firmware that does not support the optional alternate mode details answered Not Supported, which produced a spurious error on every partner change:

```
ucsi_acpi USBC000:00: GET_CURRENT_CAM command failed
```

Fixed by skipping the command when there is nothing to update.

Fixes da87d45b1951 ("usb: typec: ucsi: Add Thunderbolt alternate mode support")
Assisted-by Codex:deepseek-v4.1-flash
Cc stable <[email protected]>
---
 drivers/usb/typec/ucsi/ucsi.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/usb/typec/ucsi/ucsi.c +2 -1
index c1450639c7956..264338fd594a6 100644
@@ -1519,7 +1519,8 @@ static void ucsi_handle_connector_change(struct work_struct *work)
 
 	if (con->partner && (change & UCSI_CONSTAT_PARTNER_CHANGE)) {
 		ucsi_partner_change(con);
-		ucsi_altmode_update_active(con);
+		if (con->partner_altmode[0])
+			ucsi_altmode_update_active(con);
 
 		/* Complete pending data role swap */
 		if (!completion_done(&con->complete))
Signature · 1 line
2.53.0
author maintainer
#630 lore raw

PATCH 627/1257 usb: typec: ucsi: ccg: Validate altmode index in GET_CURRENT_CAM response

In reply to Greg Kroah-Hartman

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

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

From: Seungjin Bae <[email protected]>

[ Upstream commit 02ee864e8d2142c5648998944c3306ea6a763c26 ]

When the PPM reports more than one DisplayPort alternate mode for a connector, ucsi_ccg_update_altmodes() merges them into a single entry in uc->updated[] and sets uc->has_multiple_dp. In that case, ucsi_ccg_update_get_current_cam_cmd() rewrites the response of the GET_CURRENT_CAM command. The response is a single byte holding the index of the currently active alternate mode, and it is provided by the PPM firmware.

The function uses this byte directly as an index into uc->orig[], and then uses the linked_idx read from that entry as the translated index into uc->updated[]. Both arrays have UCSI_MAX_ALTMODES entries, but neither index is checked against that size.

If a malicious or buggy PPM reports a value of UCSI_MAX_ALTMODES or larger, e.g. 0xFF, uc->orig[cam].linked_idx reads over the end of uc->orig[]. The byte read from there is then used as the index for writing cam into uc->updated[new_cam].active_idx, so the out-of-bounds read is followed by an out-of-bounds write. This happens without any userspace action, since the UCSI core issues GET_CURRENT_CAM on its own when handling connector changes.

Fix this by rejecting responses whose index is out of range, printing an error and returning -EPROTO, so that the caller cannot accept this. Also check linked_idx before using it as an index, so that the write into uc->updated[] is always within bounds.

The response is now only processed when the command completed without an error. ucsi_sync_control_common() only reads the response when the CCI reports command completion, so otherwise the buffer is not filled and must not be mistaken for an invalid index.

This bug was found with a Python script that traces where firmware input is used.

Fixes 170a6726d0e2 ("usb: typec: ucsi: add support for separate DP altmode devices")
Cc stable <[email protected]>
Assisted-by LLM
---
 drivers/usb/typec/ucsi/ucsi_ccg.c | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)
drivers/usb/typec/ucsi/ucsi_ccg.c +19 -3
index 91c2958a708c0..80e3e84b418d7 100644
@@ -384,14 +384,28 @@ static int ucsi_ccg_init(struct ucsi_ccg *uc)
 	return -ETIMEDOUT;
 }
 
-static void ucsi_ccg_update_get_current_cam_cmd(struct ucsi_ccg *uc, u8 *data)
+static int ucsi_ccg_update_get_current_cam_cmd(struct ucsi_ccg *uc, u8 *data)
 {
 	u8 cam, new_cam;
 
 	cam = data[0];
+	if (cam >= UCSI_MAX_ALTMODES) {
+		dev_err(uc->dev, "PPM returned invalid alternate mode index %u\n",
+			cam);
+		return -EPROTO;
+	}
+
 	new_cam = uc->orig[cam].linked_idx;
+	if (new_cam >= UCSI_MAX_ALTMODES) {
+		dev_err(uc->dev, "invalid linked alternate mode index %u for %u\n",
+			new_cam, cam);
+		return -EPROTO;
+	}
+
 	uc->updated[new_cam].active_idx = cam;
 	data[0] = new_cam;
+
+	return 0;
 }
 
 static bool ucsi_ccg_update_altmodes(struct ucsi *ucsi,
@@ -636,8 +650,10 @@ static int ucsi_ccg_sync_control(struct ucsi *ucsi, u64 command, u32 *cci,
 
 	switch (UCSI_COMMAND(command)) {
 	case UCSI_GET_CURRENT_CAM:
-		if (uc->has_multiple_dp)
-			ucsi_ccg_update_get_current_cam_cmd(uc, (u8 *)data);
+		if (!ret && uc->has_multiple_dp &&
+		    (*cci & UCSI_CCI_COMMAND_COMPLETE) &&
+		    !(*cci & UCSI_CCI_ERROR))
+			ret = ucsi_ccg_update_get_current_cam_cmd(uc, (u8 *)data);
 		break;
 	case UCSI_GET_ALTERNATE_MODES:
 		if (UCSI_ALTMODE_RECIPIENT(command) == UCSI_RECIPIENT_SOP) {
Signature · 1 line
2.53.0
author maintainer
#631 lore raw

PATCH 628/1257 usb: xhci: Fix bounce buffer overflow

In reply to Greg Kroah-Hartman

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

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

From: Michal Pecio <[email protected]>

[ Upstream commit 68c5cb7574c567e83ba95258cb146db95e069a87 ]

High-speed devices with out of spec 1024 byte bulk endpoints exist and are allowed by USB core, but xhci-hcd always sets packet size to 512. The exact nature of these devices isn't documented, commit fb5ee84ea72c ("USB: Accept bulk endpoints with 1024-byte maxpacket") only states that they "don't work with xHCI host controllers", whatever it means.

But somebody (or a malicious device) can try, and then the driver will allocate a 512 byte bounce buffer for this endpoint and may write up to 1024 bytes into it if particular scatter-gather URBs are used, because xhci_align_td() obtains packet size from the descriptor. Fix this.

As a side effect, TRBs will be aligned to the packet size chosen by the driver on all endpoints of all speeds. Alignment serves the xHC, not device, so this is fine. Only out of spec devices are affected anyway.

---
 drivers/usb/host/xhci-ring.c | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)
drivers/usb/host/xhci-ring.c +3 -6
index ec278a9f95404..fffd901b59e7f 100644
@@ -3544,15 +3544,13 @@ static u32 xhci_td_remainder(struct xhci_hcd *xhci, int transferred,
 
 
 static int xhci_align_td(struct xhci_hcd *xhci, struct urb *urb, u32 enqd_len,
-			 u32 *trb_buff_len, struct xhci_segment *seg)
+			 u32 *trb_buff_len, struct xhci_segment *seg, u32 max_pkt)
 {
 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
 	unsigned int unalign;
-	unsigned int max_pkt;
 	u32 new_buff_len;
 	size_t len;
 
-	max_pkt = xhci_usb_endpoint_maxp(urb->dev, urb->ep);
 	unalign = (enqd_len + *trb_buff_len) % max_pkt;
 
 	/* we got lucky, last normal TRB data on segment is packet aligned */
@@ -3697,9 +3695,8 @@ int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
 		if (enqd_len + trb_buff_len < full_len) {
 			field |= TRB_CHAIN;
 			if (trb_is_link(ring->enqueue + 1)) {
-				if (xhci_align_td(xhci, urb, enqd_len,
-						  &trb_buff_len,
-						  ring->enq_seg)) {
+				if (xhci_align_td(xhci, urb, enqd_len, &trb_buff_len,
+						ring->enq_seg, ring->bounce_buf_len)) {
 					send_addr = ring->enq_seg->bounce_dma;
 					/* TD bounced at least, and last on this seg */
 					td->bounce_seg = ring->enq_seg;
Signature · 1 line
2.53.0
author maintainer
#632 lore raw

PATCH 629/1257 xhci: Prevent invalid vdev dereference during sideband unregister

In reply to Greg Kroah-Hartman

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

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

From: Mathias Nyman <[email protected]>

[ Upstream commit fd616dc74e8f58f351f2b295620027116cd6e92e ]

Offloaded USB audio devices using the xhci-sideband API store a pointer to the xhci virtual device (vdev) in the sideband structure when registering.

This pointer typically remains valid throughout the lifetime of the USB device. If a configured offloaded device requires a reset, the USB core usually unbinds or notifies the audio driver beforehand, ensuring that the sideband is unregistered before the vdev is freed.

An exception occurs when the USB core resets a device to recover from a failed resume, but a subsequent 'address device' request also fails. To recover in this specific scenario, the xHCI driver disables and re-enables the slot, which frees and re-allocates the vdev.

xhci_sideband_unregister() later dereferences the stale, previously freed vdev pointer during disconnect, triggering a kernel oops:

 Unable to handle kernel paging request at virtual address dead000000000122
 Call trace:
  xhci_get_ep_ctx+0x0/0x38
  xhci_sideband_unregister+0x68/0xf0
  uaudio_disconnect+0x70/0x144
  usb_audio_disconnect+0x7c/0x268
  usb_unbind_interface+0x13c/0x340
  device_release_driver_internal+0x1c4/0x2bc
  usb_disable_device+0x84/0x190
  usb_disconnect+0xe8/0x338
  hub_event+0xbd8/0x19ac

Fix this by preventing the reallocation of the vdev in this specific error path if the device is registered for sideband use.

Just propagate the error directly to the USB core. It should either retry enumeration or detect the disconnected device, and handle it accordingly.

Debugging this issue to the dangling vdev pointer, reporting it, testing, and initial patch with different solution by Lianqin Hu

---
 drivers/usb/host/xhci.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
drivers/usb/host/xhci.c +7 -4
index a9e47e178c280..28bfe5fd0b6f4 100644
@@ -4435,10 +4435,13 @@ static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
 		dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
 
 		mutex_unlock(&xhci->mutex);
-		ret = xhci_disable_and_free_slot(xhci, udev->slot_id);
-		if (!ret) {
-			if (xhci_alloc_dev(hcd, udev) == 1)
-				xhci_setup_addressable_virt_dev(xhci, udev);
+
+		if (!virt_dev->sideband) {
+			ret = xhci_disable_and_free_slot(xhci, udev->slot_id);
+			if (!ret) {
+				if (xhci_alloc_dev(hcd, udev) == 1)
+					xhci_setup_addressable_virt_dev(xhci, udev);
+			}
 		}
 		kfree(command->completion);
 		kfree(command);
Signature · 1 line
2.53.0
author maintainer
#633 lore raw

PATCH 630/1257 usb: xhci-pci: Add AMD 600 series to xhci-pci-prom21

In reply to Greg Kroah-Hartman

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

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

From: Stephen Horvath <[email protected]>

[ Upstream commit 29381088ac50a4910d18a5f8079d9bd505f839be ]

It seems the xhci-pci-prom21 module only has IDs for the 800 series chipsets. However, the 600 series chipsets also have Promontory 21 chips, so we should add their IDs to the list as well.

I have tested this on my X670 board featuring DID 0x43f7.

1022:43f7 also appears on the PCI ID database
(https://pci-ids.ucw.cz/read/PC/1022/43f7).
Device IDs 0x43f9 (B665) & 0x43fa (A620) were suggested by Shyam.

Also list the new IDs in Documentation/hwmon/prom21-xhci.rst.

---
 Documentation/hwmon/prom21-xhci.rst | 2 +-
 drivers/usb/host/xhci-pci-prom21.c  | 3 +++
 drivers/usb/host/xhci-pci.c         | 3 +++
 drivers/usb/host/xhci-pci.h         | 3 +++
 4 files changed, 10 insertions(+), 1 deletion(-)
Documentation/hwmon/prom21-xhci.rst +1 -1
index 7984fb187bd8a..6c0b6e7368921 100644
@@ -9,7 +9,7 @@ Supported chips:
 
     Prefix: 'prom21_xhci'
 
-    PCI IDs: 1022:43fc, 1022:43fd
+    PCI IDs: 1022:43f7, 1022:43f9, 1022:43fa, 1022:43fc, 1022:43fd
 
 Author:
 
drivers/usb/host/xhci-pci-prom21.c +3 -0
index 6486f4a093455..5f088a47d79f3 100644
@@ -111,6 +111,9 @@ static void prom21_xhci_remove(struct pci_dev *dev)
 }
 
 static const struct pci_device_id pci_ids[] = {
+	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_PROM21_XHCI_43F7) },
+	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_PROM21_XHCI_43F9) },
+	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_PROM21_XHCI_43FA) },
 	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_PROM21_XHCI_43FC) },
 	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_PROM21_XHCI_43FD) },
 	{ /* end: all zeroes */ }
drivers/usb/host/xhci-pci.c +3 -0
index a8889081ae824..b407676808fca 100644
@@ -701,6 +701,9 @@ static const struct pci_device_id pci_ids_renesas[] = {
 
 /* handled by xhci-pci-prom21 if enabled */
 static const struct pci_device_id pci_ids_prom21[] = {
+	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_PROM21_XHCI_43F7) },
+	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_PROM21_XHCI_43F9) },
+	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_PROM21_XHCI_43FA) },
 	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_PROM21_XHCI_43FC) },
 	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_PROM21_XHCI_43FD) },
 	{ /* end: all zeroes */ }
drivers/usb/host/xhci-pci.h +3 -0
index 11f435f94322a..533efc7db8012 100644
@@ -4,6 +4,9 @@
 #ifndef XHCI_PCI_H
 #define XHCI_PCI_H
 
+#define PCI_DEVICE_ID_AMD_PROM21_XHCI_43F7	0x43f7
+#define PCI_DEVICE_ID_AMD_PROM21_XHCI_43F9	0x43f9
+#define PCI_DEVICE_ID_AMD_PROM21_XHCI_43FA	0x43fa
 #define PCI_DEVICE_ID_AMD_PROM21_XHCI_43FC	0x43fc
 #define PCI_DEVICE_ID_AMD_PROM21_XHCI_43FD	0x43fd
 
Signature · 1 line
2.53.0
author maintainer
#634 lore raw

PATCH 631/1257 usb: typec: ucsi_ccg: Add retry mechanism in ccg_read

In reply to Greg Kroah-Hartman

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

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

From: Wayne Chang <[email protected]>

[ Upstream commit bbf6b99a57b2479bf51c3c8ad0946f4b8c33ed69 ]

CCG4 firmware occasionally fails to respond to I2C read requests, especially when reading cci and intr_reg from the ISR path. In these cases, i2c_transfer() returns -EREMOTEIO.

The CCG4 is EOL, and Infineon no longer supports firmware updates, so a software workaround is necessary.

Attempt the read up to CCG_READ_MAX_RETRIES (4) times in total when -EREMOTEIO is returned, sleeping ~1 ms via fsleep() between attempts. This allows recovery from transient I2C failures without affecting other error paths.

The sleep is safe because ccg_read() is called both from process context and from ccg_irq_handler(), which runs in threaded IRQ context (registered via request_threaded_irq() with a NULL hard-IRQ handler), so sleeping is allowed in both cases.

---
 drivers/usb/typec/ucsi/ucsi_ccg.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/usb/typec/ucsi/ucsi_ccg.c +14 -1
index 80e3e84b418d7..3f12db95c7f46 100644
@@ -135,6 +135,8 @@ struct version_format {
 #define NVIDIA_FTB_DP_OFFSET	(2)
 #define NVIDIA_FTB_DBG_OFFSET	(3)
 
+#define CCG_READ_MAX_RETRIES	4
+
 struct version_info {
 	struct version_format base;
 	struct version_format app;
@@ -255,6 +257,7 @@ static int ccg_read(struct ucsi_ccg *uc, u16 rab, u8 *data, u32 len)
 	};
 	u32 rlen, rem_len = len, max_read_len = len;
 	int status;
+	int retry_count;
 
 	/* check any max_read_len limitation on i2c adapter */
 	if (quirks && quirks->max_read_len)
@@ -266,7 +269,17 @@ static int ccg_read(struct ucsi_ccg *uc, u16 rab, u8 *data, u32 len)
 		rlen = min_t(u16, rem_len, max_read_len);
 		msgs[1].len = rlen;
 		put_unaligned_le16(rab, buf);
-		status = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
+
+		for (retry_count = 0; retry_count < CCG_READ_MAX_RETRIES; retry_count++) {
+			status = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
+
+			/* Only retry on -EREMOTEIO, and not after the last attempt */
+			if (status != -EREMOTEIO || retry_count == CCG_READ_MAX_RETRIES - 1)
+				break;
+
+			fsleep(1000);
+		}
+
 		if (status < 0) {
 			dev_err(uc->dev, "i2c_transfer failed %d\n", status);
 			pm_runtime_put_sync(uc->dev);
Signature · 1 line
2.53.0
author maintainer
#635 lore raw

PATCH 632/1257 mailbox: altera: shut down RX polling timer on channel teardown

In reply to Greg Kroah-Hartman

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

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

From: Runyu Xiao <[email protected]>

[ Upstream commit 0cf10e65639cba32d05994f85e6a8f08dd0ffe08 ]

The RX polling callback unconditionally rearms the timer after it processes mailbox data. altera_mbox_shutdown() uses timer_delete_sync(), which waits for a running callback but does not prevent that callback from rearming the timer after the deletion.

Use timer_shutdown_sync() for the final polling teardown so the timer cannot be queued again while the mailbox channel is being released. The timer is reinitialized with timer_setup() on a later channel startup, so polling mode remains reusable.

Fixes f62092f6d77d ("mailbox: Add Altera mailbox driver")
Assisted-by Codex:GPT-5
---
 drivers/mailbox/mailbox-altera.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/mailbox/mailbox-altera.c +1 -1
index 17278c2571d34..7cb91413ef7fc 100644
@@ -270,7 +270,7 @@ static void altera_mbox_shutdown(struct mbox_chan *chan)
 		writel_relaxed(~0, mbox->mbox_base + MAILBOX_INTMASK_REG);
 		free_irq(mbox->irq, chan);
 	} else if (!mbox->is_sender) {
-		timer_delete_sync(&mbox->rxpoll_timer);
+		timer_shutdown_sync(&mbox->rxpoll_timer);
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#636 lore raw

PATCH 633/1257 mailbox: bcm74110: Cap rx_svc_init_list growth to prevent PMC-induced OOM

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit eb2ee504757674450a5e03e36e6b9340f064e599 ]

bcm74110_rx_push_init_msg() allocates a GFP_ATOMIC struct for every BCM_MSG_SVC_INIT word received from the PMC co-processor and appends it to rx_svc_init_list with no cap on list length. The only consumers of this list (bcm74110_rx_pop_init_msg_block / bcm74110_rx_flush_msg) are called only during probe and at shutdown respectively; after probe completes, PMC firmware can continuously inject BCM_MSG_SVC_INIT words, exhausting GFP_ATOMIC reserves and causing a whole-device denial of service.

Add BCM74110_INIT_MSG_MAX (16 entries) as the maximum list depth. bcm74110_rx_push_init_msg() now checks the count under the existing rx_svc_list_lock before allocating; if the cap is reached the message is dropped and a rate-limited warning is emitted. The new rx_svc_init_count field is decremented by bcm74110_rx_pop_init_msg() on successful dequeue and reset to zero by bcm74110_rx_flush_msg() on shutdown.

Fixes 52436007b862 ("mailbox: Add support for bcm74110")
Assisted-by Anthropic:claude-sonnet-4.6 cursor
---
 drivers/mailbox/bcm74110-mailbox.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
drivers/mailbox/bcm74110-mailbox.c +13 -0
index c8709d5099121..bec138d76914d 100644
@@ -97,6 +97,8 @@ struct bcm74110_mbox_chan {
 	int				type;
 };
 
+#define BCM74110_INIT_MSG_MAX		16
+
 struct bcm74110_mbox {
 	struct platform_device		*pdev;
 	void __iomem			*base;
@@ -105,6 +107,7 @@ struct bcm74110_mbox {
 	int				rx_chan;
 	int				rx_irq;
 	struct list_head		rx_svc_init_list;
+	unsigned int			rx_svc_init_count;
 	spinlock_t			rx_svc_list_lock;
 
 	struct mbox_controller		controller;
@@ -148,7 +151,15 @@ static void bcm74110_rx_push_init_msg(struct bcm74110_mbox *mbox, u32 val)
 	msg->msg = val;
 
 	spin_lock(&mbox->rx_svc_list_lock);
+	if (mbox->rx_svc_init_count >= BCM74110_INIT_MSG_MAX) {
+		spin_unlock(&mbox->rx_svc_list_lock);
+		kfree(msg);
+		dev_warn_ratelimited(&mbox->pdev->dev,
+				     "PMC INIT msg list full, dropping message\n");
+		return;
+	}
 	list_add_tail(&msg->list_entry, &mbox->rx_svc_init_list);
+	mbox->rx_svc_init_count++;
 	spin_unlock(&mbox->rx_svc_list_lock);
 }
 
@@ -225,6 +236,7 @@ static int bcm74110_rx_pop_init_msg(struct bcm74110_mbox *mbox, u32 func_type,
 				 list_entry) {
 		if (BCM_MSG_GET_FIELD(msg->msg, FUNC) == func_type) {
 			list_del(&msg->list_entry);
+			mbox->rx_svc_init_count--;
 			found = true;
 			break;
 		}
@@ -248,6 +260,7 @@ static void bcm74110_rx_flush_msg(struct bcm74110_mbox *mbox)
 
 	spin_lock_irqsave(&mbox->rx_svc_list_lock, flags);
 	list_splice_init(&mbox->rx_svc_init_list, &list_temp);
+	mbox->rx_svc_init_count = 0;
 	spin_unlock_irqrestore(&mbox->rx_svc_list_lock, flags);
 
 	list_for_each_entry_safe(msg, msg_tmp, &list_temp, list_entry) {
Signature · 1 line
2.53.0
author maintainer
#637 lore raw

PATCH 634/1257 mailbox: mtk-cmdq: Fix runtime PM leak in cmdq_mbox_flush()

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]>

[ Upstream commit 18e3e979826795b62e8916743bec4de660e7cb22 ]

pm_runtime_get_sync() leaves the runtime PM usage counter incremented even when it fails, but cmdq_mbox_flush() returns the error without dropping it. The same happens when the GCE thread does not drain in time and the function bails out with -EFAULT.

Undo the reference on both error paths.

Fixes b0524f7c9635 ("mailbox: mediatek: implement flush function")
---
 drivers/mailbox/mtk-cmdq-mailbox.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/mailbox/mtk-cmdq-mailbox.c +6 -1
index e523c84b48088..96462ca844715 100644
@@ -565,8 +565,10 @@ static int cmdq_mbox_flush(struct mbox_chan *chan, unsigned long timeout)
 	int ret;
 
 	ret = pm_runtime_get_sync(cmdq->mbox.dev);
-	if (ret < 0)
+	if (ret < 0) {
+		pm_runtime_put_noidle(cmdq->mbox.dev);
 		return ret;
+	}
 
 	spin_lock_irqsave(&thread->chan->lock, flags);
 	if (list_empty(&thread->task_busy_list))
@@ -603,6 +605,9 @@ static int cmdq_mbox_flush(struct mbox_chan *chan, unsigned long timeout)
 		dev_err(cmdq->mbox.dev, "Fail to wait GCE thread 0x%x done\n",
 			(u32)(thread->base - cmdq->base));
 
+		pm_runtime_mark_last_busy(cmdq->mbox.dev);
+		pm_runtime_put_autosuspend(cmdq->mbox.dev);
+
 		return -EFAULT;
 	}
 	pm_runtime_mark_last_busy(cmdq->mbox.dev);
Signature · 1 line
2.53.0
author maintainer
#638 lore raw

PATCH 635/1257 mailbox: qcom-ipcc: Guard against NULL con_priv in send_data()

In reply to Greg Kroah-Hartman

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

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

From: Anup Vishwakarma <[email protected]>

[ Upstream commit 7b3cc361b5942ac600f38e5dff7aed009be34964 ]

qcom_ipcc_mbox_shutdown() clears chan->con_priv with no locking. qcom_ipcc_mbox_send_data() dereferences the same field without checking for NULL first, so a send racing a concurrent shutdown can crash:

  mchan = chan->con_priv;
  ...
  hwirq = qcom_ipcc_get_hwirq(mchan->client_id, mchan->signal_id);

Add the same NULL guard mbox_send_message() already uses for chan->cl, and bail out before dereferencing a cleared con_priv.

To close the remaining race where send_data() reads con_priv a moment before a concurrent shutdown clears it, acquire the spinlock in qcom_ipcc_mbox_shutdown() using the modern guard(spinlock_irqsave) primitive before setting con_priv to NULL.

Fixes d6fbfdbc1274 ("mailbox: qcom-ipcc: Fix IPCC mbox channel exhaustion")
---
 drivers/mailbox/qcom-ipcc.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/mailbox/qcom-ipcc.c +6 -0
index 185b63f724d4f..387aa72aeedf1 100644
@@ -10,6 +10,7 @@
 #include <linux/mailbox_controller.h>
 #include <linux/module.h>
 #include <linux/platform_device.h>
+#include <linux/spinlock.h>
 
 #include <dt-bindings/mailbox/qcom-ipcc.h>
 
@@ -151,6 +152,9 @@ static int qcom_ipcc_mbox_send_data(struct mbox_chan *chan, void *data)
 	struct qcom_ipcc_chan_info *mchan = chan->con_priv;
 	u32 hwirq;
 
+	if (!mchan)
+		return -EINVAL;
+
 	hwirq = qcom_ipcc_get_hwirq(mchan->client_id, mchan->signal_id);
 	writel(hwirq, ipcc->base + IPCC_REG_SEND_ID);
 
@@ -159,6 +163,8 @@ static int qcom_ipcc_mbox_send_data(struct mbox_chan *chan, void *data)
 
 static void qcom_ipcc_mbox_shutdown(struct mbox_chan *chan)
 {
+	guard(spinlock_irqsave)(&chan->lock);
+
 	chan->con_priv = NULL;
 }
 
Signature · 1 line
2.53.0
author maintainer
#639 lore raw

PATCH 636/1257 m68k: Fix seccomp filtering on ColdFire and 68000

In reply to Greg Kroah-Hartman

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

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

From: Christopher Lusk <[email protected]>

[ Upstream commit 48859f8018d93bd93ef35f7430fdf5b97f2f9715 ]

m68k selects HAVE_ARCH_SECCOMP_FILTER for all configurations, but the ColdFire and 68000 syscall entry paths only branch to syscall_trace_enter() for TIF_SYSCALL_TRACE. TIF_SECCOMP alone falls through to syscall dispatch, leaving installed filters ineffective.

Test the combined TIF_SYSCALL_TRACE and TIF_SECCOMP mask in both paths and route either flag through the existing slow path. Leave the classic MMU syscall entry implementation unchanged.

Validated the combined test under QEMU mcf5208evb (ColdFire): filters denying getpid, openat, unlinkat, and reboot each returned -EPERM. A classic-MMU control (q800) denied the filtered getpid syscall both before and after this change. The 68000 path shares the same source-level omission and receives the identical masked test but was not separately emulated. Compile-tested W=1 with CONFIG_SECCOMP_FILTER=y on both m5208evb_defconfig and a custom no-MMU UCSIMM configuration; the latter built arch/m68k/68000/entry.o and vmlinux.

Fixes 6baaade15594 ("m68k: Add kernel seccomp support")
Assisted-by Claude:claude-opus-4-8
Assisted-by Codex:gpt-5.6-sol
---
 arch/m68k/68000/entry.S    | 3 ++-
 arch/m68k/coldfire/entry.S | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)
arch/m68k/68000/entry.S +2 -1
index c257cc415c478..0d3cbededc43c 100644
@@ -79,7 +79,8 @@ ENTRY(system_call)
 
 	/* Doing a trace ? */
 	getthreadinfo
-	btst	#(TIF_SYSCALL_TRACE%8),%a2@(TINFO_FLAGS+(31-TIF_SYSCALL_TRACE)/8)
+	moveb	%a2@(TINFO_FLAGS+2),%d1
+	andl	#((_TIF_SYSCALL_TRACE + _TIF_SECCOMP) >> 8),%d1
 	jne	do_trace
 	cmpl	#NR_syscalls,%d0
 	jcc	badsys
arch/m68k/coldfire/entry.S +2 -1
index 4ea08336e2fb0..d658abdc52075 100644
@@ -72,7 +72,8 @@ ENTRY(system_call)
 	movel	%d2,%a0
 	movel	%a0@,%a1		/* save top of frame */
 	movel	%sp,%a1@(TASK_THREAD+THREAD_ESP0)
-	btst	#(TIF_SYSCALL_TRACE%8),%a0@(TINFO_FLAGS+(31-TIF_SYSCALL_TRACE)/8)
+	moveb	%a0@(TINFO_FLAGS+2),%d2
+	andl	#((_TIF_SYSCALL_TRACE + _TIF_SECCOMP) >> 8),%d2
 	bnes	1f
 
 	movel	%d3,%a0
Signature · 1 line
2.53.0
author maintainer
#640 lore raw

PATCH 637/1257 USB: serial: sierra: fix urb leak on write completion

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

[ Upstream commit e7daa54802c566ed3f22e81513f84c8c9197c5d1 ]

Make sure to drop the reference taken by usb_anchor_urb() also on successful submission of delayed write URBs during runtime resume to prevent them from leaking on completion.

Fixes e6929a9020ac ("USB: support for autosuspend in sierra while online")
Cc [email protected] # 2.6.32
Cc Oliver Neukum <[email protected]>
---
 drivers/usb/serial/sierra.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/usb/serial/sierra.c +2 -1
index 6e443aacae07d..f2cc7f364d204 100644
@@ -972,12 +972,13 @@ static int sierra_submit_delayed_urbs(struct usb_serial_port *port)
 			intfdata->in_flight--;
 			usb_unanchor_urb(urb);
 			kfree(urb->transfer_buffer);
-			usb_free_urb(urb);
 
 			spin_lock(&portdata->lock);
 			portdata->outstanding_urbs--;
 			spin_unlock(&portdata->lock);
 		}
+
+		usb_put_urb(urb);
 	}
 
 	if (ec)
Signature · 1 line
2.53.0
author maintainer
#641 lore raw

PATCH 638/1257 selftests/filesystems: Fix idmapped_tmpfile layer dir ownership

In reply to Greg Kroah-Hartman

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

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

From: Bjoern Doebel <[email protected]>

[ Upstream commit 9ba6627ef6b12debd1c54443939718db63234274 ]

The recent idmapped_tmpfile selftest creates a new directory in tmpfs owned by user ID 0. It then idmaps the mount as caller [0,10000) to disk [10000,20000). The original uid 0 owner does not exist in the mapped range. As a result, mapped_caller_creates_and_links fails at the O_TMPFILE open because inode_permission() rejects MAY_WRITE access:

idmapped_tmpfile.c:145:mapped_caller_creates_and_links:
Expected fd (-1) >= 0 (0)

Chown the directory into the mapped range to satisfy the UID requirement.

Fixes d943e68edc5cb ("selftests/filesystems: test O_TMPFILE creation on idmapped mounts")
---
 tools/testing/selftests/filesystems/idmapped_tmpfile.c | 7 +++++++
 1 file changed, 7 insertions(+)
tools/testing/selftests/filesystems/idmapped_tmpfile.c +7 -0
index bc411ab8281ea..77b96d0943578 100644
@@ -91,6 +91,13 @@ FIXTURE_SETUP(idmapped_tmpfile)
 	ASSERT_EQ(mkdir(self->dir, 0777), 0);
 	/* World-writable so an unmapped caller still passes permission(). */
 	ASSERT_EQ(chmod(self->dir, 0777), 0);
+	/*
+	 * The directory itself must be inside the range the mount maps.
+	 * Left owned by 0 it has no mapping in the mount, and
+	 * inode_permission() then fails MAY_WRITE via HAS_UNMAPPED_ID()
+	 * before any of the tmpfile logic is reached, regardless of mode.
+	 */
+	ASSERT_EQ(chown(self->dir, MAP_HOST, MAP_HOST), 0);
 }
 
 FIXTURE_TEARDOWN(idmapped_tmpfile)
Signature · 1 line
2.53.0
author maintainer
#642 lore raw

PATCH 639/1257 dm-snapshot: fix crash if dm_io_client_create fails

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

[ Upstream commit 829c4d21148a205eca864429e06530319e1f92d5 ]

If dm_io_client_create() fails, it stores error into the ps->io_client variable. The code would try to free it later with dm_io_client_destroy(ps->io_client), causing an invalid pointer dereference. Fix this by setting ps->io_client = NULL.

Assisted-by Claude:claude-opus-5
---
 drivers/md/dm-snap-persistent.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/md/dm-snap-persistent.c +5 -2
index e86d929b0e951..b587ee7330562 100644
@@ -325,8 +325,11 @@ static int read_header(struct pstore *ps, int *new_snapshot)
 	}
 
 	ps->io_client = dm_io_client_create();
-	if (IS_ERR(ps->io_client))
-		return PTR_ERR(ps->io_client);
+	if (IS_ERR(ps->io_client)) {
+		r = PTR_ERR(ps->io_client);
+		ps->io_client = NULL;
+		return r;
+	}
 
 	r = alloc_area(ps);
 	if (r)
Signature · 1 line
2.53.0
author maintainer
#643 lore raw

PATCH 640/1257 ALSA: hda: cs35l41: Fix ACPI device reference leak on probe failure

In reply to Greg Kroah-Hartman

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

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

From: Ma Ke <[email protected]>

[ Upstream commit 8d70e364e866bdfca81eee24d0688fac9472cfb9 ]

cs35l41_hda_probe() takes an acpi_device through cs35l41_hda_read_acpi() and stores it in cs35l41->dacpi. Only the failures that happen later reach the err: label, which is where that reference and cs35l41->acpi_subsystem_id are released, so the early return taken when cs35l41_hda_read_acpi() fails leaves both behind.

Keep the ownership in the caller instead of dropping the reference inside cs35l41_hda_read_acpi(). That removes the need to work out whether a given failure path has already released it, and with it the double put that cs35l41_hda_parse_acpi() would otherwise cause when it fails after having released the device itself.

cs35l41_hda_parse_acpi() and the !physdev path no longer put the reference, and the early failure enters the existing err: cleanup tail through a new err_acpi label.

The label sits between the reset of the codec and the gpio cleanup, so an early failure also releases the reset and chip-select descriptors that cs35l41_hda_parse_acpi() may already have taken, while still skipping cs35l41_safe_reset() on a codec that was never brought up.

cs35l41->dacpi comes from devm_kzalloc() and is only assigned once the ACPI device has been found, so the put is a no-op when the lookup itself failed.

Found by code review.

Fixes 447106e92a0c ("ALSA: hda: cs35l41: Support mute notifications for CS35L41 HDA")
---
 sound/hda/codecs/side-codecs/cs35l41_hda.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
sound/hda/codecs/side-codecs/cs35l41_hda.c +6 -6
index 62296be45c55e..d50c3d8f5303c 100644
@@ -1907,7 +1907,6 @@ int cs35l41_hda_parse_acpi(struct cs35l41_hda *cs35l41, struct device *physdev,
 	hw_cfg->valid = false;
 	hw_cfg->gpio1.valid = false;
 	hw_cfg->gpio2.valid = false;
-	acpi_dev_put(cs35l41->dacpi);
 
 	return ret;
 }
@@ -1928,10 +1927,8 @@ static int cs35l41_hda_read_acpi(struct cs35l41_hda *cs35l41, const char *hid, i
 	cs35l41->dacpi = adev;
 	struct device *physdev __free(put_device) =
 		get_device(acpi_get_first_physical_node(adev));
-	if (!physdev) {
-		acpi_dev_put(adev);
+	if (!physdev)
 		return -ENODEV;
-	}
 
 	sub = acpi_get_subsystem_id(ACPI_HANDLE(physdev));
 	if (IS_ERR(sub))
@@ -1986,8 +1983,10 @@ int cs35l41_hda_probe(struct device *dev, const char *device_name, int id, int i
 	dev_set_drvdata(dev, cs35l41);
 
 	ret = cs35l41_hda_read_acpi(cs35l41, device_name, id);
-	if (ret)
-		return dev_err_probe(cs35l41->dev, ret, "Platform not supported\n");
+	if (ret) {
+		dev_err_probe(cs35l41->dev, ret, "Platform not supported\n");
+		goto err_acpi;
+	}
 
 	if (IS_ERR(cs35l41->reset_gpio)) {
 		ret = PTR_ERR(cs35l41->reset_gpio);
@@ -2074,6 +2073,7 @@ int cs35l41_hda_probe(struct device *dev, const char *device_name, int id, int i
 err:
 	if (cs35l41_safe_reset(cs35l41->regmap, cs35l41->hw_cfg.bst_type))
 		gpiod_set_value_cansleep(cs35l41->reset_gpio, 0);
+err_acpi:
 	gpiod_put(cs35l41->reset_gpio);
 	gpiod_put(cs35l41->cs_gpio);
 	acpi_dev_put(cs35l41->dacpi);
Signature · 1 line
2.53.0
author maintainer
#644 lore raw

PATCH 641/1257 ACPI: APEI: accumulate the queued flag across error sections

In reply to Greg Kroah-Hartman

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

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

From: Breno Leitao <[email protected]>

[ Upstream commit f341307a14895e5da056fb419a31ef7fb534ab18 ]

ghes_do_proc() walks every error section of a CPER record, and ghes_handle_arm_hw_error() walks every error-info entry of an ARM processor section. Both assign to "queued" instead of OR-ing into it, so only the last iteration counts: a later section or entry that queues no memory-failure work clears the flag an earlier one set.

Instead of reassigning the variable at every time, just do an OR, so, if there was a single match, it will return "queued" as set.

The comment above the check says "If no memory failure
work is queued", which is the semantics this patch implements. I.e, only SIGBUS if there are queue was not handled at all. If we want to SIGBUS if any event was not handled/queued at all, we will need something more sophisticated.

Fixes 7f17b4a121d0 ("ACPI: APEI: Kick the memory_failure() queue for synchronous errors")
Fixes ccb5ecdc2dde ("ACPI: APEI: fix synchronous external aborts in user-mode")
Cc All applicable <[email protected]>
---
 drivers/acpi/apei/ghes.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/acpi/apei/ghes.c +3 -3
index fe10ab0e02f68..ec2d5ca51db02 100644
@@ -603,7 +603,7 @@ static bool ghes_handle_arm_hw_error(struct acpi_hest_generic_data *gdata,
 		 * and don't filter out 'corrected' error here.
 		 */
 		if (is_cache && has_pa) {
-			queued = ghes_do_memory_failure(err_info->physical_fault_addr, flags);
+			queued |= ghes_do_memory_failure(err_info->physical_fault_addr, flags);
 			p += err_info->length;
 			continue;
 		}
@@ -951,11 +951,11 @@ static void ghes_do_proc(struct ghes *ghes,
 			atomic_notifier_call_chain(&ghes_report_chain, sev, mem_err);
 
 			arch_apei_report_mem_error(sev, mem_err);
-			queued = ghes_handle_memory_failure(gdata, sev, sync);
+			queued |= ghes_handle_memory_failure(gdata, sev, sync);
 		} else if (guid_equal(sec_type, &CPER_SEC_PCIE)) {
 			ghes_handle_aer(gdata);
 		} else if (guid_equal(sec_type, &CPER_SEC_PROC_ARM)) {
-			queued = ghes_handle_arm_hw_error(gdata, sev, sync);
+			queued |= ghes_handle_arm_hw_error(gdata, sev, sync);
 		} else if (guid_equal(sec_type, &CPER_SEC_CXL_PROT_ERR)) {
 			struct cxl_cper_sec_prot_err *prot_err = acpi_hest_get_payload(gdata);
 
Signature · 1 line
2.53.0
author maintainer
#645 lore raw

PATCH 642/1257 arm64/efi: Clear PTE_WRITE when applying EFI_MEMORY_RO

In reply to Greg Kroah-Hartman

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

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

From: Ard Biesheuvel <[email protected]>

[ Upstream commit 215d7b6622733603751f546b9faf9b84b0c281d4 ]

set_permissions() sets PTE_RDONLY for regions that the Memory Attributes Table describes as read-only, but leaves PTE_WRITE set. PTE_WRITE is the DBM bit, so when hardware dirty state management is enabled (TCR_EL1.HD), such a descriptor is writable-clean rather than read-only, and a write by the firmware will be permitted by the hardware (which marks the entry dirty) instead of faulting.

Clear PTE_WRITE as well, as pte_wrprotect() does.

---
 arch/arm64/kernel/efi.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
arch/arm64/kernel/efi.c +7 -1
index 0ec90fd1754ed..6f34aef3d04ef 100644
@@ -117,8 +117,14 @@ static int __init set_permissions(pte_t *ptep, unsigned long addr, void *data)
 	const efi_memory_desc_t *md = spd->md;
 	pte_t pte = __ptep_get(ptep);
 
+	/*
+	 * Clear PTE_WRITE as well: it doubles as the DBM bit, and leaving it
+	 * set would permit the hardware to make the mapping writable again
+	 * when TCR_EL1.HD is set.
+	 */
 	if (md->attribute & EFI_MEMORY_RO)
-		pte = set_pte_bit(pte, __pgprot(PTE_RDONLY));
+		pte = set_pte_bit(clear_pte_bit(pte, __pgprot(PTE_WRITE)),
+				  __pgprot(PTE_RDONLY));
 	if (md->attribute & EFI_MEMORY_XP)
 		pte = set_pte_bit(pte, __pgprot(PTE_PXN));
 	else if (system_supports_bti_kernel() && spd->has_bti)
Signature · 1 line
2.53.0
author maintainer
#646 lore raw

PATCH 643/1257 btrfs: zoned: fix block group reference leak in btrfs_repair_one_zone()

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]>

[ Upstream commit 886f1aa6e6b30a02901aa7f140149d466e10a873 ]

btrfs_repair_one_zone() hands the block group reference taken by btrfs_lookup_block_group() over to relocating_repair_kthread(), which drops it. However the return value of kthread_run() is not checked, so when the kernel thread fails to spawn, nothing executes the put and the block group reference is leaked.

Check kthread_run() and drop the reference if the thread failed to start.

Fixes f7ef5287a63d ("btrfs: zoned: relocate block group to repair IO failure in zoned filesystems")
---
 fs/btrfs/volumes.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
fs/btrfs/volumes.c +4 -2
index 85ea9c5d4536c..e7d3cd66a98d1 100644
@@ -8971,6 +8971,7 @@ static int relocating_repair_kthread(void *data)
 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
 {
 	struct btrfs_block_group *cache;
+	struct task_struct *task;
 
 	if (!btrfs_is_zoned(fs_info))
 		return false;
@@ -8988,8 +8989,9 @@ bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
 		return true;
 	}
 
-	kthread_run(relocating_repair_kthread, cache,
-		    "btrfs-relocating-repair");
+	task = kthread_run(relocating_repair_kthread, cache, "btrfs-relocating-repair");
+	if (IS_ERR(task))
+		btrfs_put_block_group(cache);
 
 	return true;
 }
Signature · 1 line
2.53.0
author maintainer
#647 lore raw

PATCH 644/1257 btrfs: return -ENOTTY for unknown ioctls on the control device

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]>

[ Upstream commit 9985f1643ac3f8595862e2f82108f0ccae4cf959 ]

Commit 5ab2b180884c ("btrfs: factor out validation of btrfs_ioctl_vol_args::name") made btrfs_control_ioctl() store the result of btrfs_check_ioctl_vol_args_path() in ret before it looks at the command.

However, ret is initialized to -ENOTTY and the switch has no default case, so this initial value was what an unknown command returned. As of now, every unknown ioctl on /dev/btrfs-control returns 0. A tool that tries a control ioctl which the running kernel does not have is told that the ioctl succeeded.

The issue can be reproduced with a simple C program, run as root:

    #include <fcntl.h>
    #include <stdio.h>
    #include <sys/ioctl.h>

    int main(void)
    {
            static char buf[4096];
            int fd = open("/dev/btrfs-control", O_RDWR);

            if (ioctl(fd, TCGETS, buf) < 0)
                    perror("ioctl");
            else
                    printf("ioctl succeeded\n");
            return 0;
    }

Before commit 5ab2b180884c ("btrfs: factor out validation of btrfs_ioctl_vol_args::name"), the result is:

ioctl: Inappropriate ioctl for device

After that commit, the result is:

ioctl succeeded

This patch will add a default case that returns -ENOTTY.

Fixes 5ab2b180884c ("btrfs: factor out validation of btrfs_ioctl_vol_args::name")
---
 fs/btrfs/super.c | 3 +++
 1 file changed, 3 insertions(+)
fs/btrfs/super.c +3 -0
index ddb620ac241b4..2c9b29aa59a2e 100644
@@ -2305,6 +2305,9 @@ static long btrfs_control_ioctl(struct file *file, unsigned int cmd,
 	case BTRFS_IOC_GET_SUPPORTED_FEATURES:
 		ret = btrfs_ioctl_get_supported_features((void __user*)arg);
 		break;
+	default:
+		ret = -ENOTTY;
+		break;
 	}
 
 out:
Signature · 1 line
2.53.0
author maintainer
#648 lore raw

PATCH 645/1257 mtd: rawnand: qcom: fix read location register usage in config_nand_cw_read()

In reply to Greg Kroah-Hartman

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

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

From: Gabor Juhos <[email protected]>

[ Upstream commit 94623942a66e031826756f9c92dbde9a12e2b4d2 ]

On QPIC v2 controllers, when the last codeword is being read, the read location values must be programmed into the READ_LOCATION_LAST_CW_* registers. Prior to commit 8c52932da5e6 ("mtd: rawnand: qcom: cleanup qcom_nandc driver"), the config_nand_cw_read() function did it right, but since then it always writes the read location values to the READ_LOCATION_* registers even if the actual codeword is the last one.

Change the function to always configure the registers corresponding to the actual codeword to restore the correct behaviour.

Fixes 8c52932da5e6 ("mtd: rawnand: qcom: cleanup qcom_nandc driver")
---
 drivers/mtd/nand/raw/qcom_nandc.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/mtd/nand/raw/qcom_nandc.c +5 -3
index d7642db2e2df1..170af9f26d471 100644
@@ -328,14 +328,16 @@ config_nand_cw_read(struct nand_chip *chip, bool use_ecc, int cw)
 {
 	struct qcom_nand_controller *nandc = get_qcom_nand_controller(chip);
 	struct nand_ecc_ctrl *ecc = &chip->ecc;
-
 	__le32 *reg = &nandc->regs->read_location0;
+	int reg_base = NAND_READ_LOCATION_0;
 
-	if (nandc->props->qpic_version2 && qcom_nandc_is_last_cw(ecc, cw))
+	if (nandc->props->qpic_version2 && qcom_nandc_is_last_cw(ecc, cw)) {
 		reg = &nandc->regs->read_location_last0;
+		reg_base = NAND_READ_LOCATION_LAST_CW_0;
+	}
 
 	if (nandc->props->supports_bam)
-		qcom_write_reg_dma(nandc, reg, NAND_READ_LOCATION_0, 4, NAND_BAM_NEXT_SGL);
+		qcom_write_reg_dma(nandc, reg, reg_base, 4, NAND_BAM_NEXT_SGL);
 
 	qcom_write_reg_dma(nandc, &nandc->regs->cmd, NAND_FLASH_CMD, 1, NAND_BAM_NEXT_SGL);
 	qcom_write_reg_dma(nandc, &nandc->regs->exec, NAND_EXEC_CMD, 1, NAND_BAM_NEXT_SGL);
Signature · 1 line
2.53.0
author maintainer
#649 lore raw

PATCH 646/1257 mtd: parsers: qcom: fix offset/size overflow on large partitions

In reply to Greg Kroah-Hartman

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

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

From: Weigang He <[email protected]>

[ Upstream commit 2f7fa8d90694d21dce68ceabd8383252b111cfea ]

In parse_qcomsmem_part() the partition offset and size are computed as

	parts[j].offset = le32_to_cpu(pentry->offset) * mtd->erasesize;
	parts[j].size   = le32_to_cpu(pentry->length) * mtd->erasesize;

Both le32_to_cpu() and mtd->erasesize are 32-bit (u32). The multiply is therefore evaluated in 32-bit arithmetic and the product is truncated to 32 bits before being widened and stored into the 64-bit (u64) parts[j].offset / parts[j].size fields, so the 64-bit destinations are never used at their full width.

The SMEM partition table is firmware-provided and the per-entry offset and length are not bounds-checked against the device geometry (only numparts is capped). On a sufficiently large flash, a partition whose (offset|length) * erasesize is >= 2^32 gets a silently truncated offset/size and is mapped to the wrong region of the master MTD, which can overlap or extend into an unintended area.

Cast one operand to u64 so the multiplication is performed in 64-bit and the result fits the 64-bit fields without truncation.

Found by static analysis tool CodeQL.

Fixes 803eb124e1a6 ("mtd: parsers: Add Qcom SMEM parser")
Assisted-by LLM codeql
---
 drivers/mtd/parsers/qcomsmempart.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/mtd/parsers/qcomsmempart.c +2 -2
index d4fdc46a00730..1591aea48b280 100644
@@ -143,9 +143,9 @@ static int parse_qcomsmem_part(struct mtd_info *mtd,
 			*c = tolower(*c);
 
 		parts[j].name = name;
-		parts[j].offset = le32_to_cpu(pentry->offset) * mtd->erasesize;
+		parts[j].offset = (u64)le32_to_cpu(pentry->offset) * mtd->erasesize;
 		parts[j].mask_flags = pentry->attr;
-		parts[j].size = le32_to_cpu(pentry->length) * mtd->erasesize;
+		parts[j].size = (u64)le32_to_cpu(pentry->length) * mtd->erasesize;
 		pr_debug("%d: %s offs=0x%08x size=0x%08x attr:0x%08x\n",
 			 i, pentry->name, le32_to_cpu(pentry->offset),
 			 le32_to_cpu(pentry->length), pentry->attr);
Signature · 1 line
2.53.0
author maintainer
#650 lore raw

PATCH 647/1257 xprtrdma: prevent disconnect feedback during endpoint teardown

In reply to Greg Kroah-Hartman

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

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

From: Tim Menninger <[email protected]>

[ Upstream commit 0b5bb4e586f7b0a449f4d90a524f76a3be5db355 ]

xprt_autoclose() clears XPRT_CLOSE_WAIT before invoking the transport's ->close() operation. For RPC/RDMA, ->close() calls rpcrdma_xprt_disconnect(), which disconnects the RDMA CM endpoint and drains its QP.

Since commit 31e62d25b5b8 ("xprtrdma: Simplify RPC wake-ups on connect"), RDMA_CM_EVENT_DISCONNECTED requests a SUNRPC transport disconnect. Today that path, along with failed completion handling, reaches xprt_force_disconnect() through rpcrdma_force_disconnect().

Commit c487eb7d8e41 ("xprtrdma: Clean up disconnect") later added re_force_disconnect to ensure that multiple failure indications request only one SUNRPC disconnect. However, the gate remains open when SUNRPC itself begins endpoint teardown.

If re_force_disconnect is still clear, either a CM disconnect event or a completion error can set XPRT_CLOSE_WAIT again while the current close is in progress. When the transport send lock is subsequently released, xprt_clear_locked() observes XPRT_CLOSE_WAIT and queues another autoclose.

Requesting a disconnect this way is necessary when a connection is lost unexpectedly, but not when the event was generated by rpcrdma_xprt_disconnect() itself. In that case SUNRPC is already committed to closing the transport.

Mark re_force_disconnect before initiating local endpoint teardown so that CM events and completion errors caused by that teardown cannot request another close. An unexpected error that wins the race before local endpoint teardown begins can still request a disconnect normally.

Use a fully ordered exchange so that the gate is globally closed before rdma_disconnect() can transition the QP to error and generate the callbacks that the gate suppresses.

In 30-second traces of a sustained recovery loop, without this change there were 7,693 xprt_force_disconnect() calls, 6,267 SUNRPC autocloses, and 172,892 receive-side IB_WC_WR_FLUSH_ERR completions. With this change, the same tracepoints recorded 3,512 xprt_force_disconnect() calls, 3,212 autocloses, and 131,287 receive-side flush completions. Thus QP teardown continues to produce flushed completions, but closing the disconnect gate before teardown substantially reduces their feedback into the SUNRPC close path.

Fixes 31e62d25b5b8 ("xprtrdma: Simplify RPC wake-ups on connect")
---
 net/sunrpc/xprtrdma/verbs.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
net/sunrpc/xprtrdma/verbs.c +6 -3
index be335eed329d1..54957295a6310 100644
@@ -114,9 +114,9 @@ static void rpcrdma_xprt_drain(struct rpcrdma_xprt *r_xprt)
 	rpcrdma_ep_put(ep);
 }
 
-/* Ensure xprt_force_disconnect() is invoked exactly once when a
- * connection is closed or lost. (The important thing is it needs
- * to be invoked "at least" once).
+/* Ensure xprt_force_disconnect() is invoked at most once for an
+ * unexpected endpoint failure. Local endpoint teardown closes this
+ * gate before it can generate CM events and flushed completions.
  */
 void rpcrdma_force_disconnect(struct rpcrdma_ep *ep)
 {
@@ -587,6 +587,9 @@ void rpcrdma_xprt_disconnect(struct rpcrdma_xprt *r_xprt)
 	if (!ep)
 		return;
 
+	/* Prevent teardown-generated events from requesting another close. */
+	atomic_xchg(&ep->re_force_disconnect, 1);
+
 	id = ep->re_id;
 	rc = rdma_disconnect(id);
 	trace_xprtrdma_disconnect(r_xprt, rc);
Signature · 1 line
2.53.0
author maintainer
#651 lore raw

PATCH 648/1257 xprtrdma: trim head iovec when the payload arrives via a Write chunk

In reply to Greg Kroah-Hartman

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

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

From: Yongjian Mu <[email protected]>

[ Upstream commit 9ee534a75912361308b1f956bc3e7895a082a422 ]

The upper layer sets rq_rcv_buf.head[0].iov_len from its estimate of the reply header size. For RPCSEC_GSS that estimate includes auth->au_ralign, which gss_create_new() initializes to GSS_VERF_SLACK >> 2 (25 XDR words, or 100 bytes) and which is corrected to the real verifier size only after the first reply on that rpc_auth has been unwrapped. In this case, the krb5 MIC verifier is 36 bytes, so every request encoded before the first reply completes has a head that is 64 bytes too long.

On TCP this is harmless: xdr_realign_pages() moves the excess head bytes, which are genuine reply data, into the page list. With RPC-over-RDMA and a Write chunk (sec=krb5, i.e. RPC_GSS_SVC_NONE, where DDP is allowed), the payload has already been placed directly into the page list, and the receive buffer holds only the inline part of the reply. rpcrdma_inline_fixup() clamps its local copy of the head length to the inline length but leaves head.iov_len untouched, so xdr_realign_pages() still sees iov_len > cur and shifts whatever lies past the inline reply in the receive buffer into the front of the directly-placed payload:

rpc_xdr_recvfrom: head=[...,196] page=524288 tail=[...,64]
rpc_xdr_alignment: nfsv4 READ offset=132 copied=64

The first 64 bytes returned by each such READ are incorrect (zeroed, or shifted right by 64 bytes depending on the kernel's xdr_shrink_bufhead() implementation). This is readily hit with pNFS flexfiles over RDMA and sec=krb5: the per-DS rpc_clnt gets a fresh rpc_auth whose first RPC is a large READ. Reads following the first completed reply return the expected data.

Commit cb0ae1fbb2f5 ("xprtrdma: Do not update {head, tail}.iov_len in rpcrdma_inline_fixup()") removed the head-length correction while fixing the handling of pure-inline krb5p replies.

When a Write chunk conveyed the payload, trim head.iov_len (in both rq_rcv_buf and rq_private_buf, which call_decode() expects to match) to the inline length actually received so that the XDR layer does not realign the page list. These READ replies have no trailing inline fields, and the payload is already in the page list, so the upper layer's head estimate can be safely reduced. Reduce buflen by the same amount to avoid treating unused head capacity as additional tail capacity. Pure inline replies and Reply chunk replies are unchanged.

Tested on Linux 6.8.0 and 7.3-rc4 with NFSv4.1 pNFS flexfiles over RPC/RDMA and sec=krb5.

Fixes cb0ae1fbb2f5 ("xprtrdma: Do not update {head, tail}.iov_len in rpcrdma_inline_fixup()")
---
 net/sunrpc/xprtrdma/rpc_rdma.c | 27 +++++++++++++++++++++++----
 1 file changed, 23 insertions(+), 4 deletions(-)
net/sunrpc/xprtrdma/rpc_rdma.c +23 -4
index 1285f04cdac14..7e5713367291e 100644
@@ -984,12 +984,16 @@ void rpcrdma_reset_cwnd(struct rpcrdma_xprt *r_xprt)
  * @rqst: controlling RPC request
  * @srcp: points to RPC message payload in receive buffer
  * @copy_len: remaining length of receive buffer content
- * @pad: Write chunk pad bytes needed (zero for pure inline)
+ * @writelist: bytes conveyed by the Write chunk (zero for pure inline)
  *
  * The upper layer has set the maximum number of bytes it can
  * receive in each component of rq_rcv_buf. These values are set in
  * the head.iov_len, page_len, tail.iov_len, and buflen fields.
  *
+ * For READ replies with a Write chunk, the payload is already in
+ * the page list. An overestimated head length and buflen can be
+ * reduced without moving reply data.
+ *
  * Unlike the TCP equivalent (xdr_partial_copy_from_skb), in
  * many cases this function simply updates iov_base pointers in
  * rq_rcv_buf to point directly to the received reply data, to
@@ -998,13 +1002,16 @@ void rpcrdma_reset_cwnd(struct rpcrdma_xprt *r_xprt)
  * Returns the count of bytes which had to be memcopied.
  */
 static unsigned long
-rpcrdma_inline_fixup(struct rpc_rqst *rqst, char *srcp, int copy_len, int pad)
+rpcrdma_inline_fixup(struct rpc_rqst *rqst, char *srcp, int copy_len,
+		     u32 writelist)
 {
 	unsigned long fixup_copy_count;
 	int i, npages, curlen;
 	char *destp;
 	struct page **ppages;
 	int page_base;
+	int pad = writelist & 3;
+	unsigned int delta;
 
 	/* The head iovec is redirected to the RPC reply message
 	 * in the receive buffer, to avoid a memcopy.
@@ -1016,8 +1023,20 @@ rpcrdma_inline_fixup(struct rpc_rqst *rqst, char *srcp, int copy_len, int pad)
 	 * head.iov_len bytes are copied into the page list.
 	 */
 	curlen = rqst->rq_rcv_buf.head[0].iov_len;
-	if (curlen > copy_len)
+	if (curlen > copy_len) {
+		/* These READ replies have no inline fields after the payload.
+		 * Trim the head without moving the directly-placed data.
+		 */
+		if (writelist) {
+			delta = curlen - copy_len;
+
+			rqst->rq_rcv_buf.head[0].iov_len = copy_len;
+			rqst->rq_private_buf.head[0].iov_len = copy_len;
+			rqst->rq_rcv_buf.buflen -= delta;
+			rqst->rq_private_buf.buflen -= delta;
+		}
 		curlen = copy_len;
+	}
 	srcp += curlen;
 	copy_len -= curlen;
 
@@ -1245,7 +1264,7 @@ rpcrdma_decode_msg(struct rpcrdma_xprt *r_xprt, struct rpcrdma_rep *rep,
 	base = (char *)xdr_inline_decode(xdr, 0);
 	rpclen = xdr_stream_remaining(xdr);
 	r_xprt->rx_stats.fixup_copy_count +=
-		rpcrdma_inline_fixup(rqst, base, rpclen, writelist & 3);
+		rpcrdma_inline_fixup(rqst, base, rpclen, writelist);
 
 	r_xprt->rx_stats.total_rdma_reply += writelist;
 	return rpclen + xdr_align_size(writelist);
Signature · 1 line
2.53.0
author maintainer
#652 lore raw

PATCH 649/1257 PCI: Avoid D3 on PLX PEX 8532/8533/8548 downstream ports

In reply to Greg Kroah-Hartman

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

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

From: Imre Kaloz <[email protected]>

[ Upstream commit 8e923e51892c7da91687dd5b8081ddb1f0fb395a ]

Runtime PM suspends an idle downstream port of a PLX/Broadcom PEX 8532/8533/8548 switch to D3hot, but that takes the whole switch down with it: any device behind another port of the same switch then faults with a fatal bus error on its next access, e.g. mptsas probe on a Sun Ultra 45.

This surfaced on sparc64 once commit a5fb3ff63287 ("PCI: Allow PCI bridges to go to D3Hot on all non-x86") let bridges enter D3hot. Keep these downstream ports out of D3 by setting PCI_DEV_FLAGS_NO_D3.

Fixes a5fb3ff63287 ("PCI: Allow PCI bridges to go to D3Hot on all non-x86")
---
 drivers/pci/quirks.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
drivers/pci/quirks.c +18 -0
index edf035d251cc2..d4fcc336bc2a9 100644
@@ -2387,6 +2387,24 @@ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050,
 DECLARE_PCI_FIXUP_HEADER(0x1402, 0x2000, quirk_plx_pci9050);
 DECLARE_PCI_FIXUP_HEADER(0x1402, 0x2600, quirk_plx_pci9050);
 
+/*
+ * An idle downstream port of a PLX/Broadcom PEX 8532/8533/8548 switch
+ * autosuspends into D3hot, and that takes the whole switch down with
+ * it -- any device behind another port of the same switch then sees a
+ * fatal, non-recoverable bus fault on its next access. Keep these
+ * ports out of D3 entirely.
+ */
+static void quirk_plx_pex_no_d3(struct pci_dev *dev)
+{
+	if (pci_pcie_type(dev) == PCI_EXP_TYPE_DOWNSTREAM) {
+		dev->dev_flags |= PCI_DEV_FLAGS_NO_D3;
+		pci_info(dev, "avoiding D3 on this downstream port\n");
+	}
+}
+DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_PLX, 0x8532, quirk_plx_pex_no_d3);
+DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_PLX, 0x8533, quirk_plx_pex_no_d3);
+DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_PLX, 0x8548, quirk_plx_pex_no_d3);
+
 static void quirk_netmos(struct pci_dev *dev)
 {
 	unsigned int num_parallel = (dev->subsystem_device & 0xf0) >> 4;
Signature · 1 line
2.53.0
author maintainer
#653 lore raw

PATCH 650/1257 PCI: vmd: Flush DMA writes before handling MSI on Meteor Lake

In reply to Greg Kroah-Hartman

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

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

From: Rickey Bartlett <[email protected]>

[ Upstream commit 7307899e381cb0c16245793a4adde7491d73a2b3 ]

Per the Intel Core Ultra Processor Specification Update
(ID 792254 of 9/1/2026), the Meteor Lake VMD (8086:7d0b) is affected by an MSI erratum:

MTL016: MSI from VMD-Owned Device May Pass Memory Write

Problem When the storage subsystem is configured to operate in RAID
0 or 1 mode, a Message Signaled Interrupt (MSI) from an Intel® Volume Management Device (Intel® VMD) owned device may interrupt a core before a previous write from the device is completed.

Workaround None identified. The VMD MSI interrupt-handler should
initially perform a dummy register read to the MSI initiator device prior to any writes to ensure proper PCIe ordering.

The VMD can signal its MSI before the posted writes carrying a child device's DMA data have landed in memory. vmd_irq() then demuxes to the child handler while the child's completion queue is not yet coherent, so the handler observes no completion and returns without consuming it. The I/O is only recovered when the block layer timeout expires and polls the queue:

nvme nvme0: I/O tag 253 (50fd) QID 1 timeout, completion polled

The practical effect is therefore not a lost I/O but a 30 second stall of the entire storage stack, repeated under any sustained read load.

This was originally diagnosed and fixed by Kai-Heng Feng in September 2024 [1]. That patch used udelay(4); Keith Busch objected that the delay is merely a side effect of the read, and that flushing the pending device-to-host writes is what the erratum actually requires. Kai-Heng agreed to respin with a dummy register read. The thread then stalled on an open question from Manivannan Sadhasivam [2]: whether the read must target the child device (the "MSI initiator" named by the erratum) rather than the VMD, and whether the workaround belongs in the NVMe driver instead. No revision followed, and the erratum has remained unmitigated in mainline since.

This implements the flush read Keith asked for, and answers the open question empirically: the read MUST complete at the initiating child device. A read of the VMD's own config BAR was tried first and does not help - it terminates at the VMD and never traverses the downstream link, so it does not order against the child's posted writes (measured:
timeout rate unchanged). Reading the initiator's config space does order correctly: per PCIe ordering rules the read completion cannot pass the device's earlier posted writes, so returning from the read guarantees the completion queue entry is visible.

The initiator's config address is captured per-IRQ at MSI allocation time from the requesting device, so the hot path adds one config read only on affected parts, and only for vectors owned by a child device. The read is serialized with cfg_lock like all other VMD config access. No NVMe driver change is needed.

Measured on a Dell Pro Max 14 MC14250 (Meteor Lake, VMD 8086:7d0b, KIOXIA BG6 512GB, 7.0.0-30-generic). The drive is healthy (46C, 0 media errors, 2% used) and ASPM is disabled on the link with all L1 substates off, so neither ASPM nor APST is involved.

Dropping caches and reading 3000 shared libraries, measuring /proc/pressure/io "full" (every task on the system blocked on I/O), with nvme_core.io_timeout=5:

  unpatched:      round 1  wall 37.4s   full I/O stall 32.6s   timeouts 0
                  round 2  wall 30.6s   full I/O stall 28.7s   timeouts 1
                  round 3  wall 30.3s   full I/O stall 27.4s   timeouts 1
  VMD-BAR read:   round 1  wall 44.8s   full I/O stall 38.6s   timeouts 8
  (insufficient)  round 2  wall 234.8s  full I/O stall 207.9s  timeouts 37
                  round 3  wall 3.6s    full I/O stall 0.8s    timeouts 0
  this patch:     round 1  wall 3.6s    full I/O stall 1.3s    timeouts 0
                  round 2  wall 3.6s    full I/O stall 1.3s    timeouts 0
                  round 3  wall 3.6s    full I/O stall 1.4s    timeouts 0

Before any workaround, 208 seconds of total-system I/O stall accumulated in the first 13 minutes of uptime, roughly 27% of wall clock. Userspace experiences this as GUI applications taking 30-60+ seconds to start while throughput between stalls looks entirely normal (1.9 GB/s QD1) - which is what makes the fault easy to misattribute to ASPM or to the drive.

[1] https://lore.kernel.org/[email protected]/
[2] https://lore.kernel.org/20240913111142.4cgrmirofhhgrbqm@thinkpad/

---
 drivers/pci/controller/vmd.c | 52 ++++++++++++++++++++++++++++++++++--
 1 file changed, 50 insertions(+), 2 deletions(-)
drivers/pci/controller/vmd.c +50 -2
index 241023ecf6774..e45ef8cb16e47 100644
@@ -92,6 +92,22 @@ enum vmd_features {
 	 * referred to as MEMBAR2 or MSI-X BAR.
 	 */
 	VMD_FEAT_USE_BIOS_INFO		= (1 << 6),
+
+	/*
+	 * Meteor Lake VMD (device ID 0x7d0b) is affected by erratum MTL016:
+	 * the VMD may signal its MSI before the posted writes that carry the
+	 * child device's DMA data have landed in memory.  The demuxed handler
+	 * then runs against a not-yet-coherent completion queue and misses the
+	 * completion entirely, so the I/O is only recovered when the block
+	 * layer timeout fires and polls the queue ("timeout, completion
+	 * polled").  Intel's documented workaround is to issue a dummy read
+	 * to the MSI initiator (the child device) before handling the
+	 * interrupt: the read completion cannot pass the device's earlier
+	 * posted writes, so it pulls them into memory per PCIe ordering
+	 * rules.  A read that terminates at the VMD itself does not order
+	 * against the child's writes and is not sufficient (measured).
+	 */
+	VMD_FEAT_INTERRUPT_QUIRK	= (1 << 7),
 };
 
 #define VMD_BIOS_PM_QUIRK_LTR	0x1003	/* 3145728 ns */
@@ -114,6 +130,9 @@ static DEFINE_RAW_SPINLOCK(list_lock);
  * @irq:	back pointer to parent.
  * @enabled:	true if driver enabled IRQ
  * @virq:	the virtual IRQ value provided to the requesting driver.
+ * @flush_addr:	config space address of the initiating device, read before
+ *		demuxing to flush its posted writes (MTL016); NULL if the
+ *		VMD is not affected.
  *
  * Every MSI/MSI-X IRQ requested for a device in a VMD domain will be mapped to
  * a VMD IRQ using this structure.
@@ -123,8 +142,14 @@ struct vmd_irq {
 	struct vmd_irq_list	*irq;
 	bool			enabled;
 	unsigned int		virq;
+	void __iomem		*flush_addr;
 };
 
+struct vmd_dev;
+
+static void __iomem *vmd_cfg_addr(struct vmd_dev *vmd, struct pci_bus *bus,
+				  unsigned int devfn, int reg, int len);
+
 /**
  * struct vmd_irq_list - list of driver requested IRQs mapping to a VMD vector
  * @irq_list:	the list of irq's the VMD one demuxes to.
@@ -132,12 +157,15 @@ struct vmd_irq {
  * @count:	number of child IRQs assigned to this vector; used to track
  *		sharing.
  * @virq:	The underlying VMD Linux interrupt number
+ * @vmd:	back pointer to the owning VMD device; serializes the MTL016
+ *		flush read against other config space access.
  */
 struct vmd_irq_list {
 	struct list_head	irq_list;
 	struct srcu_struct	srcu;
 	unsigned int		count;
 	unsigned int		virq;
+	struct vmd_dev		*vmd;
 };
 
 struct vmd_dev {
@@ -295,6 +323,13 @@ static int vmd_msi_alloc(struct irq_domain *domain, unsigned int virq,
 		INIT_LIST_HEAD(&vmdirq->node);
 		vmdirq->irq = vmd_next_irq(vmd, desc);
 		vmdirq->virq = virq + i;
+		if (vmd->features & VMD_FEAT_INTERRUPT_QUIRK) {
+			struct pci_dev *pdev = msi_desc_to_pci_dev(desc);
+
+			vmdirq->flush_addr = vmd_cfg_addr(vmd, pdev->bus,
+							  pdev->devfn,
+							  PCI_VENDOR_ID, 2);
+		}
 
 		irq_domain_set_info(domain, virq + i, vmdirq->irq->virq,
 				    &vmd_msi_controller, vmdirq,
@@ -756,8 +791,20 @@ static irqreturn_t vmd_irq(int irq, void *data)
 	int idx;
 
 	idx = srcu_read_lock(&irqs->srcu);
-	list_for_each_entry_rcu(vmdirq, &irqs->irq_list, node)
+	list_for_each_entry_rcu(vmdirq, &irqs->irq_list, node) {
+		/*
+		 * MTL016: the MSI may have outrun the initiating device's
+		 * posted writes (e.g. its NVMe completion entry).  A read
+		 * that completes at the initiator flushes them, so the
+		 * demuxed handler observes a coherent completion queue.
+		 * The value is discarded; only the ordering matters.
+		 */
+		if (vmdirq->flush_addr) {
+			guard(raw_spinlock)(&irqs->vmd->cfg_lock);
+			readw(vmdirq->flush_addr);
+		}
 		generic_handle_irq(vmdirq->virq);
+	}
 	srcu_read_unlock(&irqs->srcu, idx);
 
 	return IRQ_HANDLED;
@@ -788,6 +835,7 @@ static int vmd_alloc_irqs(struct vmd_dev *vmd)
 			return err;
 
 		INIT_LIST_HEAD(&vmd->irqs[i].irq_list);
+		vmd->irqs[i].vmd = vmd;
 		vmd->irqs[i].virq = pci_irq_vector(dev, i);
 		err = devm_request_irq(&dev->dev, vmd->irqs[i].virq,
 				       vmd_irq, IRQF_NO_THREAD,
@@ -1250,7 +1298,7 @@ static const struct pci_device_id vmd_ids[] = {
 	{PCI_VDEVICE(INTEL, 0xa77f),
 		.driver_data = VMD_FEATS_CLIENT,},
 	{PCI_VDEVICE(INTEL, 0x7d0b),
-		.driver_data = VMD_FEATS_CLIENT,},
+		.driver_data = VMD_FEATS_CLIENT | VMD_FEAT_INTERRUPT_QUIRK,},
 	{PCI_VDEVICE(INTEL, 0xad0b),
 		.driver_data = VMD_FEATS_CLIENT,},
 	{PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_VMD_9A0B),
Signature · 1 line
2.53.0
author maintainer
#654 lore raw

PATCH 651/1257 PCI: vmd: Flush DMA writes before handling MSI on Arrow Lake

In reply to Greg Kroah-Hartman

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

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

From: Vladimir Nedoshivin <[email protected]>

[ Upstream commit 2c88c2dc18528489b403fe95741f5731e292f7ba ]

Per the Intel Core Ultra Processors (Series 2) Specification Update (ID 834774 of 9/1/2026), the Arrow Lake VMD device 0xad0b is affected by an MSI erratum:

ARL004: MSI from VMD-Owned Device May Pass Memory Write

Problem When the storage subsystem is configured to operate in RAID
0 or 1 mode, a Message Signaled Interrupt (MSI) from an Intel® Volume Management Device (Intel® VMD) owned device may interrupt a core before a previous write from the device is completed.

Workaround None identified. The VMD MSI interrupt-handler should
initially perform a dummy register read to the MSI initiator device prior to any writes to ensure proper PCIe ordering.

The existing VMD_FEAT_INTERRUPT_QUIRK implements Intel's documented workaround by issuing a configuration-space read to the MSI initiator before dispatching the interrupt.

Enable the existing quirk for 0xad0b as well as 0x7d0b and make the comments describe both MTL016 and ARL004.

Tested on an MSI Vector 17 HX AI with Intel VMD 8086:ad0b and an NVMe device behind VMD. With the quirk enabled, the NVMe completion stalls observed without the workaround are no longer reproduced.

---
 drivers/pci/controller/vmd.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/pci/controller/vmd.c +4 -3
index e45ef8cb16e47..9d97a832785ee 100644
@@ -94,7 +94,8 @@ enum vmd_features {
 	VMD_FEAT_USE_BIOS_INFO		= (1 << 6),
 
 	/*
-	 * Meteor Lake VMD (device ID 0x7d0b) is affected by erratum MTL016:
+	 * Some Intel VMD devices are affected by interrupt ordering errata,
+	 * including MTL016 (0x7d0b) and ARL004 (0xad0b):
 	 * the VMD may signal its MSI before the posted writes that carry the
 	 * child device's DMA data have landed in memory.  The demuxed handler
 	 * then runs against a not-yet-coherent completion queue and misses the
@@ -131,7 +132,7 @@ static DEFINE_RAW_SPINLOCK(list_lock);
  * @enabled:	true if driver enabled IRQ
  * @virq:	the virtual IRQ value provided to the requesting driver.
  * @flush_addr:	config space address of the initiating device, read before
- *		demuxing to flush its posted writes (MTL016); NULL if the
+ *		demuxing to flush its posted writes; NULL if the
  *		VMD is not affected.
  *
  * Every MSI/MSI-X IRQ requested for a device in a VMD domain will be mapped to
@@ -1300,7 +1301,7 @@ static const struct pci_device_id vmd_ids[] = {
 	{PCI_VDEVICE(INTEL, 0x7d0b),
 		.driver_data = VMD_FEATS_CLIENT | VMD_FEAT_INTERRUPT_QUIRK,},
 	{PCI_VDEVICE(INTEL, 0xad0b),
-		.driver_data = VMD_FEATS_CLIENT,},
+		.driver_data = VMD_FEATS_CLIENT | VMD_FEAT_INTERRUPT_QUIRK,},
 	{PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_VMD_9A0B),
 		.driver_data = VMD_FEATS_CLIENT,},
 	{PCI_VDEVICE(INTEL, 0xb60b),
Signature · 1 line
2.53.0
author maintainer
#655 lore raw

PATCH 652/1257 mm/damon/sysfs-schemes: read sysfs_filter->addr_range only once

In reply to Greg Kroah-Hartman

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

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

From: SJ Park <[email protected]>

[ Upstream commit 60e58be27d5e16d35e0728298f994dcae9f208a5 ]

Patch series "mm/damon: move damos filter range arguments validation to core".

DAMOS filter range arguments are being validated in the DAMON sysfs interface. Some of those have minor time-of-check to time-of-use (TOCTOU) bugs. In future, other callers might have duplicated validations with similar bugs.

Fix the bugs and further refactor the code to move the validation to the core layer. Also add kunit test cases for the validations.

Patches 1 and 2 fix the existing TOCTOU bugs. Patches 3 and 4 adds the validation in the core layer. Patch 5 drops the replicated validation in DAMON sysfs interface. Patch 6 further cleanup the code. Patches 7 and 8 extends kunit tests to test the validation.

This patch (of 8):

DAMON sysfs interface reads the user-provided address range arguments for addr type DAMOS filter twice. Once for validation, and once again for assignments to the variable that will be passed to the core layer. If the user updates the argument in parallel, an invalid address range could be passed to the core layer. Avoid it by doing the assignments first, and then validating the assigned variables before passing those to the core layer.

User impact of the bug should be trivial. From the core layer's perspective, the invalid address range is not really invalid. It just works as having a weird address range. No critical issues such as a crash or a leak could happen. And sane users ain't do such parallel arguments update anyway. If they do, such racy behavior is arguably somewhat expected and deserved. That said, there is no reason to keep such races.

Fixes 2f1abcfccd86 ("mm/damon/sysfs-schemes: support address range type DAMOS filter")
Cc Brendan Higgins <[email protected]>
Cc David Gow <[email protected]>
Cc Usama Arif <[email protected]>
---
 mm/damon/sysfs-schemes.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
mm/damon/sysfs-schemes.c +3 -3
index 32f495a96b17a..974c456a9e099 100644
@@ -2822,12 +2822,12 @@ static int damon_sysfs_add_scheme_filters(struct damos *scheme,
 				return err;
 			}
 		} else if (filter->type == DAMOS_FILTER_TYPE_ADDR) {
-			if (sysfs_filter->addr_range.end <
-					sysfs_filter->addr_range.start) {
+			filter->addr_range = sysfs_filter->addr_range;
+			if (filter->addr_range.end <
+					filter->addr_range.start) {
 				damos_destroy_filter(filter);
 				return -EINVAL;
 			}
-			filter->addr_range = sysfs_filter->addr_range;
 		} else if (filter->type == DAMOS_FILTER_TYPE_TARGET) {
 			filter->target_idx = sysfs_filter->target_idx;
 		} else if (filter->type == DAMOS_FILTER_TYPE_HUGEPAGE_SIZE) {
Signature · 1 line
2.53.0
author maintainer
#656 lore raw

PATCH 653/1257 mm/damon/core: return an error from damos_commit_filter_arg()

In reply to Greg Kroah-Hartman

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

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

From: SJ Park <[email protected]>

[ Upstream commit 6f276422aded370174edea69549ebe6b1683ffcc ]

damos_commit_filter_arg() is supposed to always succeed. It may not in future, for example, if the given filter is invalid. Prepare the case by modifying its signature to return an error when it failed. Also pipe the return value to its callers and let them handle the error.

---
 mm/damon/core.c | 41 ++++++++++++++++++++++++++++-------------
 1 file changed, 28 insertions(+), 13 deletions(-)
mm/damon/core.c +28 -13
index 0a0fdff279d86..a4542a49ff80a 100644
@@ -1244,7 +1244,7 @@ static struct damos_filter *damos_nth_ops_filter(int n, struct damos *s)
 	return NULL;
 }
 
-static void damos_commit_filter_arg(
+static int damos_commit_filter_arg(
 		struct damos_filter *dst, struct damos_filter *src)
 {
 	switch (dst->type) {
@@ -1263,28 +1263,32 @@ static void damos_commit_filter_arg(
 	default:
 		break;
 	}
+	return 0;
 }
 
-static void damos_commit_filter(
+static int damos_commit_filter(
 		struct damos_filter *dst, struct damos_filter *src)
 {
 	dst->type = src->type;
 	dst->matching = src->matching;
 	dst->allow = src->allow;
-	damos_commit_filter_arg(dst, src);
+	return damos_commit_filter_arg(dst, src);
 }
 
 static int damos_commit_core_filters(struct damos *dst, struct damos *src)
 {
 	struct damos_filter *dst_filter, *next, *src_filter, *new_filter;
-	int i = 0, j = 0;
+	int i = 0, j = 0, err;
 
 	damos_for_each_core_filter_safe(dst_filter, next, dst) {
 		src_filter = damos_nth_core_filter(i++, src);
-		if (src_filter)
-			damos_commit_filter(dst_filter, src_filter);
-		else
+		if (src_filter) {
+			err = damos_commit_filter(dst_filter, src_filter);
+			if (err)
+				return err;
+		} else {
 			damos_destroy_filter(dst_filter);
+		}
 	}
 
 	damos_for_each_core_filter_safe(src_filter, next, src) {
@@ -1296,7 +1300,11 @@ static int damos_commit_core_filters(struct damos *dst, struct damos *src)
 				src_filter->allow);
 		if (!new_filter)
 			return -ENOMEM;
-		damos_commit_filter_arg(new_filter, src_filter);
+		err = damos_commit_filter_arg(new_filter, src_filter);
+		if (err) {
+			damos_destroy_filter(new_filter);
+			return err;
+		}
 		damos_add_filter(dst, new_filter);
 	}
 	return 0;
@@ -1305,14 +1313,17 @@ static int damos_commit_core_filters(struct damos *dst, struct damos *src)
 static int damos_commit_ops_filters(struct damos *dst, struct damos *src)
 {
 	struct damos_filter *dst_filter, *next, *src_filter, *new_filter;
-	int i = 0, j = 0;
+	int i = 0, j = 0, err;
 
 	damos_for_each_ops_filter_safe(dst_filter, next, dst) {
 		src_filter = damos_nth_ops_filter(i++, src);
-		if (src_filter)
-			damos_commit_filter(dst_filter, src_filter);
-		else
+		if (src_filter) {
+			err = damos_commit_filter(dst_filter, src_filter);
+			if (err)
+				return err;
+		} else {
 			damos_destroy_filter(dst_filter);
+		}
 	}
 
 	damos_for_each_ops_filter_safe(src_filter, next, src) {
@@ -1324,7 +1335,11 @@ static int damos_commit_ops_filters(struct damos *dst, struct damos *src)
 				src_filter->allow);
 		if (!new_filter)
 			return -ENOMEM;
-		damos_commit_filter_arg(new_filter, src_filter);
+		err = damos_commit_filter_arg(new_filter, src_filter);
+		if (err) {
+			damos_destroy_filter(new_filter);
+			return err;
+		}
 		damos_add_filter(dst, new_filter);
 	}
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#657 lore raw

PATCH 654/1257 mm/damon/core-kunit: extend damos_commit_filter_for() for wrong input

In reply to Greg Kroah-Hartman

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

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

From: SJ Park <[email protected]>

[ Upstream commit a1c7fdaf165755fff928a6c25b69d7e0966b6910 ]

damos_commit_filter_for() supposes damos_commit_filter() to always succeed with given inputs. damos_commit_filter() could return an error for invalid inputs. Existing callers always pass only valid inputs, but they may pass invalid inputs in future, for test purposes. Extend the function to be able to be used for wrong inputs-caused error testing.

---
 mm/damon/tests/core-kunit.h | 24 +++++++++++++++---------
 1 file changed, 15 insertions(+), 9 deletions(-)
mm/damon/tests/core-kunit.h +15 -9
index 65443aba03300..0d09a081cd84a 100644
@@ -1062,9 +1062,15 @@ static void damos_test_commit_dests(struct kunit *test)
 }
 
 static void damos_test_commit_filter_for(struct kunit *test,
-		struct damos_filter *dst, struct damos_filter *src)
+		struct damos_filter *dst, struct damos_filter *src,
+		bool expect_fail)
 {
-	damos_commit_filter(dst, src);
+	int err;
+
+	err = damos_commit_filter(dst, src);
+	KUNIT_EXPECT_EQ(test, err != 0, expect_fail);
+	if (expect_fail)
+		return;
 	KUNIT_EXPECT_EQ(test, dst->type, src->type);
 	KUNIT_EXPECT_EQ(test, dst->matching, src->matching);
 	KUNIT_EXPECT_EQ(test, dst->allow, src->allow);
@@ -1103,47 +1109,47 @@ static void damos_test_commit_filter(struct kunit *test)
 			.type = DAMOS_FILTER_TYPE_ANON,
 			.matching = true,
 			.allow = true,
-			});
+			}, false);
 	damos_test_commit_filter_for(test, &dst,
 			&(struct damos_filter){
 			.type = DAMOS_FILTER_TYPE_MEMCG,
 			.matching = false,
 			.allow = false,
 			.memcg_id = 123,
-			});
+			}, false);
 	damos_test_commit_filter_for(test, &dst,
 			&(struct damos_filter){
 			.type = DAMOS_FILTER_TYPE_YOUNG,
 			.matching = true,
 			.allow = true,
-			});
+			}, false);
 	damos_test_commit_filter_for(test, &dst,
 			&(struct damos_filter){
 			.type = DAMOS_FILTER_TYPE_HUGEPAGE_SIZE,
 			.matching = false,
 			.allow = false,
 			.sz_range = {.min = 234, .max = 345},
-			});
+			}, false);
 	damos_test_commit_filter_for(test, &dst,
 			&(struct damos_filter){
 			.type = DAMOS_FILTER_TYPE_UNMAPPED,
 			.matching = true,
 			.allow = true,
-			});
+			}, false);
 	damos_test_commit_filter_for(test, &dst,
 			&(struct damos_filter){
 			.type = DAMOS_FILTER_TYPE_ADDR,
 			.matching = false,
 			.allow = false,
 			.addr_range = {.start = 456, .end = 567},
-			});
+			}, false);
 	damos_test_commit_filter_for(test, &dst,
 			&(struct damos_filter){
 			.type = DAMOS_FILTER_TYPE_TARGET,
 			.matching = true,
 			.allow = true,
 			.target_idx = 6,
-			});
+			}, false);
 }
 
 static void damos_test_help_initailize_scheme(struct damos *scheme)
Signature · 1 line
2.53.0
author maintainer
#658 lore raw

PATCH 655/1257 mm/damon/core-kunit: test invalid damos filter commits

In reply to Greg Kroah-Hartman

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

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

From: SJ Park <[email protected]>

[ Upstream commit 409d2ab6d98209c30d45123920721710475a30b4 ]

Add test cases for testing the validation of damos filter arguments in commit time.

---
 mm/damon/tests/core-kunit.h | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
mm/damon/tests/core-kunit.h +14 -0
index 0d09a081cd84a..062332fe847ce 100644
@@ -1130,6 +1130,13 @@ static void damos_test_commit_filter(struct kunit *test)
 			.allow = false,
 			.sz_range = {.min = 234, .max = 345},
 			}, false);
+	damos_test_commit_filter_for(test, &dst,
+			&(struct damos_filter){
+			.type = DAMOS_FILTER_TYPE_HUGEPAGE_SIZE,
+			.matching = false,
+			.allow = false,
+			.sz_range = {.min = 456, .max = 123},
+			}, true);
 	damos_test_commit_filter_for(test, &dst,
 			&(struct damos_filter){
 			.type = DAMOS_FILTER_TYPE_UNMAPPED,
@@ -1143,6 +1150,13 @@ static void damos_test_commit_filter(struct kunit *test)
 			.allow = false,
 			.addr_range = {.start = 456, .end = 567},
 			}, false);
+	damos_test_commit_filter_for(test, &dst,
+			&(struct damos_filter){
+			.type = DAMOS_FILTER_TYPE_ADDR,
+			.matching = false,
+			.allow = false,
+			.addr_range = {.start = 567, .end = 456},
+			}, true);
 	damos_test_commit_filter_for(test, &dst,
 			&(struct damos_filter){
 			.type = DAMOS_FILTER_TYPE_TARGET,
Signature · 1 line
2.53.0
maintainer
#659 lore raw

Re: [PATCH 7.3 0655/1257] mm/damon/core-kunit: test invalid damos filter commits

Hi Greg,

Quoted 1 line · On Sat, 7 Nov 2026 08:49:11 -0500 Greg Kroah-Hartman…

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

TL;DR: Please drop this. It has wrong Cc: stable@ tag.

Quoted 9 lines

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

From: SJ Park <[email protected]>

[ Upstream commit 409d2ab6d98209c30d45123920721710475a30b4 ]

Add test cases for testing the validation of damos filter arguments in commit time.

This patch is for testing commit 1bfb9384ae0e ("mm/damon/core: disallow max < min damos filter range arguments commit"), which does not exist in 7.3.y. Hence this patch is making DAMON kunit fails.

Quoted 8 lines

I didn't intend this to be applied to stable@. My original patch [1] hence doesn't have Cc: stable@. But I show Cc: stable@ tag in the upstream commit. Seems Andrew added Cc: stable@ while applying it to mm.git and I missed it. Sorry for not catching this early.

So, this patch is not really meant to be picked into stable@, and only causing the kunit failure. Could you please drop this?

[1] https://lore.kernel.org/[email protected]

Thanks,
SJ

[...]

maintainer
#660 lore raw

Re: [PATCH 7.3 0655/1257] mm/damon/core-kunit: test invalid damos filter commits

Quoted 31 lines · On Sat, 07 Nov 2026 10:32:10 -0800 SJ Park <[email protected]> wrote:

Hi Greg,

Quoted 1 line · On Sat, 7 Nov 2026 08:49:11 -0500 Greg Kroah-Hartman…

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

TL;DR: Please drop this. It has wrong Cc: stable@ tag.

Quoted 9 lines

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

From: SJ Park <[email protected]>

[ Upstream commit 409d2ab6d98209c30d45123920721710475a30b4 ]

Add test cases for testing the validation of damos filter arguments in commit time.

This patch is for testing commit 1bfb9384ae0e ("mm/damon/core: disallow max < min damos filter range arguments commit"), which does not exist in 7.3.y. Hence this patch is making DAMON kunit fails.

Quoted 8 lines
Quoted 7 lines

I didn't intend this to be applied to stable@. My original patch [1] hence doesn't have Cc: stable@. But I show Cc: stable@ tag in the upstream commit. Seems Andrew added Cc: stable@ while applying it to mm.git and I missed it. Sorry for not catching this early.

So, this patch is not really meant to be picked into stable@, and only causing the kunit failure. Could you please drop this?

FWIW, the patch was posted as a part of a series that have a few Cc: stable@ patches. I did so because Cc: stable@ patches are only for minor bug fixes that does not require the fast path of hotfixes. Apparently it only confused Andrew or his script. Sorry about that. I will not mix Cc: stable@ patches with non-Cc: stable@ patches from the next time.

Quoted 9 lines

[1] https://lore.kernel.org/[email protected]

Thanks,
SJ

[...]

Thanks,
SJ

maintainer
#661 lore raw

Re: [PATCH 7.3 0655/1257] mm/damon/core-kunit: test invalid damos filter commits

In reply to SJ Park
Quoted 1 line

TL;DR: Please drop this. It has wrong Cc: stable@ tag.

Thanks. Dropped "mm/damon/core-kunit: test invalid damos filter commits" from the 7.3 queue, along with its two preparation patches:

- mm/damon/core-kunit: extend damos_commit_filter_for() for wrong input
- mm/damon/core: return an error from damos_commit_filter_arg()

I also dropped "mm/damon/tests/core-kunit: test the size charged for a filter-trimmed region" from the 6.18 and 6.12 queues. It stays in 7.3, where it builds and its fix is queued. The 7.3 pair 29c6084658af + df7d9a0f8d91 also stays queued together.

Signature · 2 lines
Thanks,
Sasha
author maintainer
#662 lore raw

PATCH 656/1257 proc/task_mmu: handle special PMDs in clear_refs and pagemap

In reply to Greg Kroah-Hartman

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

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

From: Gregory Price <[email protected]>

[ Upstream commit d350956d829f4b620faf294c86116de640f1518c ]

mshv_vtl_low can install a special PMD from a PFN supplied in the mmap file offset. That PFN need not have a memmap entry. Reading /proc/PID/pagemap or writing /proc/PID/clear_refs for such a mapping oopses the kernel.

With a test driver mapping the PFN at the 1 TiB mark:

echo 1 > /proc/self/clear_refs

  BUG: unable to handle page fault for address: fffffb5b80000008
  #PF: supervisor read access in kernel mode
  #PF: error_code(0x0000) - not-present page
  RIP: 0010:clear_refs_pte_range+0xb1/0x1e0
  Call Trace:
   walk_pgd_range+0x50a/0xad0
   __walk_page_range+0x6a/0x1d0
   walk_page_range_mm_unsafe+0x193/0x230
   clear_refs_write+0x18e/0x3f0

pread(pagemap_fd, buf, 512 * 8, addr / PAGE_SIZE * 8)

  BUG: unable to handle page fault for address: fffff57840000008
  RIP: 0010:pagemap_pmd_range+0x3cf/0x6b0
  Call Trace:
   walk_pgd_range+0x50a/0xad0
   __walk_page_range+0x6a/0x1d0
   walk_page_range_mm_unsafe+0x193/0x230
   pagemap_read+0x1dc/0x350

clear_refs_pte_range() passes the PMD to pmd_folio(), while pagemap_pmd_range_thp() uses pmd_page() followed by page_folio().

Both paths assume the PFN has a struct page and dereference bad address.

Use vm_normal_folio_pmd() and vm_normal_page_pmd() so clear_refs skips folio operations and pagemap skips folio-derived flags for special PMDs. This matches the PTE paths, which already use vm_normal_folio() and vm_normal_page().

User-facing notes:
- Pagemap still reports PM_PRESENT and the PFN to a CAP_SYS_ADMIN reader.

- For a special PMD backed by a valid memmap entry and for the huge zero PMD, PM_FILE changes from set to clear.

- PM_MMAP_EXCLUSIVE is already clear in both cases.

- The output for an anonymous THP is unchanged.

Tested in QEMU with the test driver on broken and fixed kernels. Both proc operations oops before the fix and return 0 after it.

This is technically reachable via mshv_vtl_low, so I tagged it stable.

Fixes 3c8e44c9b369 ("mm: mark special bits for huge pfn mappings when inject")
Assisted-by LLM
Cc Jann Horn <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Peter Xu <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc <[email protected]> # v6.19+
---
 fs/proc/task_mmu.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
fs/proc/task_mmu.c +4 -2
index dd025474b0fc9..a2db957aa7996 100644
@@ -1786,7 +1786,9 @@ static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr,
 		if (!pmd_present(*pmd))
 			goto out;
 
-		folio = pmd_folio(*pmd);
+		folio = vm_normal_folio_pmd(vma, addr, *pmd);
+		if (!folio)
+			goto out;
 
 		/* Clear accessed and referenced bits. */
 		pmdp_test_and_clear_young(vma, addr, pmd);
@@ -2106,7 +2108,7 @@ static int pagemap_pmd_range_thp(pmd_t *pmdp, unsigned long addr,
 		goto populate_pagemap;
 
 	if (pmd_present(pmd)) {
-		page = pmd_page(pmd);
+		page = vm_normal_page_pmd(vma, addr, pmd);
 
 		flags |= PM_PRESENT;
 		if (pmd_soft_dirty(pmd))
Signature · 1 line
2.53.0
author maintainer
#663 lore raw

PATCH 657/1257 mm/madvise: reclaim isolated folios if PTE restart fails

In reply to Greg Kroah-Hartman

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

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

From: Gregory Price <[email protected]>

[ Upstream commit 5445a6359d717354dd76d509b8e693f13403ec61 ]

MADV_PAGEOUT collects isolated folios on a local list before reclaiming them after the PTE walk. The reschedule path drops the PTE lock and then restarts the mapping with pte_offset_map_lock().

A concurrent operation can remove or replace the PTE table while the lock is dropped, causing pte_offset_map_lock() to return NULL. Returning directly in that case bypasses reclaim_pages(), leaving the collected folios off the LRU with elevated references.

This results in a permanent memory leak. nr_isolated_anon increases reliably and does not decrease when the process dies.

Route the failure through the existing cleanup path so any isolated folios are reclaimed or put back.

Simplest userland pseudo-code reproducer:

p = mmap(PMD_SIZE, ANONYMOUS);
touch_every_page(p, PMD_SIZE);
parallel {
while (1) madvise(p, PMD_SIZE, MADV_PAGEOUT);

   while (1) {
       madvise(p, PMD_SIZE, MADV_DONTNEED);
       touch_every_page(p, PMD_SIZE);

}
}

Reproduced in qemu trivially with some explicit widening of the race window.

Fixes b2f557a21bc8 ("mm/madvise: add cond_resched() in madvise_cold_or_pageout_pte_range()")
Assisted-by LLM
Cc David Hildenbrand <[email protected]>
Cc Jann Horn <[email protected]>
Cc Jiexun Wang <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
---
 mm/madvise.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/madvise.c +2 -1
index 95287c495e462..47e40d240c7e6 100644
@@ -461,7 +461,7 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 restart:
 	start_pte = pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
 	if (!start_pte)
-		return 0;
+		goto out;
 	flush_tlb_batched_pending(mm);
 	lazy_mmu_mode_enable();
 	for (; addr < end; pte += nr, addr += nr * PAGE_SIZE) {
@@ -565,6 +565,7 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 			folio_deactivate(folio);
 	}
 
+out:
 	if (start_pte) {
 		lazy_mmu_mode_disable();
 		pte_unmap_unlock(start_pte, ptl);
Signature · 1 line
2.53.0
author maintainer
#664 lore raw

PATCH 658/1257 mm/madvise: use folio_trylock() in the cold/pageout PMD split

In reply to Greg Kroah-Hartman

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

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

From: Gregory Price <[email protected]>

[ Upstream commit 5a6c9cf117fca3c38a98fb2a2d5549795c8b0b73 ]

MADV_COLD or MADV_PAGEOUT over part of a PMD splits the THP in madvise_cold_or_pageout_pte_range(). Two threads doing that to the same THP create spurious failures.

CPU0 CPU1
---- ----
folio_get()
spin_unlock(ptl)
folio_lock()
folio_get() spin_unlock(ptl) folio_lock() <- blocks, keeps its ref
split_folio()

    folio_expected_ref_count(folio) != folio_ref_count(folio) - 1
    -EAGAIN

CPU1 cannot drop its reference until it gets the lock CPU0 holds, so CPU0's split always fails. folio_trylock() makes CPU1 leave without ever taking a reference. The PTE branch of this same function already does this, as do madvise_free_pte_range() and madvise_free_huge_pmd().

Reproducer: 400 rounds of eight threads calling MADV_COLD on half of each of eight THPs, re-formed with MADV_COLLAPSE between rounds. From /proc/vmstat:

thp_split_page thp_split_page_failed
before 3186 860
after 3200 0

The short before count is rounds where every thread failed and the advice was dropped for that THP entirely.

On failure the walker returns 0 and nothing retries. The PMD path becomes best effort when the folio lock is held elsewhere - same as the PTE path.

---
 mm/madvise.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
mm/madvise.c +2 -1
index 47e40d240c7e6..39480d78b7ad6 100644
@@ -416,9 +416,10 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 		if (next - addr != HPAGE_PMD_SIZE) {
 			int err;
 
+			if (!folio_trylock(folio))
+				goto huge_unlock;
 			folio_get(folio);
 			spin_unlock(ptl);
-			folio_lock(folio);
 			err = split_folio(folio);
 			folio_unlock(folio);
 			folio_put(folio);
Signature · 1 line
2.53.0
author maintainer
#665 lore raw

PATCH 659/1257 mm/page_alloc: do not boost watermarks in kdump capture kernels

In reply to Greg Kroah-Hartman

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

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

From: Yuanhe Shu <[email protected]>

[ Upstream commit 331f94007d79b3c02d3098eea469a92aea3efc2c ]

A watermark boost is not confined to one watermark: wmark_pages() adds it to min, low and high alike, so every watermark check sees it, including should_reclaim_retry() and the last ditch ALLOC_WMARK_HIGH attempt in __alloc_pages_may_oom(). Once the boost exceeds the memory still free the allocator gives up and invokes the OOM killer, and a capture kernel that is still booting has nothing to kill: the boot panics and the vmcore is lost.

Seen on an arm64 machine with 64K pages, CONFIG_PAGE_BLOCK_MAX_ORDER=10 (pageblock = 64M) and crashkernel=512M, running a distribution kernel based on 7.0.14. A high order UNMOVABLE allocation fell back to a MOVABLE pageblock while the capture kernel was still in do_initcalls():

Node 0 DMA free:68096kB boost:65536kB min:68160kB low:68800kB high:69440kB managed:479168kB Out of memory and no killable processes...

  Kernel panic - not syncing: System is deadlocked on memory

The zone was not short of memory. Subtracting the boost gives min:2624kB low:3264kB high:3904kB, so the 68096kB still free sat 17 times above the high watermark and the allocator would not even have entered its slow path. The boost supplied 65536kB of the 68160kB min and by itself put the zone 64kB under water. It is that large because boost_watermark() clamps it with max(pageblock_nr_pages, max_boost); watermark_boost_factor alone would have allowed 5824kB.

Commit 14f69140ff9c ("mm: limit boost_watermark on small zones") already tried to protect capture kernels, but it infers them from the zone size and skips the boost only below four pageblocks. arm64 64K pageblocks were 512M then, so the guard reached zones up to 2G; CONFIG_PAGE_BLOCK_MAX_ORDER can cap them at 64M, which shrinks the guard to zones under 256M and lets this 468M zone through.

kdump is a property of the kernel, not of the zone, so test for it directly. A capture kernel exits within seconds and never uses the fragmentation avoidance the boost buys. Normal kernels are unaffected:
the size based check still covers their genuinely tiny zones.

Passing sysctl.vm.watermark_boost_factor=0 to the capture kernel does not cover this window: sysctl.* parameters are written through procfs by do_sysctl_args(), which runs after do_initcalls() where the panic above happened, and watermark_boost_factor has no early_param of its own.

Fixes 1c30844d2dfe ("mm: reclaim small amounts of memory when an external fragmentation event occurs")
Cc Henry Willard <[email protected]>
Cc Brendan Jackman <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Zi Yan <[email protected]>
Cc <[email protected]> # v5.0
---
 mm/page_alloc.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
mm/page_alloc.c +10 -2
index 12fac9084c483..f52ed7d2cd347 100644
@@ -37,6 +37,7 @@
 #include <linux/vmstat.h>
 #include <linux/fault-inject.h>
 #include <linux/compaction.h>
+#include <linux/crash_dump.h>
 #include <trace/events/kmem.h>
 #include <trace/events/oom.h>
 #include <linux/prefetch.h>
@@ -2178,10 +2179,17 @@ static inline bool boost_watermark(struct zone *zone)
 
 	if (!watermark_boost_factor)
 		return false;
+
+	/*
+	 * A kdump capture kernel exits before a boost can pay off, while
+	 * the raised watermark can exceed the memory left for the dump.
+	 */
+	if (is_kdump_kernel())
+		return false;
+
 	/*
 	 * Don't bother in zones that are unlikely to produce results.
-	 * On small machines, including kdump capture kernels running
-	 * in a small area, boosting the watermark can cause an out of
+	 * On small machines, boosting the watermark can cause an out of
 	 * memory situation immediately.
 	 */
 	if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
Signature · 1 line
2.53.0
author maintainer
#666 lore raw

PATCH 660/1257 mm/hugetlb_cgroup: move per-node usage on cross node migration

In reply to Greg Kroah-Hartman

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

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

From: Hongfu Li <[email protected]>

[ Upstream commit fe0ba1909c59660f078560f5130e7af7c6004f12 ]

Patch series "mm/hugetlb_cgroup: move the per-node usage along with the folio", v2.

The per-node usage reported by hugetlb.<size>.numa_stat is accounted against folio_nid() in __hugetlb_cgroup_commit_charge() and __hugetlb_cgroup_uncharge_folio(), so it is only correct while a folio stays charged on the same node and in the same hugetlb_cgroup.

Two paths move a folio which stays charged, and neither moves the usage with it. hugetlb_cgroup_migrate() only moves the hugetlb_cgroup pointers of a folio migrated to another node, and hugetlb_cgroup_move_parent() only moves the page_counter charges and the hugetlb_cgroup pointer of the folios of a dying cgroup. In both cases the node (or cgroup) which was charged keeps a usage which never goes away, while the node (or cgroup) which ends up uncharging the folio underflows as soon as the folio is freed.

Patch 1/2 moves the usage along with the folio on cross node migration, patch 2/2 does the same for the folios a dying cgroup reparents.

This patch (of 2):

hugetlb.<size>.numa_stat uses folio_nid() to account usage in __hugetlb_cgroup_commit_charge() and __hugetlb_cgroup_uncharge_folio(). hugetlb_cgroup_migrate() only moves hugetlb_cgroup pointers, leaving per-node usage behind on the source node during cross-node migration.

When the migrated folio gets uncharged, we subtract usage from the destination node counter. This creates stale usage on the source node and unsigned long counter underflow on the destination node. The hugetlb.<size>.numa_stat interface exposes these incorrect per-node usage values to userspace.

Add a hugetlb_cgroup_move_usage() helper which moves the usage from the old node to the new node, and call it from hugetlb_cgroup_migrate().

Fixes f47761999052 ("hugetlb: add hugetlb.*.numa_stat file")
Cc Colin Ian King <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Kees Cook <[email protected]>
Cc Mina Almasry <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Shakeel Butt <[email protected]>
---
 mm/hugetlb_cgroup.c | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
mm/hugetlb_cgroup.c +31 -0
index ecb6e0b7819a0..7cf7c18119b43 100644
@@ -179,6 +179,34 @@ static void hugetlb_cgroup_css_free(struct cgroup_subsys_state *css)
 	hugetlb_cgroup_free(hugetlb_cgroup_from_css(css));
 }
 
+static void hugetlb_cgroup_move_usage(struct hugetlb_cgroup *from,
+				      struct hugetlb_cgroup *to,
+				      struct folio *from_folio,
+				      struct folio *to_folio)
+{
+	int idx = hstate_index(folio_hstate(from_folio));
+	unsigned long nr_pages = folio_nr_pages(from_folio);
+	int from_nid = folio_nid(from_folio);
+	int to_nid = folio_nid(to_folio);
+	unsigned long usage;
+
+	lockdep_assert_held(&hugetlb_lock);
+
+	if (!from || !to)
+		return;
+
+	if (from == to && from_nid == to_nid)
+		return;
+
+	usage = from->nodeinfo[from_nid]->usage[idx];
+	if (WARN_ON_ONCE(usage < nr_pages))
+		return;
+	WRITE_ONCE(from->nodeinfo[from_nid]->usage[idx], usage - nr_pages);
+
+	usage = to->nodeinfo[to_nid]->usage[idx];
+	WRITE_ONCE(to->nodeinfo[to_nid]->usage[idx], usage + nr_pages);
+}
+
 /*
  * Should be called with hugetlb_lock held.
  * Since we are holding hugetlb_lock, pages cannot get moved from
@@ -906,6 +934,9 @@ void hugetlb_cgroup_migrate(struct folio *old_folio, struct folio *new_folio)
 	/* move the h_cg details to new cgroup */
 	set_hugetlb_cgroup(new_folio, h_cg);
 	set_hugetlb_cgroup_rsvd(new_folio, h_cg_rsvd);
+
+	hugetlb_cgroup_move_usage(h_cg, h_cg, old_folio, new_folio);
+
 	list_move(&new_folio->lru, &h->hugepage_activelist);
 	spin_unlock_irq(&hugetlb_lock);
 }
Signature · 1 line
2.53.0
author maintainer
#667 lore raw

PATCH 661/1257 mm/hugetlb_cgroup: move per-node usage on cgroup reparenting

In reply to Greg Kroah-Hartman

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

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

From: Hongfu Li <[email protected]>

[ Upstream commit 23fac055c21176f66ed453394b533bdfc00f7fba ]

hugetlb_cgroup_css_offline() hands the folios of a dying cgroup over to its parent with hugetlb_cgroup_move_parent(), which moves the page_counter charges and the hugetlb_cgroup pointer of the folio but not its per-node usage. The parent's hugetlb.<size>.numa_stat is short by that usage while they are charged, and underflows once they are freed, exposing incorrect per-node usage values to userspace.

Move the per-node usage to the parent as well. The folios keep their node here, so only the cgroup which holds the usage changes.

Fixes f47761999052 ("hugetlb: add hugetlb.*.numa_stat file")
Cc Colin Ian King <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Kees Cook <[email protected]>
Cc Mina Almasry <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Shakeel Butt <[email protected]>
---
 mm/hugetlb_cgroup.c | 2 ++
 1 file changed, 2 insertions(+)
mm/hugetlb_cgroup.c +2 -0
index 7cf7c18119b43..3fb41311e4c7d 100644
@@ -241,6 +241,8 @@ static void hugetlb_cgroup_move_parent(int idx, struct hugetlb_cgroup *h_cg,
 	/* Take the pages off the local counter */
 	page_counter_cancel(counter, nr_pages);
 
+	hugetlb_cgroup_move_usage(h_cg, parent, folio, folio);
+
 	set_hugetlb_cgroup(folio, parent);
 out:
 	return;
Signature · 1 line
2.53.0
author maintainer
#668 lore raw

PATCH 662/1257 mm/shmem: report RCU-tasks quiescent states while undoing a range

In reply to Greg Kroah-Hartman

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

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

From: Breno Leitao <[email protected]>

[ Upstream commit ebd1a08c192109c83a87ddf42793ed6283180faf ]

This shows up in the Meta fleet on ftruncate() of large tmpfs files:

  INFO: rcu_tasks detected stalls on tasks:
  00000000752fd185: .. nvcsw: 59455/59455 holdout: 1 idle_cpu: -1/0
  task:rocksdb:bottom  state:R  running task
    __folio_split
    find_get_entry
    find_get_entries
    truncate_inode_partial_folio
    shmem_undo_range
    shmem_setattr
    notify_change
    do_ftruncate
    __x64_sys_ftruncate
    do_syscall_64

shmem_undo_range() walks the whole of the requested range in folio_batch sized steps, twice, and its two cond_resched() calls are the only reschedule points in that walk.

cond_resched() is not an RCU-tasks quiescent state. Use cond_resched_tasks_rcu_qs() at both points so the walk reports an RCU-tasks quiescent state as it proceeds.

Fixes 8315f42295d2 ("rcu: Add call_rcu_tasks()")
Cc Baolin Wang <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc "Paul E . McKenney" <[email protected]>
---
 mm/shmem.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/shmem.c +2 -2
index 848316eaa7f4f..af531eea77b93 100644
@@ -1159,7 +1159,7 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,
 		}
 		folio_batch_remove_exceptionals(&fbatch);
 		folio_batch_release(&fbatch);
-		cond_resched();
+		cond_resched_tasks_rcu_qs();
 	}
 
 	/*
@@ -1200,7 +1200,7 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,
 
 	index = start;
 	while (index < end) {
-		cond_resched();
+		cond_resched_tasks_rcu_qs();
 
 		if (!find_get_entries(mapping, &index, end - 1, &fbatch,
 				indices)) {
Signature · 1 line
2.53.0
author maintainer
#669 lore raw

PATCH 663/1257 mm/alloc_tag: account for reserved tag ids in the kernel tag check

In reply to Greg Kroah-Hartman

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

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

From: Hao Ge <[email protected]>

[ Upstream commit c6e5c0b9a493891634d0a413c3485930a28a8903 ]

The tag ids stored in the page flags include two reserved markers. Id 0 means the page has no tag and id 1 means the tag was cleared, so real tags start at CODETAG_ID_FIRST. The kernel-side check in alloc_tag_sec_init() compared kernel_tags.count alone against the addressable limit, so with the count at or just under the limit the last tag ids wrapped into those markers. Pages allocated through them then look the same as untagged pages on free, nothing is ever subtracted from the real tag and /proc/allocinfo shows that memory as still allocated.

Add the missing CODETAG_ID_FIRST, same as tags_addressable().

Fixes 4835f747d3ed ("alloc_tag: support for page allocation tag compression")
---
 mm/alloc_tag.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/alloc_tag.c +1 -1
index b334103104779..82e2c3448dcf2 100644
@@ -621,7 +621,7 @@ void __init alloc_tag_sec_init(void)
 	kernel_tags.count = last_codetag - kernel_tags.first_tag;
 
 	/* Check if kernel tags fit into page flags */
-	if (kernel_tags.count > (1UL << NR_UNUSED_PAGEFLAG_BITS)) {
+	if (CODETAG_ID_FIRST + kernel_tags.count > (1UL << NR_UNUSED_PAGEFLAG_BITS)) {
 		shutdown_mem_profiling(false); /* allocinfo file does not exist yet */
 		pr_err("%lu allocation tags cannot be references using %d available page flag bits. Memory allocation profiling is disabled!\n",
 			kernel_tags.count, NR_UNUSED_PAGEFLAG_BITS);
Signature · 1 line
2.53.0
author maintainer
#670 lore raw

PATCH 664/1257 mm/shmem: dont release a swapin-error marker as a swap entry

In reply to Greg Kroah-Hartman

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

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

From: David Carlier <[email protected]>

[ Upstream commit e4b92891aaca0d37b5973362dd14747a65406650 ]

A failed shmem swapin (eg, EIO) frees the swap slot and leaves a PTE_MARKER_POISONED entry in the page cache. On truncate or eviction shmem_free_swap() passes that marker to swap_put_entries_direct(), which warns because it is not a swap entry. There is nothing left to release either way.

Skip the release for non-swap entries, as every other caller already does.

Fixes ac2d3268284b ("mm/swapfile.c: remove the unneeded checking")
Reported-by [email protected]
Cc Baoquan he <[email protected]>
Cc Barry Song <[email protected]>
Cc Chis Li <[email protected]> (Google)
Cc Hugh Dickens <[email protected]>
Cc Kairui Song <[email protected]>
Cc Kemeng Shi <[email protected]>
Cc Nhat Pham <[email protected]>
---
 mm/shmem.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
mm/shmem.c +4 -2
index af531eea77b93..93714b47f414b 100644
@@ -976,6 +976,7 @@ static long shmem_free_swap(struct address_space *mapping,
 			    pgoff_t index, pgoff_t end, void *radswap)
 {
 	XA_STATE(xas, &mapping->i_pages, index);
+	const softleaf_t swp = radix_to_swp_entry(radswap);
 	unsigned int nr_pages = 0;
 	pgoff_t base;
 	void *entry;
@@ -992,8 +993,9 @@ static long shmem_free_swap(struct address_space *mapping,
 	}
 	xas_unlock_irq(&xas);
 
-	if (nr_pages)
-		swap_put_entries_direct(radix_to_swp_entry(radswap), nr_pages);
+	/* A swapin-error marker holds no swap slot, so just drop it. */
+	if (nr_pages && softleaf_is_swap(swp))
+		swap_put_entries_direct(swp, nr_pages);
 
 	return nr_pages;
 }
Signature · 1 line
2.53.0
author maintainer
#671 lore raw

PATCH 665/1257 mm/damon/core: charge only the part of a region the filter left

In reply to Greg Kroah-Hartman

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

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

From: Donggeun Yoo <[email protected]>

[ Upstream commit 4ff3b4a54a32142497fb44b79d0920aa6ba3393d ]

Patch series "mm/damon/core: fix the size charged for a filter-trimmed region", v2.

An address range DAMOS filter that partially overlaps a monitoring region splits it, so the scheme action reaches only one side of the boundary. damos_apply_scheme() reads the region size before that split and never re-reads it, so the quota charge and schemes/<S>/stats/sz_tried account for the whole original region.

Patch 1 re-reads the size after the core filters have run. Patch 2 adds KUnit coverage for what the function charges and reports, for the trimmed cases and for the cases that must not change.

This patch (of 2):

An address range DAMOS filter that partially overlaps a monitoring region splits the region at the filter boundary, so the scheme action is applied to only one side of it. damos_apply_scheme() reads the region size once on entry, before damos_core_filter_out() performs that split.

The quota charge and the statistics update therefore account for the region as it was before the trim. schemes/<S>/stats/sz_tried counts memory the filter excluded, which Documentation/mm/damon/design.rst says is not counted as tried, and with quotas/bytes set the excluded part is charged against the budget, throttling the scheme to a fraction of what was configured.

User impact is that DAMOS could unexpectedly slowly run, due to over-charged quota. DAMOS stat could also be confusing. No critical events such as crashes or leask happen.

Re-read the region size after the core filters have run.

---
 mm/damon/core.c | 1 +
 1 file changed, 1 insertion(+)
mm/damon/core.c +1 -0
index a4542a49ff80a..4290e2a1c7e8d 100644
@@ -2653,6 +2653,7 @@ static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
 		}
 		if (damos_core_filter_out(c, t, r, s))
 			return;
+		sz = damon_sz_region(r);
 		ktime_get_coarse_ts64(&begin);
 		trace_damos_before_apply(cidx, sidx, tidx, r, nr_accesses,
 				damon_nr_regions(t), do_trace);
Signature · 1 line
2.53.0
author maintainer
#672 lore raw

PATCH 666/1257 mm/damon/tests/core-kunit: test the size charged for a filter-trimmed region

In reply to Greg Kroah-Hartman

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

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

From: Donggeun Yoo <[email protected]>

[ Upstream commit 1c335228206392b96d327c6b49cea68cbb806d8a ]

damos_test_filter_out() checks that an address range filter splits a region at the filter boundary, and stops there. Nothing checks what damos_apply_scheme() then charges to the quota and reports as tried.

damos_test_apply_scheme_filtered_sz() covers the two ways such a filter trims a region: one that starts before the filter's range, and one that starts inside it.

damos_test_apply_scheme_filter_sz_unchanged() and damos_test_apply_scheme_quota_sz() cover the cases whose accounting must not change: a region wholly inside a reject range, one wholly inside an allow range, two filters trimming in a single call, a filter type that never splits, no filter at all, a region the quota trims, and a quota remainder too small for one region.

---
 mm/damon/tests/core-kunit.h | 316 ++++++++++++++++++++++++++++++++++++
 1 file changed, 316 insertions(+)
mm/damon/tests/core-kunit.h +316 -0
index 062332fe847ce..0f29da862951e 100644
@@ -1433,6 +1433,319 @@ static void damos_test_filter_out(struct kunit *test)
 	damos_free_filter(f);
 }
 
+static unsigned long damos_test_apply_scheme_stub(struct damon_ctx *c,
+		struct damon_target *t, struct damon_region *r,
+		struct damos *s, unsigned long *sz_filter_passed)
+{
+	return 0;
+}
+
+static void damos_test_apply_scheme_filtered_sz(struct kunit *test)
+{
+	struct damos_access_pattern pattern = {
+		.min_sz_region = 0,
+		.max_sz_region = ULONG_MAX,
+		.min_nr_accesses = 0,
+		.max_nr_accesses = UINT_MAX,
+		.min_age_region = 0,
+		.max_age_region = UINT_MAX,
+	};
+	unsigned long min_sz = DAMON_MIN_REGION_SZ;
+	struct damos_watermarks wmarks = {};
+	struct damos_quota quota = {};
+	struct damon_ctx *c;
+	struct damon_target *t;
+	struct damon_region *r;
+	struct damos_filter *f;
+	struct damos *s;
+
+	c = damon_new_ctx();
+	if (!c)
+		kunit_skip(test, "ctx alloc fail");
+	c->ops.apply_scheme = damos_test_apply_scheme_stub;
+
+	s = damon_new_scheme(&pattern, DAMOS_STAT, 0, &quota, &wmarks,
+			NUMA_NO_NODE);
+	if (!s) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "scheme alloc fail");
+	}
+	damon_add_scheme(c, s);
+
+	t = damon_new_target();
+	if (!t) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "target alloc fail");
+	}
+	damon_add_target(c, t);
+
+	f = damos_new_filter(DAMOS_FILTER_TYPE_ADDR, true, false);
+	if (!f) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "filter alloc fail");
+	}
+	f->addr_range = (struct damon_addr_range){
+		.start = 2 * min_sz,
+		.end = 8 * min_sz
+	};
+	damos_add_filter(s, f);
+	damos_set_filters_default_reject(s);
+
+	/* reject filter, region starting before the range */
+	r = damon_new_region(0, 4 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 2);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 2 * min_sz);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 2 * min_sz);
+
+	if (damon_nr_regions(t) != 2)
+		goto out;
+	damon_destroy_region(damon_next_region(r), t);
+	damon_destroy_region(r, t);
+	s->stat = (struct damos_stat){};
+
+	/* allow filter, region starting inside the range */
+	f->allow = true;
+	damos_set_filters_default_reject(s);
+	r = damon_new_region(2 * min_sz, 10 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 2);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 8 * min_sz);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 6 * min_sz);
+
+out:
+	damon_destroy_ctx(c);
+}
+
+static void damos_test_apply_scheme_filter_sz_unchanged(struct kunit *test)
+{
+	struct damos_access_pattern pattern = {
+		.min_sz_region = 0,
+		.max_sz_region = ULONG_MAX,
+		.min_nr_accesses = 0,
+		.max_nr_accesses = UINT_MAX,
+		.min_age_region = 0,
+		.max_age_region = UINT_MAX,
+	};
+	unsigned long min_sz = DAMON_MIN_REGION_SZ;
+	struct damos_watermarks wmarks = {};
+	struct damos_quota quota = {};
+	struct damos_filter *f, *f2;
+	struct damon_ctx *c;
+	struct damon_target *t;
+	struct damon_region *r;
+	struct damos *s;
+
+	c = damon_new_ctx();
+	if (!c)
+		kunit_skip(test, "ctx alloc fail");
+	c->ops.apply_scheme = damos_test_apply_scheme_stub;
+
+	s = damon_new_scheme(&pattern, DAMOS_STAT, 0, &quota, &wmarks,
+			NUMA_NO_NODE);
+	if (!s) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "scheme alloc fail");
+	}
+	damon_add_scheme(c, s);
+
+	t = damon_new_target();
+	if (!t) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "target alloc fail");
+	}
+	damon_add_target(c, t);
+
+	f = damos_new_filter(DAMOS_FILTER_TYPE_ADDR, true, false);
+	if (!f) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "filter alloc fail");
+	}
+	f->addr_range = (struct damon_addr_range){
+		.start = 2 * min_sz, .end = 8 * min_sz};
+	damos_add_filter(s, f);
+	damos_set_filters_default_reject(s);
+
+	/* wholly inside a reject range: not counted at all */
+	r = damon_new_region(4 * min_sz, 6 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, s->stat.nr_tried, 0);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 0);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 1);
+
+	/* wholly inside an allow range: counted whole, not split */
+	f->allow = true;
+	damos_set_filters_default_reject(s);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 2 * min_sz);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 1);
+
+	/* two filters, each trimming: the size left after both is counted */
+	damon_destroy_region(r, t);
+	s->stat = (struct damos_stat){};
+	f->allow = false;
+	f->addr_range = (struct damon_addr_range){
+		.start = 4 * min_sz, .end = 12 * min_sz};
+	f2 = damos_new_filter(DAMOS_FILTER_TYPE_ADDR, true, false);
+	if (!f2) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "filter alloc fail");
+	}
+	f2->addr_range = (struct damon_addr_range){
+		.start = 2 * min_sz, .end = 3 * min_sz};
+	damos_add_filter(s, f2);
+	damos_set_filters_default_reject(s);
+
+	r = damon_new_region(0, 8 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 3);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 2 * min_sz);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 2 * min_sz);
+
+	/* a core filter that never splits: counted whole */
+	damos_destroy_filter(f2);
+	damos_destroy_filter(f);
+	f = damos_new_filter(DAMOS_FILTER_TYPE_TARGET, true, true);
+	if (!f) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "filter alloc fail");
+	}
+	f->target_idx = 0;
+	damos_add_filter(s, f);
+	damos_set_filters_default_reject(s);
+	s->stat = (struct damos_stat){};
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 3);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 2 * min_sz);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 2 * min_sz);
+
+	damon_destroy_ctx(c);
+}
+
+static void damos_test_apply_scheme_quota_sz(struct kunit *test)
+{
+	struct damos_access_pattern pattern = {
+		.min_sz_region = 0,
+		.max_sz_region = ULONG_MAX,
+		.min_nr_accesses = 0,
+		.max_nr_accesses = UINT_MAX,
+		.min_age_region = 0,
+		.max_age_region = UINT_MAX,
+	};
+	unsigned long min_sz = DAMON_MIN_REGION_SZ;
+	struct damos_watermarks wmarks = {};
+	struct damos_quota quota = {};
+	struct damon_region *r, *next;
+	struct damon_ctx *c;
+	struct damon_target *t;
+	struct damos *s;
+
+	c = damon_new_ctx();
+	if (!c)
+		kunit_skip(test, "ctx alloc fail");
+
+	s = damon_new_scheme(&pattern, DAMOS_STAT, 0, &quota, &wmarks,
+			NUMA_NO_NODE);
+	if (!s) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "scheme alloc fail");
+	}
+	damon_add_scheme(c, s);
+	damos_set_filters_default_reject(s);
+
+	t = damon_new_target();
+	if (!t) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "target alloc fail");
+	}
+	damon_add_target(c, t);
+
+	/* no apply_scheme operation: the whole region is counted */
+	r = damon_new_region(0, 4 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 4 * min_sz);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 1);
+
+	/* no filter and no quota: the whole region is counted */
+	c->ops.apply_scheme = damos_test_apply_scheme_stub;
+	s->stat = (struct damos_stat){};
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 4 * min_sz);
+	KUNIT_EXPECT_EQ(test, damon_nr_regions(t), 1);
+
+	/* the quota trims the region: the trimmed size is counted */
+	damon_for_each_region_safe(r, next, t)
+		damon_destroy_region(r, t);
+	s->stat = (struct damos_stat){};
+	s->quota.esz = 2 * min_sz;
+	s->quota.charged_sz = 0;
+
+	r = damon_new_region(0, 8 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 2 * min_sz);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 2 * min_sz);
+
+	/* quota remainder below one region: tried, but nothing counted */
+	damon_for_each_region_safe(r, next, t)
+		damon_destroy_region(r, t);
+	s->stat = (struct damos_stat){};
+	s->quota.esz = 1;
+	s->quota.charged_sz = 0;
+
+	r = damon_new_region(0, 4 * min_sz);
+	if (!r) {
+		damon_destroy_ctx(c);
+		kunit_skip(test, "region alloc fail");
+	}
+	damon_add_region(r, t);
+
+	damos_apply_scheme(c, t, r, s);
+	KUNIT_EXPECT_EQ(test, s->stat.nr_tried, 1);
+	KUNIT_EXPECT_EQ(test, s->stat.sz_tried, 0);
+	KUNIT_EXPECT_EQ(test, r->ar.end, 4 * min_sz);
+
+	damon_destroy_ctx(c);
+}
+
 static void damon_test_feed_loop_next_input(struct kunit *test)
 {
 	unsigned long last_input = 900000, current_score = 200;
@@ -1682,6 +1995,9 @@ static struct kunit_case damon_test_cases[] = {
 	KUNIT_CASE(damon_test_commit_target_regions),
 	KUNIT_CASE(damon_test_commit_ctx),
 	KUNIT_CASE(damos_test_filter_out),
+	KUNIT_CASE(damos_test_apply_scheme_filtered_sz),
+	KUNIT_CASE(damos_test_apply_scheme_filter_sz_unchanged),
+	KUNIT_CASE(damos_test_apply_scheme_quota_sz),
 	KUNIT_CASE(damon_test_feed_loop_next_input),
 	KUNIT_CASE(damon_test_set_filters_default_reject),
 	KUNIT_CASE(damon_test_apply_min_nr_regions),
Signature · 1 line
2.53.0
author maintainer
#673 lore raw

PATCH 667/1257 platform/x86/amd/pmf: Add AMDI0112 ACPI ID

In reply to Greg Kroah-Hartman

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

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

From: Mario Limonciello <[email protected]>

[ Upstream commit 325bcc126cf7a512a0e2da0efddad665f69badac ]

The AMDI0112 ID is used to bind the PMF driver to some platforms. It doesn't have any Linux side code changes relative to the most similar AMDI0105.

---
 drivers/platform/x86/amd/pmf/core.c | 1 +
 1 file changed, 1 insertion(+)
drivers/platform/x86/amd/pmf/core.c +1 -0
index b4eae65e675b8..5966190d1496b 100644
@@ -454,6 +454,7 @@ static const struct acpi_device_id amd_pmf_acpi_ids[] = {
 	{"AMDI0107", 0},
 	{"AMDI0108", 0},
 	{"AMDI0109", 0},
+	{"AMDI0112", 0},
 	{ }
 };
 MODULE_DEVICE_TABLE(acpi, amd_pmf_acpi_ids);
Signature · 1 line
2.53.0
author maintainer
#674 lore raw

PATCH 668/1257 platform/x86/amd/pmf: Validate the APTS state index

In reply to Greg Kroah-Hartman

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

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

From: Mario Limonciello <[email protected]>

[ Upstream commit 192dddd5aa45166450820cef16521bdf23976a73 ]

The static slider APTS state index is supplied by the BIOS as an 8-bit value, but apts_config_store contains only APTS_MAX_STATES entries. An invalid firmware value can therefore cause amd_pmf_update_slider_v2() to read beyond the end of the array.

Validate the selected index before applying the slider values and return an error when it is out of range.

Fixes 8362e862fb87 ("platform/x86/amd/pmf: Update sps power thermals according to the platform-profiles")
---
 drivers/platform/x86/amd/pmf/sps.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
drivers/platform/x86/amd/pmf/sps.c +7 -3
index 0b70a5153f465..0918fb388fde6 100644
@@ -248,20 +248,24 @@ static int amd_pmf_update_sps_power_limits_v2(struct amd_pmf_dev *pdev, int pwr_
 	switch (pwr_mode) {
 	case POWER_MODE_PERFORMANCE:
 		index = config_store_v2.sps_idx.power_states[src][POWER_MODE_BEST_PERFORMANCE];
-		amd_pmf_update_slider_v2(pdev, index);
 		break;
 	case POWER_MODE_BALANCED_POWER:
 		index = config_store_v2.sps_idx.power_states[src][POWER_MODE_BALANCED];
-		amd_pmf_update_slider_v2(pdev, index);
 		break;
 	case POWER_MODE_POWER_SAVER:
 		index = config_store_v2.sps_idx.power_states[src][POWER_MODE_BEST_POWER_EFFICIENCY];
-		amd_pmf_update_slider_v2(pdev, index);
 		break;
 	default:
 		return -EINVAL;
 	}
 
+	if (index >= APTS_MAX_STATES) {
+		dev_err(pdev->dev, "Invalid APTS index: %d\n", index);
+		return -EINVAL;
+	}
+
+	amd_pmf_update_slider_v2(pdev, index);
+
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#675 lore raw

PATCH 669/1257 platform/x86/amd: Stop counting intermediate cycles with metrics table

In reply to Greg Kroah-Hartman

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

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

From: Mario Limonciello <[email protected]>

[ Upstream commit 0c2c928ea7d33c8131b0785bda4e26a32dce5caa ]

The metrics table doesn't increment for all cases that can cause an intermediate wakeup if the cycle is very fast. This can make the intent from commit 9f5595d5f03fd ("platform/x86/amd: pmc: Require at least 2.5 seconds between HW sleep cycles") not work properly.

That commit originally was measured to work properly, but it was accidental due to a logic error. The logic error was fixed in commit 4dbd11796f3a8 ("platform/x86/amd: pmc: Clear metrics table at start of cycle") but this now masked the table doesn't always update.

Since that code was introduced, Daniel Gibson added a number of changes to the logic which includes a state variable introduced in commit 037f0b03c663a ("platform/x86/amd/pmc: Don't log during intermediate wakeups").

Utilize that state variable to instead decide if a single sequence has started.

Cc Daniel Gibson <[email protected]>
Cc [email protected] # 7.1.y: 037f0b03c663a platform/x86/amd/pmc: Don't log during intermediate wakeups
Cc [email protected] # 6.18.y: 037f0b03c663a platform/x86/amd/pmc: Don't log during intermediate wakeups
Fixes 4dbd11796f3a8 ("platform/x86/amd: pmc: Clear metrics table at start of cycle")
---
 drivers/platform/x86/amd/pmc/pmc.c | 15 +--------------
 1 file changed, 1 insertion(+), 14 deletions(-)
drivers/platform/x86/amd/pmc/pmc.c +1 -14
index 6792aa2c61874..e384b56d67559 100644
@@ -701,19 +701,6 @@ static int amd_pmc_verify_czn_rtc(struct amd_pmc_dev *pdev, u32 *arg)
 	return rc;
 }
 
-static bool amd_pmc_intermediate_wakeup_need_delay(struct amd_pmc_dev *pdev)
-{
-	/*
-	 * Starting a new HW sleep cycle right after waking from one
-	 * can cause electrical problems triggering the over voltage protection.
-	 * That is avoided by delaying the next suspend a bit, see also
-	 * https://lore.kernel.org/all/[email protected]/
-	 */
-	struct smu_metrics table;
-
-	return get_metrics_table(pdev, &table) == 0 && table.s0i3_last_entry_status;
-}
-
 static bool amd_pmc_want_suspend_delay(struct amd_pmc_dev *pdev)
 {
 	/*
@@ -804,7 +791,7 @@ static void amd_pmc_s2idle_check(void)
 	struct amd_pmc_dev *pdev = &pmc;
 	int rc;
 
-	if (amd_pmc_intermediate_wakeup_need_delay(pdev) ||
+	if (!pdev->is_first_check_after_suspend ||
 	    amd_pmc_want_suspend_delay(pdev))
 		msleep(2500);
 
Signature · 1 line
2.53.0
author maintainer
#676 lore raw

PATCH 670/1257 platform/x86: asus-wmi: fix unclear usage of bd->props.power

In reply to Greg Kroah-Hartman

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

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

From: Denis Benato <[email protected]>

[ Upstream commit fd83d81ddf058d487e6d6489b18094f068e66a59 ]

The bd->props.power is checked in parts of the driver correctly comparing with BACKLIGHT_POWER_ON, while in others with a raw usage of bd->props.power and !bd->props.power, moreover in certain checks the logic has been inverted due to BACKLIGHT_POWER_ON being defined as 0: fix both the wrong usage and the inconsistencies by using proper comparisons.

---
 drivers/platform/x86/asus-wmi.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/platform/x86/asus-wmi.c +9 -3
index daf8bd17e6380..10c8fcb075b2d 100644
@@ -4532,7 +4532,8 @@ static int update_screenpad_bl_status(struct backlight_device *bd)
 	u32 ctrl_param = bd->props.brightness;
 	int err = 0;
 
-	if (bd->props.power) {
+	switch (bd->props.power) {
+	case BACKLIGHT_POWER_ON:
 		err = asus_wmi_set_devstate(ASUS_WMI_DEVID_SCREENPAD_POWER, 1, NULL);
 		if (err < 0)
 			return err;
@@ -4540,12 +4541,17 @@ static int update_screenpad_bl_status(struct backlight_device *bd)
 		err = asus_wmi_set_devstate(ASUS_WMI_DEVID_SCREENPAD_LIGHT, ctrl_param, NULL);
 		if (err < 0)
 			return err;
-	}
+		break;
 
-	if (!bd->props.power) {
+	case BACKLIGHT_POWER_OFF:
 		err = asus_wmi_set_devstate(ASUS_WMI_DEVID_SCREENPAD_POWER, 0, NULL);
 		if (err < 0)
 			return err;
+		break;
+
+	default:
+		pr_warn("Invalid screenpad backlight power state: %d\n", bd->props.power);
+		return -EINVAL;
 	}
 
 	return err;
Signature · 1 line
2.53.0
author maintainer
#677 lore raw

PATCH 671/1257 platform/x86: asus-wmi: fix screenpad power state detection

In reply to Greg Kroah-Hartman

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

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

From: Denis Benato <[email protected]>

[ Upstream commit f9a1cd14b392a82fdc73474894bf8b198757dfb2 ]

On some models, e.g. the UX5400EA, the screenpad power state cannot be read back: DSTS(ASUS_WMI_DEVID_SCREENPAD_POWER) never sets ASUS_WMI_DSTS_STATUS_BIT, so asus_wmi_get_devstate_simple() reports the panel as powered off regardless of its real state.

The DSDT shows DSTS 0x00050031 (POWER) and DSTS 0x00050032 (LIGHT) both read the same two-byte EC register, each returning a different
byte: byte 0 is a raw EC status byte, which is 0xa0 when the panel is powered and 0x00 when it is off, and byte 1 is the brightness. Read the power state from the low byte instead of
ASUS_WMI_DSTS_STATUS_BIT: firmware reporting the power through the status bit is covered too, since ASUS_WMI_DSTS_STATUS_BIT lies inside ASUS_WMI_DSTS_BRIGHTNESS_MASK.

Reuse read_screenpad_backlight_power() in asus_screenpad_init() in place of the raw devstate read. This makes the brightness read reachable on models like the UX5400EA, so mask the SCREENPAD_LIGHT value with ASUS_WMI_DSTS_BRIGHTNESS_MASK before storing it: the unmasked devstate (0x0001ffa0 when the panel is on) would otherwise be exposed to userspace as an out-of-range brightness (max_brightness is
255) which systemd-backlight then persists.

While at it, pass asus_wmi_get_devstate() the u32 it expects.

---
 drivers/platform/x86/asus-wmi.c | 22 +++++++++++++++-------
 1 file changed, 15 insertions(+), 7 deletions(-)
drivers/platform/x86/asus-wmi.c +15 -7
index 10c8fcb075b2d..3cc0b96baeb34 100644
@@ -4498,13 +4498,20 @@ static int is_display_toggle(int code)
 
 static int read_screenpad_backlight_power(struct asus_wmi *asus)
 {
-	int ret;
+	int ret, retval;
 
-	ret = asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_SCREENPAD_POWER);
+	ret = asus_wmi_get_devstate(asus, ASUS_WMI_DEVID_SCREENPAD_POWER, &retval);
 	if (ret < 0)
 		return ret;
-	/* 1 == powered */
-	return ret ? BACKLIGHT_POWER_ON : BACKLIGHT_POWER_OFF;
+
+	/*
+	 * The firmware reports the panel power in the low byte of the
+	 * devstate as a raw EC status byte that is non-zero when the
+	 * panel is powered; other models report it through
+	 * ASUS_WMI_DSTS_STATUS_BIT, which lies inside the same mask.
+	 */
+	return (retval & ASUS_WMI_DSTS_BRIGHTNESS_MASK) ?
+		BACKLIGHT_POWER_ON : BACKLIGHT_POWER_OFF;
 }
 
 static int read_screenpad_brightness(struct backlight_device *bd)
@@ -4568,16 +4575,17 @@ static int asus_screenpad_init(struct asus_wmi *asus)
 	struct backlight_device *bd;
 	struct backlight_properties props;
 	int err, power;
-	int brightness = 0;
+	u32 brightness = 0;
 
-	power = asus_wmi_get_devstate_simple(asus, ASUS_WMI_DEVID_SCREENPAD_POWER);
+	power = read_screenpad_backlight_power(asus);
 	if (power < 0)
 		return power;
 
-	if (power) {
+	if (power == BACKLIGHT_POWER_ON) {
 		err = asus_wmi_get_devstate(asus, ASUS_WMI_DEVID_SCREENPAD_LIGHT, &brightness);
 		if (err < 0)
 			return err;
+		brightness &= ASUS_WMI_DSTS_BRIGHTNESS_MASK;
 	}
 
 	memset(&props, 0, sizeof(struct backlight_properties));
Signature · 1 line
2.53.0
author maintainer
#678 lore raw

PATCH 672/1257 platform/x86: hp-bioscfg: fix 16-byte heap overflow for empty auth token

In reply to Greg Kroah-Hartman

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

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

From: Muhammad Bilal <[email protected]>

[ Upstream commit 540b8ae192afb5566c1b13b6884aee87107a26b9 ]

hp_calculate_security_buffer() special-cases an empty authentication string and returns a fixed 4 bytes (sizeof(u16) * 2). But hp_populate_security_buffer() does not special-case that same input:
for any authentication string that does not start with BEAM_PREFIX, including the empty string, it always builds "UTF_PREFIX + authentication" and converts the result to UTF-16, writing a 2-byte length header plus 2 bytes per character of "<utf-16/>" (9 characters), 20 bytes total, regardless of how long "authentication" itself is.

The caller, hp_set_attribute(), sizes its kmalloc() buffer using hp_calculate_security_buffer()'s return value, so for an empty authentication token it allocates 4 bytes for the security area but hp_populate_security_buffer() then writes 20 bytes into it, causing a 16-byte heap buffer overflow.

The authentication token used here is the current admin/setup password, which is an empty string by default until one is configured. Any write to a writable BIOS attribute while no admin password has been set reaches this path.

Fix by removing the special-case early return for an empty string in hp_calculate_security_buffer(). The generic calculation that follows already accounts for the UTF_PREFIX correctly, which naturally yields the same 20 bytes that hp_populate_security_buffer() writes for an empty string, avoiding duplicate logic for special cases.

---
 drivers/platform/x86/hp/hp-bioscfg/spmobj-attributes.c | 3 ---
 1 file changed, 3 deletions(-)
drivers/platform/x86/hp/hp-bioscfg/spmobj-attributes.c +0 -3
index 4d94e48c1a4c8..abf8ce20fe15c 100644
@@ -47,9 +47,6 @@ size_t hp_calculate_security_buffer(const char *authentication)
 		return sizeof(u16) * 2;
 
 	authlen = strlen(authentication);
-	if (!authlen)
-		return sizeof(u16) * 2;
-
 	size = sizeof(u16) + authlen * sizeof(u16);
 	if (!strstarts(authentication, BEAM_PREFIX))
 		size += strlen(UTF_PREFIX) * sizeof(u16);
Signature · 1 line
2.53.0
author maintainer
#679 lore raw

PATCH 673/1257 platform/x86: hp-wmi: fix heap OOB read and memory corruption in hp_wmi_perform_query()

In reply to Greg Kroah-Hartman

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

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

From: Muhammad Bilal <[email protected]>

[ Upstream commit 6dea092b261f04d632411c2be52d13190f5f67b1 ]

hp_wmi_perform_query() evaluates an ACPI WMI method and expects a struct bios_return header in the returned buffer. However, it only checks that the ACPI object type is ACPI_TYPE_BUFFER without verifying that obj->buffer.length is at least sizeof(*bios_return) (8 bytes).

If the firmware or ACPI method returns a buffer shorter than 8 bytes:

1. bios_return->return_code at offset 4 reads out of bounds from the allocated ACPI buffer slab.

2. If return_code evaluates to 0 and outsize is non-zero, (int)(obj->buffer.length - sizeof(*bios_return)) evaluates to a negative integer (e.g. -8 for a 0-length buffer). actual_outsize is set to this negative value and passed to memcpy(buffer, ..., actual_outsize), where the signed negative value is cast to size_t (e.g. 0xfffffffffffffff8), attempting to copy ~18 Exabytes and triggering an immediate kernel crash. Additionally, memset(buffer + actual_outsize, ...) performs an out-of-bounds write before buffer.

Fix this by ensuring obj->buffer.length is at least sizeof(*bios_return) before accessing the return code, and compute actual_outsize safely using min_t(u32, ...), which is sound specifically because the guard above already rules out obj->buffer.length being smaller than sizeof(*bios_return) by the time that subtraction runs.

Fixes c3021ea1beee ("hp-wmi: allow setting input and output buffer sizes separately")
---
 drivers/platform/x86/hp/hp-wmi.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/platform/x86/hp/hp-wmi.c +4 -3
index 615b4cf6fc451..8a0fe50ef0c29 100644
@@ -691,8 +691,9 @@ static int hp_wmi_perform_query(int query, enum hp_wmi_command command,
 		goto out_free;
 	}
 
-	if (obj->type != ACPI_TYPE_BUFFER) {
-		pr_warn("query 0x%x returned an invalid object 0x%x\n", query, ret);
+	if (obj->type != ACPI_TYPE_BUFFER ||
+	    obj->buffer.length < sizeof(*bios_return)) {
+		pr_warn("query 0x%x returned wrong type or too small buffer\n", query);
 		ret = -EINVAL;
 		goto out_free;
 	}
@@ -711,7 +712,7 @@ static int hp_wmi_perform_query(int query, enum hp_wmi_command command,
 	if (!outsize)
 		goto out_free;
 
-	actual_outsize = min(outsize, (int)(obj->buffer.length - sizeof(*bios_return)));
+	actual_outsize = min_t(u32, outsize, obj->buffer.length - sizeof(*bios_return));
 	memcpy(buffer, obj->buffer.pointer + sizeof(*bios_return), actual_outsize);
 	memset(buffer + actual_outsize, 0, outsize - actual_outsize);
 
Signature · 1 line
2.53.0
author maintainer
#680 lore raw

PATCH 674/1257 platform/x86/amd/pmf: Fix power_supply refcount leak in amd_pmf_get_battery_prop()

In reply to Greg Kroah-Hartman

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

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

From: Jack Boykin <[email protected]>

[ Upstream commit 9f3eebbbd1033de0abcc2694ba4b455d30fe33f9 ]

power_supply_get_by_name() takes a reference that is only dropped on the error path. On success it leaks, five times per policy evaluation. Unregistering the battery later trips the use_cnt WARN_ON in power_supply_unregister() and never frees it.

While here, return -ENODEV instead of an uninitialised 'value' when no battery matches, and stop at the first supply found rather than letting the last one in the table win.

Found by reading the code. Fix and changelog drafted with Claude Code (Fable 5.1) and reviewed by hand. Compile-tested only (allmodconfig, W=1, sparse); not run on Smart PC hardware.

Fixes f4627dfd0e19 ("platform/x86/amd/pmf: Add support to get inputs from other subsystems")
Assisted-by LLM sparse
---
 drivers/platform/x86/amd/pmf/spc.c | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)
drivers/platform/x86/amd/pmf/spc.c +3 -5
index 592ba4de4c7f1..efb09a7915f72 100644
@@ -199,13 +199,11 @@ static int amd_pmf_get_battery_prop(enum power_supply_property prop)
 			continue;
 
 		ret = power_supply_get_property(psy, prop, &value);
-		if (ret) {
-			power_supply_put(psy);
-			return ret;
-		}
+		power_supply_put(psy);
+		return ret ? ret : value.intval;
 	}
 
-	return value.intval;
+	return -ENODEV;
 }
 
 static int amd_pmf_get_battery_info(struct amd_pmf_dev *dev, struct ta_pmf_enact_table *in)
Signature · 1 line
2.53.0
author maintainer
#681 lore raw

PATCH 675/1257 platform/x86: asus-wmi: Serialize WMI method evaluations with a mutex

In reply to Greg Kroah-Hartman

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

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

From: Marco Scardovi <[email protected]>

[ Upstream commit b9428edaf4109e86a97254228d831767d0acc1f8 ]

Concurrent evaluations of ASUS WMI management methods (from ACPI notify, HID, userspace daemons, and debugfs) enter the BIOS ACPI/SMM interface simultaneously, triggering re-entrant SMIs or EC mailbox buffer corruption.

Fix this at the root by introducing a centralized evaluation helper (asus_wmi_evaluate_method_locked()) protected by a global mutex (asus_wmi_eval_lock) using guard(mutex). Route all evaluations of ASUS_WMI_MGMT_GUID (method3, method5, method_buf, and show_call) through this helper.

A static mutex is required because asus_wmi_evaluate_method() is an exported symbol used by external modules (such as hid-asus and asus-armoury) that lack access to struct asus_wmi drvdata, and the underlying ASUS ACPI/EC management method is a single physical platform resource.

The mutex is non-recursive: nested ACPI/WMI notify handlers must not call back into evaluate on the same task (defer via workqueue, as asus_rfkill_notify already does).

The sysfs-versus-notify race predates the later export of asus_wmi_evaluate_method(), so Fixes points at the original shared evaluate helper rather than that export.

---
 drivers/platform/x86/asus-wmi.c | 30 +++++++++++++++++++++---------
 1 file changed, 21 insertions(+), 9 deletions(-)
drivers/platform/x86/asus-wmi.c +21 -9
index 3cc0b96baeb34..84859646d7acd 100644
@@ -16,6 +16,7 @@
 #include <linux/acpi.h>
 #include <linux/backlight.h>
 #include <linux/bits.h>
+#include <linux/cleanup.h>
 #include <linux/debugfs.h>
 #include <linux/delay.h>
 #include <linux/dmi.h>
@@ -28,6 +29,7 @@
 #include <linux/leds.h>
 #include <linux/minmax.h>
 #include <linux/module.h>
+#include <linux/mutex.h>
 #include <linux/pci.h>
 #include <linux/pci_hotplug.h>
 #include <linux/platform_data/x86/asus-wmi.h>
@@ -353,6 +355,20 @@ static void asus_wmi_show_deprecated(void)
 
 /* WMI ************************************************************************/
 
+/*
+ * Concurrent evaluations of ASUS WMI methods can re-enter firmware
+ * SMI/EC mailbox handling and corrupt the mailbox.
+ */
+static DEFINE_MUTEX(asus_wmi_eval_lock);
+
+static acpi_status asus_wmi_evaluate_method_locked(u32 method_id,
+						   struct acpi_buffer *input,
+						   struct acpi_buffer *output)
+{
+	guard(mutex)(&asus_wmi_eval_lock);
+	return wmi_evaluate_method(ASUS_WMI_MGMT_GUID, 0, method_id, input, output);
+}
+
 static int asus_wmi_evaluate_method3(u32 method_id,
 		u32 arg0, u32 arg1, u32 arg2, u32 *retval)
 {
@@ -367,8 +383,7 @@ static int asus_wmi_evaluate_method3(u32 method_id,
 	union acpi_object *obj;
 	u32 tmp = 0;
 
-	status = wmi_evaluate_method(ASUS_WMI_MGMT_GUID, 0, method_id,
-				     &input, &output);
+	status = asus_wmi_evaluate_method_locked(method_id, &input, &output);
 
 	pr_debug("%s called (0x%08x) with args: 0x%08x, 0x%08x, 0x%08x\n",
 		__func__, method_id, arg0, arg1, arg2);
@@ -419,8 +434,7 @@ static int asus_wmi_evaluate_method5(u32 method_id,
 	union acpi_object *obj;
 	u32 tmp = 0;
 
-	status = wmi_evaluate_method(ASUS_WMI_MGMT_GUID, 0, method_id,
-				     &input, &output);
+	status = asus_wmi_evaluate_method_locked(method_id, &input, &output);
 
 	pr_debug("%s called (0x%08x) with args: 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x\n",
 		__func__, method_id, arg0, arg1, arg2, arg3, arg4);
@@ -467,8 +481,7 @@ static int asus_wmi_evaluate_method_buf(u32 method_id,
 	union acpi_object *obj;
 	int err = 0;
 
-	status = wmi_evaluate_method(ASUS_WMI_MGMT_GUID, 0, method_id,
-				     &input, &output);
+	status = asus_wmi_evaluate_method_locked(method_id, &input, &output);
 
 	pr_debug("%s called (0x%08x) with args: 0x%08x, 0x%08x\n",
 		__func__, method_id, arg0, arg1);
@@ -5052,9 +5065,8 @@ static int show_call(struct seq_file *m, void *data)
 	union acpi_object *obj;
 	acpi_status status;
 
-	status = wmi_evaluate_method(ASUS_WMI_MGMT_GUID,
-				     0, asus->debug.method_id,
-				     &input, &output);
+	status = asus_wmi_evaluate_method_locked(asus->debug.method_id,
+						 &input, &output);
 
 	if (ACPI_FAILURE(status))
 		return -EIO;
Signature · 1 line
2.53.0
author maintainer
#682 lore raw

PATCH 676/1257 platform/x86: oxpec: Fix Apex charge limit control

In reply to Greg Kroah-Hartman

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

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

From: Antheas Kapenekakis <[email protected]>

[ Upstream commit 0ccdf9a1381c7fb6d9e84abeb8e5d6c85dd07059 ]

The OneXPlayer Apex uses E5/E6 for battery bypass / charge limit, making it the first device to deviate. This was verified by a user on Windows with BIOS version 2.17 and later by running this kernel patch.

Drop X1_ from the MASK variables as they are common in all devices, introduce a board enum for Apex, and make it use the new E5/E6 registers for charge limit / bypass. Apply the same quirks as oxp_fly, since APEX uses the same registers otherwise.

---
 drivers/platform/x86/oxpec.c | 68 ++++++++++++++++++++++++++++--------
 1 file changed, 53 insertions(+), 15 deletions(-)
drivers/platform/x86/oxpec.c +53 -15
index 34bb17fca1481..38c272995437e 100644
@@ -50,6 +50,7 @@ enum oxp_board {
 	oxp_x1,
 	oxp_g1_i,
 	oxp_g1_a,
+	oxp_apex,
 };
 
 static enum oxp_board board;
@@ -93,11 +94,14 @@ static struct device *oxp_dev;
 #define OXP_X1_CHARGE_LIMIT_REG		0xA3 /* X1 charge limit (%) */
 #define OXP_X1_CHARGE_INHIBIT_REG	0xA4 /* X1 bypass charging */
 
-#define OXP_X1_CHARGE_INHIBIT_MASK_AWAKE	0x01
+#define OXP_APEX_CHARGE_LIMIT_REG	0xE5 /* Apex charge limit (%) */
+#define OXP_APEX_CHARGE_INHIBIT_REG	0xE6 /* Apex bypass charging */
+
+#define OXP_CHARGE_INHIBIT_MASK_AWAKE	0x01
 /* X1 Mask is 0x0A, F1Pro is 0x02 but the extra bit on the X1 does nothing. */
-#define OXP_X1_CHARGE_INHIBIT_MASK_OFF		0x02
-#define OXP_X1_CHARGE_INHIBIT_MASK_ALWAYS	(OXP_X1_CHARGE_INHIBIT_MASK_AWAKE | \
-						 OXP_X1_CHARGE_INHIBIT_MASK_OFF)
+#define OXP_CHARGE_INHIBIT_MASK_OFF		0x02
+#define OXP_CHARGE_INHIBIT_MASK_ALWAYS	(OXP_CHARGE_INHIBIT_MASK_AWAKE | \
+					 OXP_CHARGE_INHIBIT_MASK_OFF)
 
 static const struct dmi_system_id dmi_table[] = {
 	{
@@ -154,7 +158,7 @@ static const struct dmi_system_id dmi_table[] = {
 			DMI_MATCH(DMI_BOARD_VENDOR, "ONE-NETBOOK"),
 			DMI_EXACT_MATCH(DMI_BOARD_NAME, "ONEXPLAYER APEX"),
 		},
-		.driver_data = (void *)oxp_fly,
+		.driver_data = (void *)oxp_apex,
 	},
 	{
 		.matches = {
@@ -352,6 +356,7 @@ static umode_t tt_toggle_is_visible(struct kobject *kobj,
 	case oxp_x1:
 	case oxp_g1_i:
 	case oxp_g1_a:
+	case oxp_apex:
 		return attr->mode;
 	default:
 		break;
@@ -381,6 +386,7 @@ static ssize_t tt_toggle_store(struct device *dev,
 	case oxp_fly:
 	case oxp_mini_amd_pro:
 	case oxp_g1_a:
+	case oxp_apex:
 		reg = OXP_TURBO_SWITCH_REG;
 		mask = OXP_TURBO_TAKE_VAL;
 		break;
@@ -427,6 +433,7 @@ static ssize_t tt_toggle_show(struct device *dev,
 	case oxp_fly:
 	case oxp_mini_amd_pro:
 	case oxp_g1_a:
+	case oxp_apex:
 		reg = OXP_TURBO_SWITCH_REG;
 		mask = OXP_TURBO_TAKE_VAL;
 		break;
@@ -524,6 +531,7 @@ static bool oxp_psy_ext_supported(void)
 	case oxp_g1_i:
 	case oxp_g1_a:
 	case oxp_fly:
+	case oxp_apex:
 		return true;
 	default:
 		break;
@@ -537,12 +545,24 @@ static int oxp_psy_ext_get_prop(struct power_supply *psy,
 				enum power_supply_property psp,
 				union power_supply_propval *val)
 {
+	u8 limit_reg, inhibit_reg;
 	long raw_val;
 	int ret;
 
+	switch (board) {
+	case oxp_apex:
+		limit_reg = OXP_APEX_CHARGE_LIMIT_REG;
+		inhibit_reg = OXP_APEX_CHARGE_INHIBIT_REG;
+		break;
+	default:
+		limit_reg = OXP_X1_CHARGE_LIMIT_REG;
+		inhibit_reg = OXP_X1_CHARGE_INHIBIT_REG;
+		break;
+	}
+
 	switch (psp) {
 	case POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD:
-		ret = read_from_ec(OXP_X1_CHARGE_LIMIT_REG, 1, &raw_val);
+		ret = read_from_ec(limit_reg, 1, &raw_val);
 		if (ret)
 			return ret;
 		if (raw_val < 0 || raw_val > 100)
@@ -550,14 +570,14 @@ static int oxp_psy_ext_get_prop(struct power_supply *psy,
 		val->intval = raw_val;
 		return 0;
 	case POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR:
-		ret = read_from_ec(OXP_X1_CHARGE_INHIBIT_REG, 1, &raw_val);
+		ret = read_from_ec(inhibit_reg, 1, &raw_val);
 		if (ret)
 			return ret;
-		if ((raw_val & OXP_X1_CHARGE_INHIBIT_MASK_ALWAYS) ==
-		    OXP_X1_CHARGE_INHIBIT_MASK_ALWAYS)
+		if ((raw_val & OXP_CHARGE_INHIBIT_MASK_ALWAYS) ==
+		    OXP_CHARGE_INHIBIT_MASK_ALWAYS)
 			val->intval = POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE;
-		else if ((raw_val & OXP_X1_CHARGE_INHIBIT_MASK_AWAKE) ==
-			 OXP_X1_CHARGE_INHIBIT_MASK_AWAKE)
+		else if ((raw_val & OXP_CHARGE_INHIBIT_MASK_AWAKE) ==
+			 OXP_CHARGE_INHIBIT_MASK_AWAKE)
 			val->intval = POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE_AWAKE;
 		else
 			val->intval = POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO;
@@ -573,29 +593,41 @@ static int oxp_psy_ext_set_prop(struct power_supply *psy,
 				enum power_supply_property psp,
 				const union power_supply_propval *val)
 {
+	u8 limit_reg, inhibit_reg;
 	long raw_val;
 
+	switch (board) {
+	case oxp_apex:
+		limit_reg = OXP_APEX_CHARGE_LIMIT_REG;
+		inhibit_reg = OXP_APEX_CHARGE_INHIBIT_REG;
+		break;
+	default:
+		limit_reg = OXP_X1_CHARGE_LIMIT_REG;
+		inhibit_reg = OXP_X1_CHARGE_INHIBIT_REG;
+		break;
+	}
+
 	switch (psp) {
 	case POWER_SUPPLY_PROP_CHARGE_CONTROL_END_THRESHOLD:
 		if (val->intval < 0 || val->intval > 100)
 			return -EINVAL;
-		return write_to_ec(OXP_X1_CHARGE_LIMIT_REG, val->intval);
+		return write_to_ec(limit_reg, val->intval);
 	case POWER_SUPPLY_PROP_CHARGE_BEHAVIOUR:
 		switch (val->intval) {
 		case POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO:
 			raw_val = 0;
 			break;
 		case POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE_AWAKE:
-			raw_val = OXP_X1_CHARGE_INHIBIT_MASK_AWAKE;
+			raw_val = OXP_CHARGE_INHIBIT_MASK_AWAKE;
 			break;
 		case POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE:
-			raw_val = OXP_X1_CHARGE_INHIBIT_MASK_ALWAYS;
+			raw_val = OXP_CHARGE_INHIBIT_MASK_ALWAYS;
 			break;
 		default:
 			return -EINVAL;
 		}
 
-		return write_to_ec(OXP_X1_CHARGE_INHIBIT_REG, raw_val);
+		return write_to_ec(inhibit_reg, raw_val);
 	default:
 		return -EINVAL;
 	}
@@ -656,6 +688,7 @@ static int oxp_pwm_enable(void)
 	case oxp_x1:
 	case oxp_g1_i:
 	case oxp_g1_a:
+	case oxp_apex:
 		return write_to_ec(OXP_SENSOR_PWM_ENABLE_REG, PWM_MODE_MANUAL);
 	default:
 		return -EINVAL;
@@ -676,6 +709,7 @@ static int oxp_pwm_disable(void)
 	case oxp_x1:
 	case oxp_g1_i:
 	case oxp_g1_a:
+	case oxp_apex:
 		return write_to_ec(OXP_SENSOR_PWM_ENABLE_REG, PWM_MODE_AUTO);
 	default:
 		return -EINVAL;
@@ -696,6 +730,7 @@ static int oxp_pwm_read(long *val)
 	case oxp_x1:
 	case oxp_g1_i:
 	case oxp_g1_a:
+	case oxp_apex:
 		return read_from_ec(OXP_SENSOR_PWM_ENABLE_REG, 1, val);
 	default:
 		return -EOPNOTSUPP;
@@ -732,6 +767,7 @@ static int oxp_pwm_fan_speed(long *val)
 	case oxp_mini_amd_a07:
 	case oxp_mini_amd_pro:
 	case oxp_g1_a:
+	case oxp_apex:
 		return read_from_ec(OXP_SENSOR_FAN_REG, 2, val);
 	default:
 		return -EOPNOTSUPP;
@@ -764,6 +800,7 @@ static int oxp_pwm_input_write(long val)
 	case oxp_fly:
 	case oxp_mini_amd_pro:
 	case oxp_g1_a:
+	case oxp_apex:
 		return write_to_ec(OXP_SENSOR_PWM_REG, val);
 	default:
 		return -EOPNOTSUPP;
@@ -803,6 +840,7 @@ static int oxp_pwm_input_read(long *val)
 	case oxp_fly:
 	case oxp_mini_amd_pro:
 	case oxp_g1_a:
+	case oxp_apex:
 	default:
 		ret = read_from_ec(OXP_SENSOR_PWM_REG, 1, val);
 		if (ret)
Signature · 1 line
2.53.0
author maintainer
#683 lore raw

PATCH 677/1257 platform/x86: simatic-ipc: fix platform device leak on registration 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]>

[ Upstream commit 9523698252fd583d6987582b9c34ec6500d10986 ]

register_platform_devices() registers the battery, LED, and watchdog platform devices in sequence. If LED registration fails, the battery device remains registered. If watchdog registration fails, the LED and battery devices remain registered.

These failure paths leave successful platform_device_register_data() calls without the matching platform_device_unregister() calls.

Add an unwind ladder to unregister previously registered platform devices in reverse order before returning the registration error.

The issue was identified by a static analysis tool I developed and confirmed by manual review.

Fixes dd123e62bded ("platform/x86: simatic-ipc: add main driver for Siemens devices")
---
 drivers/platform/x86/siemens/simatic-ipc.c | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)
drivers/platform/x86/siemens/simatic-ipc.c +17 -4
index 7039874d8f112..4a4509fc9263e 100644
@@ -92,6 +92,7 @@ static int register_platform_devices(u32 station_id)
 	u8 wdtmode = SIMATIC_IPC_DEVICE_NONE;
 	u8 battmode = SIMATIC_IPC_DEVICE_NONE;
 	char *pdevname;
+	int ret;
 	int i;
 
 	for (i = 0; i < ARRAY_SIZE(device_modes); i++) {
@@ -139,8 +140,10 @@ static int register_platform_devices(u32 station_id)
 				pdevname, PLATFORM_DEVID_NONE,
 				&platform_data,
 				sizeof(struct simatic_ipc_platform));
-		if (IS_ERR(ipc_led_platform_device))
-			return PTR_ERR(ipc_led_platform_device);
+		if (IS_ERR(ipc_led_platform_device)) {
+			ret = PTR_ERR(ipc_led_platform_device);
+			goto err_unregister_batt;
+		}
 
 		pr_debug("device=%s created\n",
 			 ipc_led_platform_device->name);
@@ -153,8 +156,10 @@ static int register_platform_devices(u32 station_id)
 				KBUILD_MODNAME "_wdt", PLATFORM_DEVID_NONE,
 				&platform_data,
 				sizeof(struct simatic_ipc_platform));
-		if (IS_ERR(ipc_wdt_platform_device))
-			return PTR_ERR(ipc_wdt_platform_device);
+		if (IS_ERR(ipc_wdt_platform_device)) {
+			ret = PTR_ERR(ipc_wdt_platform_device);
+			goto err_unregister_led;
+		}
 
 		pr_debug("device=%s created\n",
 			 ipc_wdt_platform_device->name);
@@ -169,6 +174,14 @@ static int register_platform_devices(u32 station_id)
 	}
 
 	return 0;
+
+err_unregister_led:
+	if (ledmode != SIMATIC_IPC_DEVICE_NONE)
+		platform_device_unregister(ipc_led_platform_device);
+err_unregister_batt:
+	if (battmode != SIMATIC_IPC_DEVICE_NONE)
+		platform_device_unregister(ipc_batt_platform_device);
+	return ret;
 }
 
 static void request_additional_modules(u32 station_id)
Signature · 1 line
2.53.0
author maintainer
#684 lore raw

PATCH 678/1257 platform/x86/amd: hfi: Fix out-of-bounds reads when parsing ranking data

In reply to Greg Kroah-Hartman

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

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

From: Mario Limonciello <[email protected]>

[ Upstream commit b7b273844b94af9cc64907dccd9e7997c2b60f1a ]

amd_hfi_fill_metadata() parses CPU core ranking data out of the firmware-provided PCC shared memory but trusts two values it should not:

- n_bitmaps is used to bound the outer loop that reads the APIC ID bitmaps from table_data[], but it is never validated against the size of the shared memory region (pcct_ext->length). A firmware-supplied count larger than the region reads past the end of table_data.

- When resolving the base of the ranking data for a processor, the pointer is shifted by an extra "i * nr_class" term, where i is the current bitmap index. The per-processor offset is already applied through apic_index, which uses the running count of active processors (apic_start). The extra shift compounds for every logical processor beyond the first bitmap (APIC ID >= 32), reading out of bounds.

Both result in out-of-bounds reads that can corrupt the ranking metrics, oops, or otherwise destabilise the system.

Reject an n_bitmaps value that would not fit within the shared memory region, and drop the bogus "i * nr_class" term so the ranking data is addressed only through its correct per-processor offset.

Fixes d4e95ea7a78e ("platform/x86: hfi: Parse CPU core ranking data from shared memory")
---
 drivers/platform/x86/amd/hfi/hfi.c | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)
drivers/platform/x86/amd/hfi/hfi.c +16 -4
index e1c776b71f3e6..6d1d3b6c28a97 100644
@@ -20,6 +20,7 @@
 #include <linux/module.h>
 #include <linux/mailbox_client.h>
 #include <linux/mutex.h>
+#include <linux/overflow.h>
 #include <linux/percpu-defs.h>
 #include <linux/platform_device.h>
 #include <linux/smp.h>
@@ -168,6 +169,21 @@ static int amd_hfi_fill_metadata(struct amd_hfi_data *amd_hfi_data)
 		return -EINVAL;
 	}
 
+	/*
+	 * The bitmaps enumerating the APIC IDs occupy the first n_bitmaps
+	 * words of table_data.  Reject a firmware-provided count that would
+	 * push those reads past the end of the shared memory region.
+	 */
+	if (struct_size(amd_hfi_data->shmem, table_data, amd_hfi_data->shmem->n_bitmaps) >
+	    pcct_ext->length) {
+		dev_err(amd_hfi_data->dev, "invalid number of bitmaps: %u\n",
+			amd_hfi_data->shmem->n_bitmaps);
+		return -EINVAL;
+	}
+
+	/* The ranking data for each processor follows the bitmaps */
+	u32 *table = amd_hfi_data->shmem->table_data + amd_hfi_data->shmem->n_bitmaps;
+
 	for (unsigned int i = 0; i < amd_hfi_data->shmem->n_bitmaps; i++) {
 		u32 bitmap = amd_hfi_data->shmem->table_data[i];
 
@@ -192,10 +208,6 @@ static int amd_hfi_fill_metadata(struct amd_hfi_data *amd_hfi_data)
 			info = per_cpu_ptr(&amd_hfi_cpuinfo, cpu_index);
 			apic_index = apic_start * info->nr_class * 2;
 			for (unsigned int k = 0; k < info->nr_class; k++) {
-				u32 *table = amd_hfi_data->shmem->table_data +
-					     amd_hfi_data->shmem->n_bitmaps +
-					     i * info->nr_class;
-
 				info->amd_hfi_classes[k].eff = table[apic_index + 2 * k];
 				info->amd_hfi_classes[k].perf = table[apic_index + 2 * k + 1];
 			}
Signature · 1 line
2.53.0
author maintainer
#685 lore raw

PATCH 679/1257 platform/x86/intel-uncore-freq: Continue restoring limits on resume

In reply to Greg Kroah-Hartman

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

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

From: Guixiong Wei <[email protected]>

[ Upstream commit 38998529f45c02edcf96b0a3ddd3c83de6d11bbe ]

The PM notifier iterates over every uncore frequency instance to restore user-configured MSR_UNCORE_RATIO_LIMIT values after resume. Entries that have never been configured legitimately have stored_uncore_data set to zero.

The refactoring that split common and enumeration code changed the iteration from active control CPUs to all allocated instances. It also changed the skip for an invalid or unconfigured entry from continue to return, causing that entry to terminate the entire restore operation.

On a multi-package or multi-die system, configuring only a later instance therefore leaves its limit unrestored after suspend, hibernation, or restore if an earlier entry is invalid or unconfigured.

Use continue to skip only the current entry and restore all remaining configured instances.

---
 drivers/platform/x86/intel/uncore-frequency/uncore-frequency.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/platform/x86/intel/uncore-frequency/uncore-frequency.c +1 -1
index 667f2c8b9594a..c44e7e38cae25 100644
@@ -211,7 +211,7 @@ static int uncore_pm_notify(struct notifier_block *nb, unsigned long mode,
 			struct uncore_data *data = &uncore_instances[i];
 
 			if (!data || !data->valid || !data->stored_uncore_data)
-				return 0;
+				continue;
 
 			wrmsrq_on_cpu(data->control_cpu, MSR_UNCORE_RATIO_LIMIT,
 				      data->stored_uncore_data);
Signature · 1 line
2.53.0
author maintainer
#686 lore raw

PATCH 680/1257 platform/x86/intel/vsec: Fix inverted walk_header() test in get_features()

In reply to Greg Kroah-Hartman

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

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

From: David E. Box <[email protected]>

[ Upstream commit 3678e39c6aaeb9aa380c7357b24f7d55955543f8 ]

intel_vsec_walk_header() used to return a bool that was true when devices were found. It was converted to return 0 on success and a negative errno on failure, but the boolean test in intel_vsec_get_features() was left unchanged, so its meaning is now inverted.

A successful walk returns 0 and leaves found set to false, while a failed walk returns an error that evaluates to true. When no other capabilities are present, intel_vsec_pci_init() then returns -ENODEV even though the auxiliary devices were created, and the driver core tears them back down.

This affects platforms that have no DVSEC or VSEC capabilities and describe their features through device_data instead, which today means DG1. Test the return value for success explicitly.

Fixes a6ce8bf3c993 ("platform/x86/intel/vsec: Return real error codes from registration path")
Assisted-by LLM
---
 drivers/platform/x86/intel/vsec.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/platform/x86/intel/vsec.c +1 -1
index 5ab2215fdd7fa..7d51f27f09bc9 100644
@@ -641,7 +641,7 @@ static bool intel_vsec_get_features(struct pci_dev *pdev,
 		found = true;
 
 	if (info && (info->quirks & VSEC_QUIRK_NO_DVSEC) &&
-	    intel_vsec_walk_header(&pdev->dev, info))
+	    !intel_vsec_walk_header(&pdev->dev, info))
 		found = true;
 
 	return found;
Signature · 1 line
2.53.0
author maintainer
#687 lore raw

PATCH 681/1257 fbdev: sh_mobile_lcdcfb: Restore the per-overlay sysfs attributes

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

[ Upstream commit 317a8be730919177956be32422ebe00cf7e46710 ]

The ovl_* files documented in Documentation/ABI/testing/sysfs-devices-platform-sh_mobile_lcdc_fb no longer exist.

Commit a979182a2453 ("fbdev: lcdcfb: Register sysfs groups through driver core") moved the attributes from each overlay's framebuffer device to the platform driver's dev_groups and renamed them overlay_*. There is now only one set of attributes for the whole LCDC. The callbacks still expect dev_get_drvdata() to return a struct fb_info, but the platform device holds struct sh_mobile_lcdc_priv, so they access the wrong structure.

Restore the documented names and register the group on each overlay's framebuffer device with device_add_groups(). Remove it with device_remove_groups() before unregistering the framebuffer. Skip creation when dev_of_fbinfo(info) is NULL, as the old device_create_file() calls did.

Drop the CONFIG_FB_DEVICE guard, since the driver already depends on it.

Fixes a979182a2453 ("fbdev: lcdcfb: Register sysfs groups through driver core")
Assisted-by LLM
---
 drivers/video/fbdev/sh_mobile_lcdcfb.c | 39 +++++++++++++++++---------
 1 file changed, 25 insertions(+), 14 deletions(-)
drivers/video/fbdev/sh_mobile_lcdcfb.c +25 -14
index e8324b01700f6..5743c96d54814 100644
@@ -1337,22 +1337,24 @@ overlay_rop3_store(struct device *dev, struct device_attribute *attr,
 	return count;
 }
 
-static DEVICE_ATTR_RW(overlay_alpha);
-static DEVICE_ATTR_RW(overlay_mode);
-static DEVICE_ATTR_RW(overlay_position);
-static DEVICE_ATTR_RW(overlay_rop3);
-
-static struct attribute *overlay_sysfs_attrs[] __maybe_unused = {
-	&dev_attr_overlay_alpha.attr,
-	&dev_attr_overlay_mode.attr,
-	&dev_attr_overlay_position.attr,
-	&dev_attr_overlay_rop3.attr,
+static struct device_attribute dev_attr_ovl_alpha =
+	__ATTR(ovl_alpha, 0644, overlay_alpha_show, overlay_alpha_store);
+static struct device_attribute dev_attr_ovl_mode =
+	__ATTR(ovl_mode, 0644, overlay_mode_show, overlay_mode_store);
+static struct device_attribute dev_attr_ovl_position =
+	__ATTR(ovl_position, 0644, overlay_position_show, overlay_position_store);
+static struct device_attribute dev_attr_ovl_rop3 =
+	__ATTR(ovl_rop3, 0644, overlay_rop3_show, overlay_rop3_store);
+
+static struct attribute *overlay_sysfs_attrs[] = {
+	&dev_attr_ovl_alpha.attr,
+	&dev_attr_ovl_mode.attr,
+	&dev_attr_ovl_position.attr,
+	&dev_attr_ovl_rop3.attr,
 	NULL,
 };
 
-#ifdef CONFIG_FB_DEVICE
 ATTRIBUTE_GROUPS(overlay_sysfs);
-#endif
 
 static const struct fb_fix_screeninfo sh_mobile_lcdc_overlay_fix  = {
 	.id =		"SH Mobile LCDC",
@@ -1510,9 +1512,10 @@ sh_mobile_lcdc_overlay_fb_unregister(struct sh_mobile_lcdc_overlay *ovl)
 {
 	struct fb_info *info = ovl->info;
 
-	if (info == NULL || info->dev == NULL)
+	if (!info || !dev_of_fbinfo(info))
 		return;
 
+	device_remove_groups(dev_of_fbinfo(info), overlay_sysfs_groups);
 	unregister_framebuffer(ovl->info);
 }
 
@@ -1530,6 +1533,15 @@ sh_mobile_lcdc_overlay_fb_register(struct sh_mobile_lcdc_overlay *ovl)
 	if (ret < 0)
 		return ret;
 
+	/* The framebuffer device is optional, see fb_device_create(). */
+	if (dev_of_fbinfo(info)) {
+		ret = device_add_groups(dev_of_fbinfo(info), overlay_sysfs_groups);
+		if (ret < 0) {
+			unregister_framebuffer(info);
+			return ret;
+		}
+	}
+
 	dev_info(lcdc->dev, "registered %s/overlay %u as %dx%d %dbpp.\n",
 		 dev_name(lcdc->dev), ovl->index, info->var.xres,
 		 info->var.yres, info->var.bits_per_pixel);
@@ -2637,7 +2649,6 @@ static int sh_mobile_lcdc_probe(struct platform_device *pdev)
 static struct platform_driver sh_mobile_lcdc_driver = {
 	.driver		= {
 		.name		= "sh_mobile_lcdc_fb",
-		.dev_groups	= overlay_sysfs_groups,
 		.pm		= &sh_mobile_lcdc_dev_pm_ops,
 	},
 	.probe		= sh_mobile_lcdc_probe,
Signature · 1 line
2.53.0
author maintainer
#688 lore raw

PATCH 682/1257 fbdev: core: Initialize modelist in framebuffer_alloc()

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]>

[ Upstream commit 0c9cb9321cb3863b52bdea4b8ae5a27705762c9e ]

framebuffer_alloc() returns zeroed memory, so info->modelist starts out with NULL next and prev pointers. The list head is initialized only later, by fb_videomode_to_modelist() or by do_register_framebuffer().

The "fix potential memory leak" commits listed below added fb_destroy_modelist(&info->modelist) to the probe error paths of s3fb, tdfxfb, tridentfb, i740fb and carminefb. These paths can run before the list head is initialized:

- s3fb, tdfxfb, tridentfb and i740fb call fb_videomode_to_modelist() only after a successful EDID read, and tridentfb can also hit the error path on an ioremap() or kmalloc() failure before that;
- carminefb jumps to the error path when fb_find_mode() fails, before its fb_videomode_to_modelist() call.

fb_destroy_modelist() then dereferences the NULL head. Reproduced on Debian 12 (6.1.180) by binding s3fb to a VGA device without EDID and forcing fb_alloc_cmap() to fail:

s3fb 0000:00:03.0: cannot allocate colormap

  BUG: kernel NULL pointer dereference, address: 0000000000000000
  RIP: 0010:fb_destroy_modelist+0x10/0x80
  Call Trace:
   s3_pci_probe.cold+0x12b/0x2bf [s3fb]
   local_pci_probe+0x41/0x80
   pci_device_probe+0xc3/0x240
   really_probe+0xde/0x380
   __driver_probe_device+0x84/0x150
   driver_probe_device+0x1f/0x90
   __driver_attach+0xce/0x1c0
   bus_for_each_dev+0x87/0xd0
   bus_add_driver+0x1ae/0x200
   driver_register+0x89/0xe0
   do_one_initcall+0x59/0x220
   do_init_module+0x4a/0x1f0

Initialize the list head in framebuffer_alloc(), so info->modelist is always a valid, possibly empty, list and fb_destroy_modelist() is safe on every error path. Keep the lazy initialization in do_register_framebuffer(), as drivers that embed struct fb_info rather than calling framebuffer_alloc() still depend on it.

Fixes 3b0ed04bc852 ("fbdev: s3fb: fix potential memory leak in s3_pci_probe()")
Fixes bb019d755366 ("fbdev: tdfxfb: fix potential memory leak in tdfxfb_probe()")
Fixes 7a35ec619d9a ("fbdev: tridentfb: fix potential memory leak in trident_pci_probe()")
Fixes 5936063409af ("fbdev: i740fb: fix potential memory leak in i740fb_probe()")
Fixes 6fcca16a2b19 ("fbdev: carminefb: fix potential memory leak in alloc_carmine_fb()")
---
 drivers/video/fbdev/core/fb_info.c | 1 +
 1 file changed, 1 insertion(+)
drivers/video/fbdev/core/fb_info.c +1 -0
index 52f9bd2c5417a..05988a936bebb 100644
@@ -43,6 +43,7 @@ struct fb_info *framebuffer_alloc(size_t size, struct device *dev)
 	info->device = dev;
 	info->fbcon_rotate_hint = -1;
 	info->blank = FB_BLANK_UNBLANK;
+	INIT_LIST_HEAD(&info->modelist);
 
 #if IS_ENABLED(CONFIG_FB_BACKLIGHT)
 	mutex_init(&info->bl_curve_mutex);
Signature · 1 line
2.53.0
author maintainer
#689 lore raw

PATCH 683/1257 fbdev: ssd1307fb: check for fb_deferred_io_init() error

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Stoakes (ARM) <[email protected]>

[ Upstream commit 81ae1f9a6c850efab3e5dec6b7c9aa5c587f92b7 ]

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

Currently ssd1307fb_probe() ignores its return value.

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

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

Fix this by checking for the error.

Fixes 56c134f7f1b5 ("fbdev: Track deferred-I/O pages in pageref struct")
---
 drivers/video/fbdev/ssd1307fb.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/video/fbdev/ssd1307fb.c +5 -1
index 4d185c7542843..8fd96c37ee1ab 100644
@@ -767,7 +767,11 @@ static int ssd1307fb_probe(struct i2c_client *client)
 	info->fix.smem_start = __pa(vmem);
 	info->fix.smem_len = vmem_size;
 
-	fb_deferred_io_init(info);
+	ret = fb_deferred_io_init(info);
+	if (ret) {
+		dev_err(dev, "failed to init fb deferred io: %d\n", ret);
+		goto fb_defio_error;
+	}
 
 	i2c_set_clientdata(client, info);
 
Signature · 1 line
2.53.0
author maintainer
#690 lore raw

PATCH 684/1257 fbdev: xen-fbfront: check for fb_deferred_io_init() error

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Stoakes (ARM) <[email protected]>

[ Upstream commit 5b234b0dd29d79207c059c7b40851dd1e934fa3a ]

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

Currently xenfb_probe() ignores its return value.

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

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

Fix this by checking for the error.

Fixes 56c134f7f1b5 ("fbdev: Track deferred-I/O pages in pageref struct")
---
 drivers/video/fbdev/xen-fbfront.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/video/fbdev/xen-fbfront.c +6 -1
index 4385976277ac3..7ef909d4242d9 100644
@@ -443,7 +443,11 @@ static int xenfb_probe(struct xenbus_device *dev,
 	}
 
 	fb_info->fbdefio = &xenfb_defio;
-	fb_deferred_io_init(fb_info);
+	ret = fb_deferred_io_init(fb_info);
+	if (ret < 0) {
+		xenbus_dev_fatal(dev, ret, "fb_deferred_io_init");
+		goto error_cmap;
+	}
 
 	xenfb_init_shared_page(info, fb_info);
 
@@ -465,6 +469,7 @@ static int xenfb_probe(struct xenbus_device *dev,
 
 error_fb:
 	fb_deferred_io_cleanup(fb_info);
+error_cmap:
 	fb_dealloc_cmap(&fb_info->cmap);
 	framebuffer_release(fb_info);
 error_nomem:
Signature · 1 line
2.53.0
author maintainer
#691 lore raw

PATCH 685/1257 fbdev: udlfb: check for fb_deferred_io_init() error

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Stoakes (ARM) <[email protected]>

[ Upstream commit eae055f33e41e1d3e1a7e905bdcb1e9f196ed31d ]

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

Currently dlfb_ops_open() ignores its return value.

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

fb_open() will then dereference a NULL pointer (calling fb_deferred_io_open()) as soon as dlfb_ops_open() returns.

Additionally, if the allocation of info->fbdefio itself fails, dlfb_ops_open() sets info->fbdefio to NULL and invokes fb_deferred_io_init() regardless, hitting BUG_ON(!fbdefio).

Fix this by only invoking fb_deferred_io_init() if the allocation succeeded, and checking for the error.

The driver already supports operating without deferred I/O, so in either case fall back to that by setting info->fbdefio to NULL.

The ignored return value was introduced in commit 56c134f7f1b5 ("fbdev:
Track deferred-I/O pages in pageref struct").

However, the BUG_ON() issue originates from the earlier commit 5bea1fbf9423 ("staging: udlfb: fix incorrect fb_defio implementation for multiple framebuffers"), so target that for the fix.

Fixes 5bea1fbf9423 ("staging: udlfb: fix incorrect fb_defio implementation for multiple framebuffers")
---
 drivers/video/fbdev/udlfb.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/video/fbdev/udlfb.c +6 -3
index 92b352bc7e969..8b7b4bdac4fbf 100644
@@ -947,10 +947,13 @@ static int dlfb_ops_open(struct fb_info *info, int user)
 			fbdefio->delay = DL_DEFIO_WRITE_DELAY;
 			fbdefio->sort_pagereflist = true;
 			fbdefio->deferred_io = dlfb_dpy_deferred_io;
-		}
 
-		info->fbdefio = fbdefio;
-		fb_deferred_io_init(info);
+			info->fbdefio = fbdefio;
+			if (fb_deferred_io_init(info)) {
+				kfree(fbdefio);
+				info->fbdefio = NULL;
+			}
+		}
 	}
 
 	dev_dbg(info->dev, "open, user=%d fb_info=%p count=%d\n",
Signature · 1 line
2.53.0
author maintainer
#692 lore raw

PATCH 686/1257 fbdev: smscufx: check for fb_deferred_io_init() error

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Stoakes (ARM) <[email protected]>

[ Upstream commit 8ea6c6e77ccf887f3e68c64f4c261071a345da1e ]

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

Currently ufx_ops_open() ignores its return value.

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

fb_open() will then dereference a NULL pointer (calling fb_deferred_io_open()) as soon as ufx_ops_open() returns.

Additionally, if the allocation of info->fbdefio itself fails, ufx_ops_open() sets info->fbdefio to NULL and invokes fb_deferred_io_init() regardless, hitting BUG_ON(!fbdefio).

Fix this by only invoking fb_deferred_io_init() if the allocation succeeded, and checking for the error.

The driver already supports operating without deferred I/O, so in either case fall back to that by setting info->fbdefio to NULL.

The ignored return value was introduced in commit 56c134f7f1b5 ("fbdev:
Track deferred-I/O pages in pageref struct").

However, the BUG_ON() issue originates from the earlier commit 3c8a63e22a08 ("Add support for SMSC UFX6000/7000 USB display adapters"), so target that for the fix.

Fixes 3c8a63e22a08 ("Add support for SMSC UFX6000/7000 USB display adapters")
---
 drivers/video/fbdev/smscufx.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/video/fbdev/smscufx.c +6 -3
index 5704f60e1741b..34d8abd5b3544 100644
@@ -1041,10 +1041,13 @@ static int ufx_ops_open(struct fb_info *info, int user)
 		if (fbdefio) {
 			fbdefio->delay = UFX_DEFIO_WRITE_DELAY;
 			fbdefio->deferred_io = ufx_dpy_deferred_io;
-		}
 
-		info->fbdefio = fbdefio;
-		fb_deferred_io_init(info);
+			info->fbdefio = fbdefio;
+			if (fb_deferred_io_init(info)) {
+				kfree(fbdefio);
+				info->fbdefio = NULL;
+			}
+		}
 	}
 
 	pr_debug("open /dev/fb%d user=%d fb_info=%p count=%d",
Signature · 1 line
2.53.0
author maintainer
#693 lore raw

PATCH 687/1257 fbdev: sh_mobile_lcdc: check for fb_deferred_io_init() error

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Stoakes (ARM) <[email protected]>

[ Upstream commit 5192201aaac2a923ff98306e3ccda58718ee395f ]

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

Currently sh_mobile_lcdc_start() ignores its return value.

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

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

Fix this by checking for the error.

Also clear info->fbdefio in that case, so that sh_mobile_lcdc_stop() does not attempt to clean up deferred I/O state that was never initialised.

Fixes 56c134f7f1b5 ("fbdev: Track deferred-I/O pages in pageref struct")
---
 drivers/video/fbdev/sh_mobile_lcdcfb.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/video/fbdev/sh_mobile_lcdcfb.c +5 -1
index 5743c96d54814..a8ef7c5993919 100644
@@ -1042,7 +1042,11 @@ static int sh_mobile_lcdc_start(struct sh_mobile_lcdc_priv *priv)
 			ch->defio.deferred_io = sh_mobile_lcdc_deferred_io;
 			ch->defio.delay = msecs_to_jiffies(tmp);
 			ch->info->fbdefio = &ch->defio;
-			fb_deferred_io_init(ch->info);
+			ret = fb_deferred_io_init(ch->info);
+			if (ret) {
+				ch->info->fbdefio = NULL;
+				return ret;
+			}
 		}
 
 		sh_mobile_lcdc_display_on(ch);
Signature · 1 line
2.53.0
author maintainer
#694 lore raw

PATCH 688/1257 fbdev: kyro: Release WC setup on registration failure

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit d3bc005a62945aec57059201092b12b7c955e5a7 ]

If register_framebuffer() fails, kyrofb_probe() frees the framebuffer without releasing its write-combining range. Release the range before freeing the framebuffer. Earlier failures still skip this cleanup.

The missing cleanup already exists in the initial Git import, before the conversion from mtrr_add() to arch_phys_wc_add().

This issue was identified during our ongoing static-analysis research while reviewing kernel code.

---
 drivers/video/fbdev/kyro/fbdev.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/video/fbdev/kyro/fbdev.c +3 -1
index c237389888229..94d6af54e6c46 100644
@@ -765,7 +765,7 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
 	fb_memset_io(info->screen_base, 0, size);
 
 	if (register_framebuffer(info) < 0)
-		goto out_free_fb;
+		goto out_free_wc;
 
 	fb_info(info, "%s frame buffer device, at %dx%d@%d using %ldk/%ldk of VRAM\n",
 		info->fix.id,
@@ -776,6 +776,8 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
 
 	return 0;
 
+out_free_wc:
+	arch_phys_wc_del(currentpar->wc_cookie);
 out_free_fb:
 	framebuffer_release(info);
 
Signature · 1 line
2.53.0
author maintainer
#695 lore raw

PATCH 689/1257 fbdev: nvidia: Release write-combining handle on probe failure

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit 8710af6a35201a6d01b5af8f7e4bad29cc40467f ]

Failures in nvidia_set_fbinfo() or register_framebuffer() leave the handle from arch_phys_wc_add() allocated. Release it in the shared error path, as nvidiafb_remove() already does on normal removal.

The missing cleanup was already present in the initial Git import, when the driver used mtrr_add() directly.

This issue was identified during our ongoing static-analysis research while reviewing kernel code.

---
 drivers/video/fbdev/nvidia/nvidia.c | 1 +
 1 file changed, 1 insertion(+)
drivers/video/fbdev/nvidia/nvidia.c +1 -0
index 4ef7a5ba43cc4..395f5d0455fa4 100644
@@ -1423,6 +1423,7 @@ static int nvidiafb_probe(struct pci_dev *pd, const struct pci_device_id *ent)
 	return 0;
 
 err_out_iounmap_fb:
+	arch_phys_wc_del(par->wc_cookie);
 	fb_destroy_modelist(&info->modelist);
 err_out_free_base1:
 	fb_destroy_modedb(info->monspecs.modedb);
Signature · 1 line
2.53.0
author maintainer
#696 lore raw

PATCH 690/1257 arm64/mm: Treat faults taken by EFI runtime firmware as kernel faults

In reply to Greg Kroah-Hartman

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

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

From: Ard Biesheuvel <[email protected]>

[ Upstream commit 171be684bfa3020f81bf0b85bc7ac42024575fbf ]

When EFI runtime services are invoked from a preemptible kthread, the kthread runs with efi_mm installed via kthread_use_mm() and preemption enabled, so neither faulthandler_disabled() nor !mm applies in do_page_fault(). A permission fault taken by the firmware on one of its own (TTBR0) mappings then hits the 'access to user memory outside uaccess routines' check and oopses, without efi_runtime_fixup_exception() ever being consulted.

efi_mm has no VMAs, so there is nothing for the mm to resolve. Send such faults to no_context directly, so that __do_kernel_fault() can recover from them as it does when the call is made with preemption disabled.

Fixes a5baf582f4c0 ("arm64/efi: Call EFI runtime services without disabling preemption")
---
 arch/arm64/mm/fault.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
arch/arm64/mm/fault.c +3 -2
index 75c3e463df2ef..357be4c9106df 100644
@@ -620,9 +620,10 @@ static int __kprobes do_page_fault(unsigned long far, unsigned long esr,
 
 	/*
 	 * If we're in an interrupt or have no user context, we must not take
-	 * the fault.
+	 * the fault. EFI runtime services may execute with preemption enabled
+	 * and mm == &efi_mm, but faults need to be treated as kernel faults.
 	 */
-	if (faulthandler_disabled() || !mm)
+	if (faulthandler_disabled() || !mm || mm_is_efi(mm))
 		goto no_context;
 
 	if (user_mode(regs))
Signature · 1 line
2.53.0
author maintainer
#697 lore raw

PATCH 691/1257 tools/dma: fix building from the top level with O=

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit 352665c55877368854f87724698dad0b453444eb ]

"make O=<dir> tools/dma" fails:

Makefile:27: /tools/build/Makefile.include: No such file or directory

tools/Makefile clears srctree, and the dma Makefile only works it out again when building_out_of_srctree is not set, which the top-level Makefile sets for O= builds.

Also work out srctree when it is empty, as tools/bpf/Makefile does since commit a89b2cbf71d64 ("tools, bpf: Fix build for 'make -s tools/bpf O=<dir>'").

Fixes f74ee32963f1b ("tools/dma: move dma_map_benchmark from selftests to tools/dma")
Assisted-by LLM
---
 tools/dma/Makefile | 6 ++++++
 1 file changed, 6 insertions(+)
tools/dma/Makefile +6 -0
index 0c239a6b9eae5..20ae7f09cd206 100644
@@ -7,7 +7,13 @@ bindir ?= /usr/bin
 # isn't set and when invoked from selftests build, where srctree
 # is set to ".". building_out_of_srctree is undefined for in srctree
 # builds
+ifeq ($(srctree),)
+update_srctree := 1
+endif
 ifndef building_out_of_srctree
+update_srctree := 1
+endif
+ifeq ($(update_srctree),1)
 srctree := $(patsubst %/,%,$(dir $(CURDIR)))
 srctree := $(patsubst %/,%,$(dir $(srctree)))
 endif
Signature · 1 line
2.53.0
author maintainer
#698 lore raw

PATCH 692/1257 serial: sc16is7xx: fix data corruption due to unexpected xon/xoff

In reply to Greg Kroah-Hartman

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

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

From: Martin Fuzzey <[email protected]>

[ Upstream commit 8bb50e95c0abd44607bc60a43032c1dbf7470d5a ]

The hardware supports automatically sending XON/OFF based on the FIFO status and that is already implemented by the driver. However that capability was not announced with the UPF_SOFT_FLOW bit.

When the port is opened with the default of XON enabled the driver configures that in the hardware.
If userspace does not want XON/OFF (which is normally the case) it will use TCSETS to disactivate it. However the serial core optimises this to only notify the driver if someting imporant has changed, and for XON/XOFF thit is only if the driver declares UPF_SOFT_FLOW.

So we end up with unwanted XON/XOFF in the data stream.

The problem only occurs if nothing else needed to be set by termios, ie if the user space requested values are the same as the default values, except for XON/XOFF.
Since the default speed is 9600 this means that the problem only occurs when requesting 9600, otherwise the call to the driver will be made to change the speed, and that will also clear the XON/XOFF.
As 9600 is quite rare these days that probably explains why this hasn't already been seen.

It also only occurs on the first port open after boot since the subsequent opens will use the "logical state" set by TCSETS but not communicated to the driver the first time.

---
 drivers/tty/serial/sc16is7xx.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/tty/serial/sc16is7xx.c +1 -1
index 296079c16fdb9..7ddc8a38adab4 100644
@@ -1516,7 +1516,7 @@ static int sc16is7xx_setup_channel(struct sc16is7xx_one *one, int i,
 	/* Initialize port data */
 	port->type	= PORT_SC16IS7XX;
 	port->fifosize	= SC16IS7XX_FIFO_SIZE;
-	port->flags	= UPF_FIXED_TYPE | UPF_LOW_LATENCY;
+	port->flags	= UPF_FIXED_TYPE | UPF_LOW_LATENCY | UPF_SOFT_FLOW;
 	port->iotype	= UPIO_BUS;
 	port->rs485_config = sc16is7xx_config_rs485;
 	port->rs485_supported = sc16is7xx_rs485_supported;
Signature · 1 line
2.53.0
author maintainer
#699 lore raw

PATCH 693/1257 serial: sc16is7xx: declare MCR and IER as volatile registers

In reply to Greg Kroah-Hartman

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

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

From: Hugo Villeneuve <[email protected]>

[ Upstream commit 1c41d09dcd07ee9648e20aa8238e404c2e6a12fb ]

MCR register has the same address as XON1 register. IER register has the same address as DLH register.

Which register is accessed depends on bits configuration in some other registers.

To prevent potential access errors, declare MCR and IER as volatile registers.

---
 drivers/tty/serial/sc16is7xx.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/tty/serial/sc16is7xx.c +2 -0
index 7ddc8a38adab4..fba5885595957 100644
@@ -501,7 +501,9 @@ static bool sc16is7xx_regmap_volatile(struct device *dev, unsigned int reg)
 {
 	switch (reg) {
 	case SC16IS7XX_RHR_REG: /* Shared address space with THR & DLL */
+	case SC16IS7XX_IER_REG: /* Shared address space with DLH */
 	case SC16IS7XX_IIR_REG: /* Shared address space with FCR & EFR */
+	case SC16IS7XX_MCR_REG: /* Shared address space with XON1 */
 	case SC16IS7XX_LSR_REG: /* Shared address space with XON2 */
 	case SC16IS7XX_MSR_REG: /* Shared address space with TCR & XOFF1 */
 	case SC16IS7XX_SPR_REG: /* Shared address space with TLR & XOFF2 */
Signature · 1 line
2.53.0
author maintainer
#700 lore raw

PATCH 694/1257 serial: 8250_exar: store the GPIO platform device in struct exar8250

In reply to Greg Kroah-Hartman

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

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

From: Jiri Slaby (SUSE) <[email protected]>

[ Upstream commit 33d337816e00994daaf670243186d9e537ee090d ]

The GPIO platform device is registered via platform->register_gpio() when port 0 is being set up. It is stored to port->port.private_data of the on-stack uart template (and from there it is copied into every registered port). pci_xr17v35x_exit() then fetches it back by serial8250_get_port(priv->line[0]).

But port 0 does not have to exist at that point. If serial8250_register_8250_port() fails for port 0, priv->line[0] holds a negative error code. The probe still succeeds (it only breaks the loop), so on unbind, priv->line[0] (a negative value) is passed to serial8250_get_port(). The GPIO device is never unregistered and a bogus port is accessed.

The same problem would also occur after the planned conversion of serial8250_register_8250_port() to return a uart port instead of a line. As Sashiko pointed out in that case:
If board->setup() fails for the first port (i=0) in exar_pci_probe(), priv->uport[0] remains NULL. If serial8250_register_8250_port() fails, it returns an ERR_PTR. In either case, the loop breaks and probe returns success. When the device is later unbound, pci_xr17v35x_exit() unconditionally passes priv->uport[0] to platform->unregister_gpio(), which will dereference it without checking for validity.

The GPIO device belongs to the PCI device, not to any particular port. So store it in a new struct exar8250::gpio member. Pass priv to both ->register_gpio() and ->unregister_gpio(), so that pci_xr17v35x_exit() does not need to look up any port at all.

---
 drivers/tty/serial/8250/8250_exar.c | 36 ++++++++++++++---------------
 1 file changed, 18 insertions(+), 18 deletions(-)
drivers/tty/serial/8250/8250_exar.c +18 -18
index 836792e861bfc..2e7adf6a410c6 100644
@@ -231,8 +231,9 @@ struct exar8250_platform {
 	int (*rs485_config)(struct uart_port *port, struct ktermios *termios,
 			    struct serial_rs485 *rs485);
 	const struct serial_rs485 *rs485_supported;
-	int (*register_gpio)(struct pci_dev *pcidev, struct uart_8250_port *port);
-	void (*unregister_gpio)(struct uart_8250_port *port);
+	int (*register_gpio)(struct exar8250 *priv, struct pci_dev *pcidev,
+			     struct uart_8250_port *port);
+	void (*unregister_gpio)(struct exar8250 *priv);
 };
 
 /**
@@ -256,6 +257,7 @@ struct exar8250 {
 	struct exar8250_board	*board;
 	struct eeprom_93cx6	eeprom;
 	void __iomem		*virt;
+	struct platform_device	*gpio;
 	int			line[];
 };
 
@@ -1167,22 +1169,21 @@ static const struct software_node exar_gpio_node = {
 	.properties = exar_gpio_properties,
 };
 
-static int xr17v35x_register_gpio(struct pci_dev *pcidev, struct uart_8250_port *port)
+static int xr17v35x_register_gpio(struct exar8250 *priv, struct pci_dev *pcidev,
+				  struct uart_8250_port *port)
 {
 	if (pcidev->vendor == PCI_VENDOR_ID_EXAR)
-		port->port.private_data =
-			__xr17v35x_register_gpio(pcidev, &exar_gpio_node);
+		priv->gpio = __xr17v35x_register_gpio(pcidev, &exar_gpio_node);
 
 	return 0;
 }
 
-static void xr17v35x_unregister_gpio(struct uart_8250_port *port)
+static void xr17v35x_unregister_gpio(struct exar8250 *priv)
 {
-	if (!port->port.private_data)
-		return;
-
-	__xr17v35x_unregister_gpio(port->port.private_data);
-	port->port.private_data = NULL;
+	if (priv->gpio) {
+		__xr17v35x_unregister_gpio(priv->gpio);
+		priv->gpio = NULL;
+	}
 }
 
 static int sealevel_rs485_config(struct uart_port *port, struct ktermios *termios,
@@ -1279,8 +1280,9 @@ static const struct software_node iot2040_gpio_node = {
 	.properties = iot2040_gpio_properties,
 };
 
-static int iot2040_register_gpio(struct pci_dev *pcidev,
-			      struct uart_8250_port *port)
+static int iot2040_register_gpio(struct exar8250 *priv,
+				 struct pci_dev *pcidev,
+				 struct uart_8250_port *port)
 {
 	u8 __iomem *p = port->port.membase;
 
@@ -1289,8 +1291,7 @@ static int iot2040_register_gpio(struct pci_dev *pcidev,
 	writeb(IOT2040_UARTS_ENABLE, p + UART_EXAR_MPIOLVL_15_8);
 	writeb(IOT2040_UARTS_GPIO_HI_MODE, p + UART_EXAR_MPIOSEL_15_8);
 
-	port->port.private_data =
-		__xr17v35x_register_gpio(pcidev, &iot2040_gpio_node);
+	priv->gpio = __xr17v35x_register_gpio(pcidev, &iot2040_gpio_node);
 
 	return 0;
 }
@@ -1367,7 +1368,7 @@ pci_xr17v35x_setup(struct exar8250 *priv, struct pci_dev *pcidev,
 		/* Setup Multipurpose Input/Output pins. */
 		setup_gpio(pcidev, p);
 
-		ret = platform->register_gpio(pcidev, port);
+		ret = platform->register_gpio(priv, pcidev, port);
 	}
 
 	return ret;
@@ -1377,9 +1378,8 @@ static void pci_xr17v35x_exit(struct pci_dev *pcidev)
 {
 	const struct exar8250_platform *platform = exar_get_platform();
 	struct exar8250 *priv = pci_get_drvdata(pcidev);
-	struct uart_8250_port *port = serial8250_get_port(priv->line[0]);
 
-	platform->unregister_gpio(port);
+	platform->unregister_gpio(priv);
 }
 
 static inline void exar_misc_clear(struct exar8250 *priv)
Signature · 1 line
2.53.0
author maintainer
#701 lore raw

PATCH 695/1257 dm-bufio: fix non-working memory limit

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

[ Upstream commit 1190dbeaeaa026a4879e675b8556a150c36a7ced ]

The function evict_old is supposed to loop and evict buffers while the allocated size is above the threshold. However if it hits one bufio client that is empty, it stops and doesn't attempt to scan other clients.

This commit fixes it, so that it skips empty clients and retries up to dm_bufio_client_count times.

Fixes 450e8dee51aa ("dm bufio: improve concurrent IO performance")
Assisted-by Claude:claude-opus-5
---
 drivers/md/dm-bufio.c | 41 +++++++++++++++++++++++++++++++++++++----
 1 file changed, 37 insertions(+), 4 deletions(-)
drivers/md/dm-bufio.c +37 -4
index d58eed96a8ff5..edad64654ef68 100644
@@ -2545,6 +2545,13 @@ struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsign
 	init_waitqueue_head(&c->free_buffer_wait);
 	c->async_write_error = 0;
 
+	/*
+	 * A client with no buffers yet is not holding the oldest buffer in
+	 * the system; leaving this zeroed would claim exactly that and keep
+	 * the client pinned at the front of dm_bufio_all_clients.
+	 */
+	c->oldest_buffer = jiffies;
+
 	c->dm_io = dm_io_client_create();
 	if (IS_ERR(c->dm_io)) {
 		r = PTR_ERR(c->dm_io);
@@ -2779,9 +2786,23 @@ static unsigned long __evict_a_few(unsigned long nr_buffers)
 
 	dm_bufio_unlock(c);
 
-	if (count)
+	if (count) {
 		c->oldest_buffer = oldest_buffer;
-	__insert_client(c);
+		__insert_client(c);
+	} else {
+		/*
+		 * We evicted nothing, so 'oldest_buffer' tells us nothing new
+		 * and the client keeps its old, possibly very stale, value.
+		 * Requeue it at the back rather than by that value, otherwise
+		 * __insert_client() would put it straight back at the front
+		 * and every subsequent call would pop this same client again,
+		 * never reaching any of the others.
+		 *
+		 * This leaves the list slightly out of order, which is fine -
+		 * it is only ever an approximation.
+		 */
+		list_add_tail(&c->client_list, &dm_bufio_all_clients);
+	}
 
 	return count;
 }
@@ -2806,11 +2827,23 @@ static void evict_old(void)
 {
 	unsigned long threshold = dm_bufio_cache_size -
 		dm_bufio_cache_size / DM_BUFIO_LOW_WATERMARK_RATIO;
+	int unproductive = 0;
 
 	mutex_lock(&dm_bufio_clients_lock);
 	while (dm_bufio_current_allocated > threshold) {
-		if (!__evict_a_few(64))
-			break;
+		if (__evict_a_few(64)) {
+			unproductive = 0;
+		} else {
+			/*
+			 * This client had nothing to give.  Try the others
+			 * before giving up: one idle client, or one whose
+			 * buffers are all held, must not stop us evicting
+			 * from everybody else.  Stop once a whole sweep of
+			 * the client list has freed nothing.
+			 */
+			if (++unproductive >= dm_bufio_client_count)
+				break;
+		}
 		cond_resched();
 	}
 	mutex_unlock(&dm_bufio_clients_lock);
Signature · 1 line
2.53.0
author maintainer
#702 lore raw

PATCH 696/1257 dm-bufio: fix a race leading to an unsigned integer underflow

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

[ Upstream commit 005d2ec5723cd4ac740de678274623f1fadd6a6e ]

The function __scan tests "count - freed <= retain_target" and then sets "atomic_long_set(&c->need_shrink, 0);" It exits with the condition "if (!atomic_long_read(&c->need_shrink)) break;" It may be possible that between these two statements, another thread sets &c->need_shrink to a non-zero value. In this case, the function __scan continues and it may possibly the "freed" variable is larger than the "count" variable. The expression "count - freed" underflows and the function __scan will continue to free all the buffers, even those that are below retain_target.

Fix this bug by immediatelly exiting if we set "atomic_long_set(&c->need_shrink, 0)"; and don't attempt to re-read c->need_shrink afterwards.

Fixes 450e8dee51aa ("dm bufio: improve concurrent IO performance")
Assisted-by Claude:claude-opus-5
---
 drivers/md/dm-bufio.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-bufio.c +3 -1
index edad64654ef68..5f02262707610 100644
@@ -2426,8 +2426,10 @@ static void __scan(struct dm_bufio_client *c)
 
 	for (l = 0; l < LIST_SIZE; l++) {
 		while (true) {
-			if (count - freed <= retain_target)
+			if (count - freed <= retain_target) {
 				atomic_long_set(&c->need_shrink, 0);
+				break;
+			}
 			if (!atomic_long_read(&c->need_shrink))
 				break;
 
Signature · 1 line
2.53.0
author maintainer
#703 lore raw

PATCH 697/1257 misc: issei: Fix issei architecture deps

In reply to Greg Kroah-Hartman

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

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

From: Peter Robinson <[email protected]>

[ Upstream commit a8af929e9d751a85e9f46e8515cbe266249465a2 ]

The issei driver is Intel specific and hence x86 only.

---
 drivers/misc/issei/Kconfig | 1 +
 1 file changed, 1 insertion(+)
drivers/misc/issei/Kconfig +1 -0
index 12a3fd8099694..dfcfa2d30b9ee 100644
@@ -2,6 +2,7 @@
 # Copyright (C) 2023-2026 Intel Corporation
 config INTEL_SSEI
 	tristate "Intel Silicon Security Engine Interface"
+	depends on X86
 	help
 	  The ISSEI (Intel Silicon Security Engine Interface)
 	  subsystem provides a communication channel between the host and the
Signature · 1 line
2.53.0
author maintainer
#704 lore raw

PATCH 698/1257 misc: tifm: dont clear dev->driver in tifm_device_remove()

In reply to Greg Kroah-Hartman

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

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

From: Joshua Mulloy <[email protected]>

[ Upstream commit 2b23952d70d43321a90dd8a06bcaab04a1a73118 ]

tifm_device_remove() sets sock->dev.driver to NULL after calling the driver's remove() callback. Since commit a995fe1a3aa7 ("rust: driver:
drop device private data post unbind"), device_unbind_cleanup() dereferences dev->driver after the bus remove() callback has returned, so removing a card from a TI FlashMedia reader oopses:

  BUG: kernel NULL pointer dereference, address: 0000000000000090
  Workqueue: tifm tifm_7xx1_switch_media [tifm_7xx1]
  RIP: 0010:device_unbind_cleanup+0x16/0xb0
  Call Trace:
   device_release_driver_internal+0x220/0x260
   device_release_driver+0x12/0x20
   bus_remove_device+0xf9/0x1c0
   device_del+0x161/0x3b0
   device_unregister+0x17/0x70
   tifm_7xx1_switch_media.cold+0x6b/0xbd [tifm_7xx1]
   process_one_work+0x1ac/0x3d0
   worker_thread+0x1b8/0x360
   kthread+0xf7/0x130
   ret_from_fork+0x195/0x2a0
   ret_from_fork_asm+0x1a/0x30

The driver core clears dev->driver itself in device_unbind_cleanup(), so there is no need for the bus code to do it. Remove the assignment.

The problem was found and the fix written with the help of an AI coding assistant. Tested on a Dell Precision M6500 (TI PCIxx12 FlashMedia, 104c:803b) running a 7.0 kernel: removing an SD card oopsed every time without the fix; with it, insert, read and remove work.

Fixes a995fe1a3aa7 ("rust: driver: drop device private data post unbind")
Assisted-by LLM
---
 drivers/misc/tifm_core.c | 1 -
 1 file changed, 1 deletion(-)
drivers/misc/tifm_core.c +0 -1
index aac8f0933e435..03d1324bc2534 100644
@@ -97,7 +97,6 @@ static void tifm_device_remove(struct device *dev)
 		sock->card_event = tifm_dummy_event;
 		sock->data_event = tifm_dummy_event;
 		drv->remove(sock);
-		sock->dev.driver = NULL;
 	}
 
 	put_device(dev);
Signature · 1 line
2.53.0
author maintainer
#705 lore raw

PATCH 699/1257 mei: vsc: Fix packet CRC computed over pointer size

In reply to Greg Kroah-Hartman

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

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

From: Wentao Guan <[email protected]>

[ Upstream commit 1d2a50533aac7046488da78b0d25f69673cbb028 ]

vsc_tp_xfer() computes the packet CRC over sizeof(pkt) + olen bytes, but pkt is a pointer, so sizeof(pkt) evaluates to the pointer size instead of the size of struct vsc_tp_packet_hdr. The value correctly match the 8-byte header on 64-bit builds.

Use sizeof(pkt->hdr), consistent with the header size used everywhere else in the driver, e.g. in VSC_TP_PACKET_SIZE().

---
 drivers/misc/mei/vsc-tp.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/misc/mei/vsc-tp.c +1 -1
index 432bc59f11f97..ce877cb957574 100644
@@ -293,7 +293,7 @@ int vsc_tp_xfer(struct vsc_tp *tp, u8 cmd, const void *obuf, size_t olen,
 	pkt->hdr.seq = cpu_to_le32(++tp->seq);
 	memcpy(pkt->buf, obuf, olen);
 
-	crc = ~crc32(~0, (u8 *)pkt, sizeof(pkt) + olen);
+	crc = ~crc32(~0, (u8 *)pkt, sizeof(pkt->hdr) + olen);
 	memcpy(pkt->buf + olen, &crc, sizeof(crc));
 
 	ret = vsc_tp_wakeup_request(tp);
Signature · 1 line
2.53.0
author maintainer
#706 lore raw

PATCH 700/1257 speakup: Fix NULL pointer dereference on VT switch + selection

In reply to Greg Kroah-Hartman

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

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

From: Samuel Thibault <[email protected]>

[ Upstream commit e1301ab8a8411fccc7effe0711fc09939a94953c ]

When selecting/pasting very quickly after VT switch, the tty is not set yet, leading to a NULL dereference. We can just abort the operation.

---
 drivers/accessibility/speakup/selection.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/accessibility/speakup/selection.c +6 -0
index 1713ce4e0ba53..a04a7e8c307b3 100644
@@ -61,6 +61,9 @@ static struct speakup_selection_work speakup_sel_work = {
 
 int speakup_set_selection(struct tty_struct *tty)
 {
+	if (!tty)
+		return -ENODEV;
+
 	/* we get kref here first in order to avoid a subtle race when
 	 * cancelling selection work. getting kref first establishes the
 	 * invariant that if speakup_sel_work.tty is not NULL when
@@ -120,6 +123,9 @@ static struct speakup_selection_work speakup_paste_work = {
 
 int speakup_paste_selection(struct tty_struct *tty)
 {
+	if (!tty)
+		return -ENODEV;
+
 	tty_kref_get(tty);
 	if (cmpxchg(&speakup_paste_work.tty, NULL, tty)) {
 		tty_kref_put(tty);
Signature · 1 line
2.53.0
author maintainer
#707 lore raw

PATCH 701/1257 clk: qcom: ipq-cmn-pll: Assign .num before accessing .hws

In reply to Greg Kroah-Hartman

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

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

From: Aamir Ahmed <[email protected]>

[ Upstream commit 231bbd135772390522be3656b34b49ea3039eccf ]

hw_data->hws[] is annotated with __counted_by(num), so hw_data->num must hold the element count before the array is accessed. ipq_cmn_pll_register_clks() assigns it only after storing the fixed rate output clocks and the CMN PLL, and the unwind loop under unregister_fixed_clk reads .hws[] with .num still zero. Both are out-of-bounds accesses under CONFIG_UBSAN_BOUNDS.

Move the assignment to right after the allocation.

---
 drivers/clk/qcom/ipq-cmn-pll.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/clk/qcom/ipq-cmn-pll.c +2 -1
index dafe8c1738df8..a9abad9ff4e57 100644
@@ -380,6 +380,8 @@ static int ipq_cmn_pll_register_clks(struct platform_device *pdev)
 	if (!hw_data)
 		return -ENOMEM;
 
+	hw_data->num = num_clks + 1;
+
 	/*
 	 * Register the CMN PLL clock, which is the parent clock of
 	 * the fixed rate output clocks.
@@ -406,7 +408,6 @@ static int ipq_cmn_pll_register_clks(struct platform_device *pdev)
 	 * is configured to 12 GHZ by DT property assigned-clock-rates-u64.
 	 */
 	hw_data->hws[CMN_PLL_CLK] = cmn_pll_hw;
-	hw_data->num = num_clks + 1;
 
 	ret = devm_of_clk_add_hw_provider(dev, of_clk_hw_onecell_get, hw_data);
 	if (ret)
Signature · 1 line
2.53.0
author maintainer
#708 lore raw

PATCH 702/1257 clk: qcom: ipq5018: add 24MHz rate for USB UTMI clock

In reply to Greg Kroah-Hartman

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

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

From: Kathiravan Thirumoorthy <[email protected]>

[ Upstream commit 75e893169fc5c9ec28d5f9dffde40ce29b59a5de ]

The USB UTMI reference clock must operate at 24 MHz, as recommended by the hardware team, for reliable USB operation.

Validation showed that USB 3.2 hub enumeration with USB 2.0 devices fails when the UTMI reference clock is not configured to the required 24 MHz rate. Configuring the UTMI reference clock to 24 MHz to resolve the enumeration failure and ensure successful device detection.

Fixes e3fdbef1bab8 ("clk: qcom: Add Global Clock controller (GCC) driver for IPQ5018")
---
 drivers/clk/qcom/gcc-ipq5018.c | 1 +
 1 file changed, 1 insertion(+)
drivers/clk/qcom/gcc-ipq5018.c +1 -0
index 46da652956fb0..add6a53d4df55 100644
@@ -1269,6 +1269,7 @@ static struct clk_rcg2 usb0_master_clk_src = {
 };
 
 static const struct freq_tbl ftbl_usb0_mock_utmi_clk_src[] = {
+	F(24000000, P_XO, 1, 0, 0),
 	F(60000000, P_GPLL4, 10, 1, 2),
 	{ }
 };
Signature · 1 line
2.53.0