Skip to contentSkip to conversation

7.3.6-rc1 review

PATCH Applied Greg Kroah-Hartman 21 participants 2,693 messages Nov 18 – Nov 21 Page 18 of 20

Subsystems (4)
lore
Share & tools
lore
author maintainer
#2323 lore raw

PATCH 2302/2651 tcp_bpf: propagate error code in tcp_bpf_sendmsg()

In reply to Greg Kroah-Hartman

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

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

From: Dmitry Antipov <[email protected]>

[ Upstream commit 82e31923c0553fdbfcddcd910ca07952880ca9b9 ]

In tcp_bpf_sendmsg(), the value returned by sk_msg_memcopy_from_iter() is checked for error but not propagated to 'out_err' label, so error handling may not work as expected. Fix this by assigning error value to 'err', thus making sure that error won't be silently ignored.

---
 net/ipv4/tcp_bpf.c | 1 +
 1 file changed, 1 insertion(+)
net/ipv4/tcp_bpf.c +1 -0
index 2e234d155b5e6..0ce583f68d3b7 100644
@@ -581,6 +581,7 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
 					       copy);
 		if (ret < 0) {
 			sk_msg_trim(sk, msg_tx, osize);
+			err = ret;
 			goto out_err;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#2324 lore raw

PATCH 2303/2651 ocfs2: reserve xattr value tree metadata only once

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

[ Upstream commit 5365f1f417b36627f825aacf9844ae24b671b525 ]

ocfs2_calc_xattr_set_need() asks for the new value's extent tree twice when it replaces an inline value smaller than a value root with one large enough to be stored outside. The "stored outside" branch reserves the tree and then falls through to meta_guess instead of going out:

        if (!ocfs2_xattr_is_local(xe)) {
                ...
                xv = (struct ocfs2_xattr_value_root *)
                     (base + name_offset + name_len);
                value_size = OCFS2_XATTR_ROOT_SIZE;
        } else
                xv = &def_xv.xv;

        if (old_clusters >= new_clusters) {
                ...
                goto out;
        } else {
                meta_add += ocfs2_extend_meta_needed(&xv->xr_list);
                ...
                if (value_size >= OCFS2_XATTR_ROOT_SIZE)
                        goto out;
        }

On the fall-through xv is def_xv, so what gets added here is the two blocks ocfs2_extend_meta_needed() wants for an empty value root -- and both sides of meta_guess reserve that same tree again. The create side has done so since commit 3ed2be719eb9 ("ocfs2: allow for more than one data extent when creating xattr"), which ported this reservation to the create case without noticing it was already on the way in, and the existing-block side since commit 0cdc7dde00ec ("ocfs2: fix missing metadata reservation for large xattrs"). Both were chasing the same RESTART_META failure in ocfs2_xattr_extend_allocation(), for xattr create and then for xattr update.

ocfs2_init_xattr_set_ctxt() hands the total straight to ocfs2_reserve_new_metadata_blocks(), so the surplus is two blocks held for the whole transaction. A setxattr that would otherwise fit can come back -ENOSPC on a filesystem whose metadata allocator is nearly exhausted.

Move the reservation into the branch that stops there, leaving meta_guess as the only place that reserves for a value tree the fall through is about to create. The paths that do go out keep reserving against the value root they already have, which for an external old value is the on-disk one and so can legitimately ask for more than two blocks.

Both sides of meta_guess have to come out even on their own now that the copy covering for them is gone. The existing-block side only started reserving the value tree in the commit this one is tagged against. The create side has reserved the tree since 3ed2be719eb9, but only the tree:
the block ocfs2_create_xattr_block() claims came out of the same two, and on the fall-through it was the duplicate removed here that made up the difference. So "ocfs2: reserve metadata for a new xattr block and its value tree" has to land first -- without it the create side reserves 2 where 3 are needed and the value tree is back to RESTART_META. That one fixes a shortfall of its own on the path that reaches meta_guess directly, where there was never a duplicate to cover it, so it is worth taking alone; this patch is not.

Fixes 0cdc7dde00ec ("ocfs2: fix missing metadata reservation for large xattrs")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)
fs/ocfs2/xattr.c +15 -2
index 316418e2d909f..a061cd891867f 100644
@@ -3474,12 +3474,21 @@ static int ocfs2_calc_xattr_set_need(struct inode *inode,
 			credits += ocfs2_remove_extent_credits(inode->i_sb);
 			goto out;
 		} else {
-			meta_add += ocfs2_extend_meta_needed(&xv->xr_list);
 			clusters_add += new_clusters - old_clusters;
 			credits += ocfs2_calc_extend_credits(inode->i_sb,
 							     &xv->xr_list);
-			if (value_size >= OCFS2_XATTR_ROOT_SIZE)
+			/*
+			 * The old value occupies at least as much room as a
+			 * value root, whether it sat outside or inline, so the
+			 * new root fits where it was and no new xattr block or
+			 * bucket is needed -- only the metadata to extend the
+			 * tree hanging off it.  A smaller one is replaced
+			 * outright, which meta_guess below reserves for.
+			 */
+			if (value_size >= OCFS2_XATTR_ROOT_SIZE) {
+				meta_add += ocfs2_extend_meta_needed(&xv->xr_list);
 				goto out;
+			}
 		}
 	} else {
 		/*
@@ -3531,6 +3540,10 @@ static int ocfs2_calc_xattr_set_need(struct inode *inode,
 		 * Reserve metadata for the new xattr's value extent tree.
 		 * The not_found path above adds credits for this tree but
 		 * omits meta_add, leaving meta_ac NULL for large values.
+		 *
+		 * This is all of meta_ac on this side beyond the xattr tree
+		 * above: no xattr block is allocated here, and a new bucket or
+		 * index block is paid for out of data_ac.
 		 */
 		if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE)
 			meta_add += ocfs2_extend_meta_needed(&def_xv.xv.xr_list);
Signature · 1 line
2.53.0
author maintainer
#2325 lore raw

PATCH 2304/2651 ocfs2: initialize status waiters before publishing them

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit f6bfa6c458288d72948af95391b205f3eb775721 ]

o2net_prep_nsw() publishes its stack waiter in nn_status_idr and nn_status_list under nn_lock, then initializes the wait queue and completion status after releasing the lock. A concurrent disconnect can find that waiter through o2net_complete_nodes_nsw() and call wake_up() before the wait queue has a valid lock and list head. The sender can also overwrite a completion status with its initial value.

Initialize the wait queue and status before publishing the waiter. nn_lock then orders publication against completion, and no reader can observe a partially initialized object. Leave the IDR allocation and its failure handling unchanged.

A controlled case-modified test kernel used a synthetic connection to enter the real send path and overlap publication with disconnect. The candidate completion and wake-up code were unchanged. Its Oops includes:

  KASAN: null-ptr-deref in range [0x0000000000000000-0x0000000000000007]
  RIP: 0010:__wake_up_common+0xa0/0x1f0
  Call Trace:
   <TASK>
   __wake_up+0x36/0x60
   o2net_complete_nsw_locked+0x222/0x370
   o2net_set_nn_state+0x917/0xea0
   o2net_disconnect_node+0xd0/0x190
   o2net_validate_control_write+0x454/0x500
   full_proxy_write+0x11f/0x180
   vfs_write+0x25a/0x1010
   ksys_write+0x111/0x200
   do_syscall_64+0x114/0x620
   entry_SYSCALL_64_after_hwframe+0x77/0x7f
   </TASK>
  Modules linked in:
Fixes 98211489d414 ("[PATCH] OCFS2: The Second Oracle Cluster Filesystem")
Assisted-by LLM
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc Kees Cook <[email protected]>
Cc Jakub Kicinski <[email protected]>
Cc Kurt Hackel <[email protected]>
Cc Jia-Ju Bai <[email protected]>
---
 fs/ocfs2/cluster/tcp.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
fs/ocfs2/cluster/tcp.c +5 -3
index 0ba26bd2eba11..0eaf2c4a6989e 100644
@@ -301,6 +301,11 @@ static int o2net_prep_nsw(struct o2net_node *nn, struct o2net_status_wait *nsw)
 {
 	int ret;
 
+	/* Initialize all completion-visible state before publishing the waiter. */
+	init_waitqueue_head(&nsw->ns_wq);
+	nsw->ns_sys_status = O2NET_ERR_NONE;
+	nsw->ns_status = 0;
+
 	spin_lock(&nn->nn_lock);
 	ret = idr_alloc(&nn->nn_status_idr, nsw, 0, 0, GFP_ATOMIC);
 	if (ret >= 0) {
@@ -311,9 +316,6 @@ static int o2net_prep_nsw(struct o2net_node *nn, struct o2net_status_wait *nsw)
 	if (ret < 0)
 		return ret;
 
-	init_waitqueue_head(&nsw->ns_wq);
-	nsw->ns_sys_status = O2NET_ERR_NONE;
-	nsw->ns_status = 0;
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#2326 lore raw

PATCH 2305/2651 selftests/proc: proc-pid-vm: fix unused variable warning on non-x86

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit c4d9005e7e1ee6ce277f47cf53d44fc5b90b287b ]

g_vsyscall is only used by the x86_64 test, so clang builds for other architectures get:

proc-pid-vm.c:224:21: warning: unused variable 'g_vsyscall' [-Wunused-variable]

The vsyscall strings next to it had the same problem and were marked __maybe_unused for it. Move all of the vsyscall variables into the __x86_64__ block that uses them instead, and drop those annotations along with the local __maybe_unused fallback that was added for them.

Fixes 17415606f9d8 ("tools/testing/selftests/proc/proc-pid-vm.c: test with vsyscall in mind")
Assisted-by LLM
Cc Shuah Khan <[email protected]>
Cc Alexey Dobriyan <[email protected]>
---
 tools/testing/selftests/proc/proc-pid-vm.c | 14 ++++----------
 1 file changed, 4 insertions(+), 10 deletions(-)
tools/testing/selftests/proc/proc-pid-vm.c +4 -10
index 4e6a3e53f9757..98e882e568154 100644
@@ -47,10 +47,6 @@
 #include <sys/resource.h>
 #include <linux/fs.h>
 
-#ifndef __maybe_unused
-#define __maybe_unused __attribute__((__unused__))
-#endif
-
 #include "kselftest.h"
 
 static inline long sys_execveat(int dirfd, const char *pathname, char **argv, char **envp, int flags)
@@ -214,7 +210,6 @@ static int make_exe(const uint8_t *payload, size_t len)
 
 	return fd1;
 }
-#endif
 
 /*
  * 0: vsyscall VMA doesn't exist	vsyscall=none
@@ -222,15 +217,14 @@ static int make_exe(const uint8_t *payload, size_t len)
  * 2: vsyscall VMA is r-xp		vsyscall=emulate
  */
 static volatile int g_vsyscall;
-static const char *str_vsyscall __maybe_unused;
+static const char *str_vsyscall;
 
-static const char str_vsyscall_0[] __maybe_unused = "";
-static const char str_vsyscall_1[] __maybe_unused =
+static const char str_vsyscall_0[] = "";
+static const char str_vsyscall_1[] =
 "ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0                  [vsyscall]\n";
-static const char str_vsyscall_2[] __maybe_unused =
+static const char str_vsyscall_2[] =
 "ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]\n";
 
-#ifdef __x86_64__
 static void sigaction_SIGSEGV(int _, siginfo_t *__, void *___)
 {
 	_exit(g_vsyscall);
Signature · 1 line
2.53.0
author maintainer
#2327 lore raw

PATCH 2306/2651 Drivers: hv: vmbus: Check ACPI companion before use

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

Platform drivers can be forced to bind to devices outside their match tables through driver_override. vmbus_acpi_add() assumes that every bound device has an ACPI companion and dereferences it without checking.

Return -ENODEV when the companion is absent to avoid a NULL pointer dereference.

Fixes 9c8434238041 ("Drivers: hv: vmbus: Convert acpi_device to more generic platform_device")
---
 drivers/hv/vmbus_drv.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/hv/vmbus_drv.c +6 -2
index 4692687cdbf3b..28f459679406a 100644
@@ -2571,10 +2571,14 @@ EXPORT_SYMBOL_GPL(vmbus_free_mmio);
 #ifdef CONFIG_ACPI
 static int vmbus_acpi_add(struct platform_device *pdev)
 {
+	struct acpi_device *ancestor;
+	struct acpi_device *device;
 	acpi_status result;
 	int ret_val = -ENODEV;
-	struct acpi_device *ancestor;
-	struct acpi_device *device = ACPI_COMPANION(&pdev->dev);
+
+	device = ACPI_COMPANION(&pdev->dev);
+	if (!device)
+		return -ENODEV;
 
 	vmbus_root_device = &device->dev;
 
Signature · 1 line
2.53.0
author maintainer
#2328 lore raw

PATCH 2307/2651 kexec: Add helper to report an active kexec reboot

In reply to Greg Kroah-Hartman

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

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

From: Shradha Gupta <[email protected]>

[ Upstream commit 14c73a2b061e494ab6da346ab075b14f2a4b2d06 ]

A shutdown callback in a loadable module may need to distinguish a kexec reboot from a normal restart, halt, or poweroff. The Hyper-V VMBus driver needs this distinction when moving its kexec cleanup into a common syscore shutdown callback.

Add kexec_is_in_progress() and export it to GPL modules so the callback can remain guarded when VMBus is built as a module. Provide a false inline implementation when CONFIG_KEXEC_CORE is disabled.

The helper reports only the normal kexec reboot path. Crash kexec and preserve-context kexec do not set this state.

Stable-dep-of: 228e21764b38 ("Drivers: hv: Run VMBus kexec cleanup from syscore shutdown")

---
 include/linux/kexec.h | 2 ++
 kernel/kexec_core.c   | 7 +++++++
 2 files changed, 9 insertions(+)
include/linux/kexec.h +2 -0
index 0af8ae4fdd087..aeb74b47c36e4 100644
@@ -468,6 +468,7 @@ bool kexec_load_permitted(int kexec_image_type);
 
 /* flag to track if kexec reboot is in progress */
 extern bool kexec_in_progress;
+bool kexec_is_in_progress(void);
 
 #ifndef page_to_boot_pfn
 static inline unsigned long page_to_boot_pfn(struct page *page)
@@ -544,6 +545,7 @@ static inline void *kimage_map_segment(struct kimage *image, int idx)
 { return NULL; }
 static inline void kimage_unmap_segment(void *buffer) { }
 #define kexec_in_progress false
+static inline bool kexec_is_in_progress(void) { return false; }
 #endif /* CONFIG_KEXEC_CORE */
 
 #ifdef CONFIG_KEXEC_SIG
kernel/kexec_core.c +7 -0
index dc770b9a6d053..282c7b3c6c353 100644
@@ -23,6 +23,7 @@
 #include <linux/hardirq.h>
 #include <linux/elf.h>
 #include <linux/elfcore.h>
+#include <linux/export.h>
 #include <linux/utsname.h>
 #include <linux/numa.h>
 #include <linux/suspend.h>
@@ -54,6 +55,12 @@ atomic_t __kexec_lock = ATOMIC_INIT(0);
 /* Flag to indicate we are going to kexec a new kernel */
 bool kexec_in_progress = false;
 
+bool kexec_is_in_progress(void)
+{
+	return kexec_in_progress;
+}
+EXPORT_SYMBOL_GPL(kexec_is_in_progress);
+
 bool kexec_file_dbg_print;
 
 /*
Signature · 1 line
2.53.0
author maintainer
#2329 lore raw

PATCH 2308/2651 Drivers: hv: Run VMBus kexec cleanup from syscore shutdown

In reply to Greg Kroah-Hartman

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

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

From: Shradha Gupta <[email protected]>

[ Upstream commit 228e21764b389a71a05af6a356efa1bad0751b5e ]

ARM64 Hyper-V guests do not run the VMBus kexec cleanup before secondary CPUs are stopped. Consequently, the old VMBus connection and SynIC state remain active when the kexec kernel starts.

Run the VMBus kexec handler from the existing VMBus syscore shutdown callback. syscore_shutdown() runs after device shutdown and before machine shutdown, while all CPUs needed by the SynIC CPU hotplug teardown are still available. Guard the callback with kexec_is_in_progress() so normal restart, halt, and poweroff paths are unchanged.

Use the same path on x86 and remove the architecture-specific handler pointer and the weak setup/remove interfaces. VMBus teardown now precedes hv_stimer_global_cleanup() on x86.

The new x86 ordering relies on commit be0cfab740e5 ("clocksource:
hyper-v: Remove support for stimer interrupts in message mode"), which removed the synthetic timer's dependency on VMBus message delivery. Older kernels that retain message-mode stimer interrupts must preserve the existing x86 ordering and therefore require an ARM64-specific backport.

Document the VMBus cleanup path and its position in shutdown ordering.

---
 Documentation/virt/hyperv/overview.rst | 12 +++++++-----
 arch/x86/kernel/cpu/mshyperv.c         | 27 ++++++--------------------
 drivers/hv/hv_common.c                 | 10 ----------
 drivers/hv/vmbus_drv.c                 | 22 +++++++++++++--------
 include/asm-generic/mshyperv.h         |  2 --
 5 files changed, 27 insertions(+), 46 deletions(-)
Documentation/virt/hyperv/overview.rst +7 -5
index 77408a89d1a40..34a53ba7a1227 100644
@@ -114,11 +114,13 @@ a shared page or remove an overlay page after the new kernel is
 using the page for a different purpose, corrupting the new kernel.
 Hyper-V does not provide a single "set everything" operation to
 guest VMs, so Linux code must individually revoke all sharing before
-doing kexec.   See hv_kexec_handler() and hv_crash_handler().  But
-the crash/panic path still has holes in cleanup because some shared
-pages are set using per-CPU synthetic registers and there's no
-mechanism to revoke the shared pages for CPUs other than the CPU
-running the panic path.
+doing kexec.  For a normal kexec reboot, the VMBus driver calls
+hv_kexec_handler() from its syscore shutdown callback, after device
+shutdown and before the architecture-specific machine shutdown.  The
+crash/panic path uses hv_crash_handler(), but still has holes in
+cleanup because some shared pages are set using per-CPU synthetic
+registers and there is no mechanism to revoke the shared pages for
+CPUs other than the CPU running the panic path.
 
 CPU Management
 --------------
arch/x86/kernel/cpu/mshyperv.c +6 -21
index b4af7c0a70ac8..fec1c37dafbff 100644
@@ -148,7 +148,6 @@ EXPORT_SYMBOL_GPL(hv_set_msr);
 static void (*mshv_handler)(void);
 static void (*vmbus_handler)(void);
 static void (*hv_stimer0_handler)(void);
-static void (*hv_kexec_handler)(void);
 static void (*hv_crash_handler)(struct pt_regs *regs);
 
 DEFINE_IDTENTRY_SYSVEC(sysvec_hyperv_callback)
@@ -215,16 +214,6 @@ void hv_remove_stimer0_handler(void)
 	hv_stimer0_handler = NULL;
 }
 
-void hv_setup_kexec_handler(void (*handler)(void))
-{
-	hv_kexec_handler = handler;
-}
-
-void hv_remove_kexec_handler(void)
-{
-	hv_kexec_handler = NULL;
-}
-
 void hv_setup_crash_handler(void (*handler)(struct pt_regs *regs))
 {
 	hv_crash_handler = handler;
@@ -240,17 +229,13 @@ static void hv_machine_shutdown(void)
 {
 	if (kexec_in_progress) {
 		hv_stimer_global_cleanup();
-
-		if (hv_kexec_handler)
-			hv_kexec_handler();
-	}
-
-	/*
-	 * Call hv_cpu_die() on all the CPUs, otherwise later the hypervisor
-	 * corrupts the old VP Assist Pages and can crash the kexec kernel.
-	 */
-	if (kexec_in_progress)
+		/*
+		 * Call hv_cpu_die() on all the CPUs, otherwise later the
+		 * hypervisor corrupts the old VP Assist Pages and can crash
+		 * the kexec kernel.
+		 */
 		cpuhp_remove_state(CPUHP_AP_HYPERV_ONLINE);
+	}
 
 	/* The function calls stop_other_cpus(). */
 	native_machine_shutdown();
drivers/hv/hv_common.c +0 -10
index 31256cb22b39e..bb290a5eaf1de 100644
@@ -681,16 +681,6 @@ void __weak hv_setup_mshv_handler(void (*handler)(void))
 }
 EXPORT_SYMBOL_GPL(hv_setup_mshv_handler);
 
-void __weak hv_setup_kexec_handler(void (*handler)(void))
-{
-}
-EXPORT_SYMBOL_GPL(hv_setup_kexec_handler);
-
-void __weak hv_remove_kexec_handler(void)
-{
-}
-EXPORT_SYMBOL_GPL(hv_remove_kexec_handler);
-
 void __weak hv_setup_crash_handler(void (*handler)(struct pt_regs *regs))
 {
 }
drivers/hv/vmbus_drv.c +14 -8
index 28f459679406a..c8330fffb138c 100644
@@ -33,6 +33,7 @@
 #include <linux/sysfb.h>
 #include <linux/efi.h>
 #include <linux/kernel.h>
+#include <linux/kexec.h>
 #include <linux/syscore_ops.h>
 #include <linux/dma-map-ops.h>
 #include <linux/pci.h>
@@ -2908,6 +2909,12 @@ static void hv_kexec_handler(void)
 	cpuhp_remove_state(hyperv_cpuhp_online);
 };
 
+static void hv_vmbus_syscore_shutdown(void *data)
+{
+	if (kexec_is_in_progress())
+		hv_kexec_handler();
+}
+
 static void hv_crash_handler(struct pt_regs *regs)
 {
 	int cpu;
@@ -2958,14 +2965,15 @@ static void hv_synic_resume(void *data)
 	 */
 }
 
-/* The callbacks run only on CPU0, with irqs_disabled. */
-static const struct syscore_ops hv_synic_syscore_ops = {
+/* The suspend and resume callbacks run only on CPU0, with irqs_disabled. */
+static const struct syscore_ops hv_vmbus_syscore_ops = {
 	.suspend = hv_synic_suspend,
 	.resume = hv_synic_resume,
+	.shutdown = hv_vmbus_syscore_shutdown,
 };
 
-static struct syscore hv_synic_syscore = {
-	.ops = &hv_synic_syscore_ops,
+static struct syscore hv_vmbus_syscore = {
+	.ops = &hv_vmbus_syscore_ops,
 };
 
 static int __init hv_acpi_init(void)
@@ -3014,10 +3022,9 @@ static int __init hv_acpi_init(void)
 	if (ret)
 		goto cleanup;
 
-	hv_setup_kexec_handler(hv_kexec_handler);
 	hv_setup_crash_handler(hv_crash_handler);
 
-	register_syscore(&hv_synic_syscore);
+	register_syscore(&hv_vmbus_syscore);
 
 	return 0;
 
@@ -3039,9 +3046,8 @@ static void __exit vmbus_exit(void)
 		 */
 		return;
 
-	unregister_syscore(&hv_synic_syscore);
+	unregister_syscore(&hv_vmbus_syscore);
 
-	hv_remove_kexec_handler();
 	hv_remove_crash_handler();
 	hv_stimer_global_cleanup();
 	vmbus_disconnect();
include/asm-generic/mshyperv.h +0 -2
index bf601d67cecb9..98fe5c0f54eaf 100644
@@ -183,8 +183,6 @@ void hv_remove_vmbus_handler(void);
 void hv_setup_stimer0_handler(void (*handler)(void));
 void hv_remove_stimer0_handler(void);
 
-void hv_setup_kexec_handler(void (*handler)(void));
-void hv_remove_kexec_handler(void);
 void hv_setup_crash_handler(void (*handler)(struct pt_regs *regs));
 void hv_remove_crash_handler(void);
 void hv_setup_mshv_handler(void (*handler)(void));
Signature · 1 line
2.53.0
author maintainer
#2330 lore raw

PATCH 2309/2651 mshv_vtl: initialize poll file mutex before device registration

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

mshv_vtl_init() registers /dev/mshv before initializing the poll file mutex. A concurrent MSHV_SET_POLL_FILE ioctl can therefore attempt to lock an uninitialized mutex while module initialization is still in progress.

Initialize the file-scope mutex statically so it is ready before the misc device becomes visible.

Fixes 7bfe3b8ea6e3 ("Drivers: hv: Introduce mshv_vtl driver")
---
 drivers/hv/mshv_vtl_main.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/hv/mshv_vtl_main.c +1 -3
index 9133646b5b66c..2d4fe24cecbff 100644
@@ -97,7 +97,7 @@ union hv_synic_overlay_page_msr {
 	} __packed;
 };
 
-static struct mutex mshv_vtl_poll_file_lock;
+static DEFINE_MUTEX(mshv_vtl_poll_file_lock);
 static union hv_register_vsm_page_offsets mshv_vsm_page_offsets;
 static union hv_register_vsm_capabilities mshv_vsm_capabilities;
 
@@ -1411,8 +1411,6 @@ static int __init mshv_vtl_init(void)
 		goto free_low;
 	}
 
-	mutex_init(&mshv_vtl_poll_file_lock);
-
 	device_initialize(mem_dev);
 	dev_set_name(mem_dev, "mshv vtl mem dev");
 	ret = device_add(mem_dev);
Signature · 1 line
2.53.0
author maintainer
#2331 lore raw

PATCH 2310/2651 platform/x86: ibm_rtl: Fix potential OOB read at signature search

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit f1d81af2521ad504a20481fef12c358d26e6c3a6 ]

The loop for signature search fetches 22 bytes of struct ibm_rtl_table at each check, while the loop count is calculated in 4 bytes unit, which means that, at the last entry, it fetches over the limit.

Rewrite the loop to use the byte offset and correct the boundary condition check for avoiding the potential OOB access.

Fixes 15dd100349b8 ("platform/x86: ibm_rtl: fix EBDA signature search pointer arithmetic")
---
 drivers/platform/x86/ibm_rtl.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/platform/x86/ibm_rtl.c +4 -4
index 139956168cf94..82fda8d9178be 100644
@@ -234,9 +234,9 @@ static const struct dmi_system_id ibm_rtl_dmi_table[] __initconst = {
 };
 
 static int __init ibm_rtl_init(void) {
-	unsigned long ebda_addr, ebda_size;
+	unsigned long ebda_addr, ebda_size, offset;
 	unsigned int ebda_kb;
-	int ret = -ENODEV, i;
+	int ret = -ENODEV;
 
 	if (force)
 		pr_warn("module loaded by force\n");
@@ -271,9 +271,9 @@ static int __init ibm_rtl_init(void) {
 		return -ENOMEM;
 
 	/* search for the _RTL_ signature at the start of the table */
-	for (i = 0 ; i < ebda_size/sizeof(unsigned int); i++) {
+	for (offset = 0; offset + sizeof(*rtl_table) <= ebda_size; offset += 4) {
 		struct ibm_rtl_table __iomem * tmp;
-		tmp = (struct ibm_rtl_table __iomem *) (ebda_map + i*sizeof(unsigned int));
+		tmp = (struct ibm_rtl_table __iomem *) (ebda_map + offset);
 		if ((readq(&tmp->signature) & RTL_MASK) == RTL_SIGNATURE) {
 			phys_addr_t addr;
 			unsigned int plen;
Signature · 1 line
2.53.0
author maintainer
#2332 lore raw

PATCH 2311/2651 selftests: ALSA: pcmtest: Check the frame count of each transfer

In reply to Greg Kroah-Hartman

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

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

From: HyeongJun An <[email protected]>

[ Upstream commit 317f2ddb6662fca8954e381a1bc632667872c4a3 ]

The tests keep the result of snd_pcm_writei(), snd_pcm_readi() and their non-interleaved forms in a size_t. A size_t is never negative, so ASSERT_GE(res, 0) always passes.

The capture tests still catch a failed read when they compare the data. But the playback tests do not. The driver sets pc_test to 1 when it saw no corrupted data, and that is also true when it saw no data at all. So a playback test passes even when every write fails.

Store the result as snd_pcm_sframes_t and check that the whole request was transferred. The calls block, so a short count means an error.

Fixes 10b98a4db11a ("selftests: ALSA: Add test for the 'pcmtest' driver")
Assisted-by Claude:claude-opus-5-5
---
 .../selftests/alsa/test-pcmtest-driver.c      | 21 +++++++++++--------
 1 file changed, 12 insertions(+), 9 deletions(-)
tools/testing/selftests/alsa/test-pcmtest-driver.c +12 -9
index 95065ef3b4410..5bba17434a6bc 100644
@@ -166,7 +166,7 @@ FIXTURE_SETUP(pcmtest) {
 TEST_F(pcmtest, playback) {
 	snd_pcm_t *handle;
 	unsigned char *it;
-	size_t write_res;
+	snd_pcm_sframes_t write_res;
 	int test_results;
 	int i, cur_ch, pos_in_ch;
 	void *samples;
@@ -190,7 +190,7 @@ TEST_F(pcmtest, playback) {
 		it[i] = patterns[cur_ch].buf[pos_in_ch % patterns[cur_ch].len];
 	}
 	write_res = snd_pcm_writei(handle, samples, params->rate * params->time);
-	ASSERT_GE(write_res, 0);
+	ASSERT_EQ(write_res, params->rate * params->time);
 
 	snd_pcm_close(handle);
 	free(samples);
@@ -206,7 +206,7 @@ TEST_F(pcmtest, playback) {
 TEST_F(pcmtest, capture) {
 	snd_pcm_t *handle;
 	unsigned char *it;
-	size_t read_res;
+	snd_pcm_sframes_t read_res;
 	int i, cur_ch, pos_in_ch;
 	void *samples;
 	struct pcmtest_test_params *params = &self->params;
@@ -222,7 +222,7 @@ TEST_F(pcmtest, capture) {
 	snd_pcm_format_set_silence(params->format, samples,
 				   params->rate * params->channels * params->time);
 	read_res = snd_pcm_readi(handle, samples, params->rate * params->time);
-	ASSERT_GE(read_res, 0);
+	ASSERT_EQ(read_res, params->rate * params->time);
 	snd_pcm_close(handle);
 	it = (unsigned char *)samples;
 	for (i = 0; i < self->params.sec_buf_len * self->params.time; i++) {
@@ -239,7 +239,8 @@ TEST_F(pcmtest, ni_capture) {
 	snd_pcm_t *handle;
 	struct pcmtest_test_params params = self->params;
 	char **chan_samples;
-	size_t i, j, read_res;
+	snd_pcm_sframes_t read_res;
+	size_t i, j;
 
 	chan_samples = calloc(CH_NUM, sizeof(*chan_samples));
 	ASSERT_NE(chan_samples, NULL);
@@ -257,7 +258,7 @@ TEST_F(pcmtest, ni_capture) {
 
 	for (i = 0; i < 1; i++) {
 		read_res = snd_pcm_readn(handle, (void **)chan_samples, params.rate * params.time);
-		ASSERT_GE(read_res, 0);
+		ASSERT_EQ(read_res, params.rate * params.time);
 	}
 	snd_pcm_close(handle);
 
@@ -273,7 +274,8 @@ TEST_F(pcmtest, ni_playback) {
 	snd_pcm_t *handle;
 	struct pcmtest_test_params params = self->params;
 	char **chan_samples;
-	size_t i, j, read_res;
+	snd_pcm_sframes_t write_res;
+	size_t i, j;
 	int test_res;
 
 	chan_samples = calloc(CH_NUM, sizeof(*chan_samples));
@@ -294,8 +296,9 @@ TEST_F(pcmtest, ni_playback) {
 	}
 
 	for (i = 0; i < 1; i++) {
-		read_res = snd_pcm_writen(handle, (void **)chan_samples, params.rate * params.time);
-		ASSERT_GE(read_res, 0);
+		write_res = snd_pcm_writen(handle, (void **)chan_samples,
+					   params.rate * params.time);
+		ASSERT_EQ(write_res, params.rate * params.time);
 	}
 
 	snd_pcm_close(handle);
Signature · 1 line
2.53.0
author maintainer
#2333 lore raw

PATCH 2312/2651 selftests: ALSA: pcmtest: Make room for the longest fill pattern

In reply to Greg Kroah-Hartman

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

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

From: HyeongJun An <[email protected]>

[ Upstream commit c338e77291d6b1b6aee6d45b3cc523f97199a011 ]

The driver accepts fill patterns of up to 4096 bytes, as pcmtest.rst documents. The test reads each pattern into a 1024-byte buffer, using the length the driver reports. So a pattern longer than 1024 bytes overflows the buffer into the next pattern and past the array.

Size the buffer to the driver's maximum.

Fixes 10b98a4db11a ("selftests: ALSA: Add test for the 'pcmtest' driver")
Assisted-by Claude:claude-opus-5-5
---
 tools/testing/selftests/alsa/test-pcmtest-driver.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
tools/testing/selftests/alsa/test-pcmtest-driver.c +3 -1
index 5bba17434a6bc..e025a7bac26b7 100644
@@ -10,9 +10,11 @@
 #include "kselftest_harness.h"
 
 #define CH_NUM 4
+/* The driver accepts patterns of up to 4096 bytes */
+#define MAX_PATTERN_LEN 4096
 
 struct pattern_buf {
-	char buf[1024];
+	char buf[MAX_PATTERN_LEN];
 	int len;
 };
 
Signature · 1 line
2.53.0
author maintainer
#2334 lore raw

PATCH 2313/2651 gtp: set a valid genl command in PDP context get and dump replies

In reply to Greg Kroah-Hartman

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

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

From: Anil Kaushik <[email protected]>

[ Upstream commit 758d8928d2c5d6703da827577cef86d643155236 ]

gtp_genl_fill_info() stamps the reply with the command its callers pass in. gtp_genl_get_pdp() and gtp_genl_dump_pdp() pass nlmsg_type, which in a genl message is the dynamically assigned family id rather than a GTP_CMD_* value, so replies to a PDP context get or dump carry a meaningless command number.

libgtpnl ignores the command and is unaffected, but parsers that check it (for example the ynl tooling) treat the reply as an unknown command and discard it. Pass GTP_CMD_GETPDP, as gtp_tunnel_notify() already passes a real command on the notification path. No uapi change.

Fixes 459aa660eb1d ("gtp: add initial driver for datapath of GPRS Tunneling Protocol (GTP-U)")
---
 drivers/net/gtp.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/net/gtp.c +2 -2
index 69fe5717846b5..3dd97d75551ce 100644
@@ -2279,7 +2279,7 @@ static int gtp_genl_get_pdp(struct sk_buff *skb, struct genl_info *info)
 	}
 
 	err = gtp_genl_fill_info(skb2, NETLINK_CB(skb).portid, info->snd_seq,
-				 0, info->nlhdr->nlmsg_type, pctx);
+				 0, GTP_CMD_GETPDP, pctx);
 	if (err < 0)
 		goto err_unlock_free;
 
@@ -2326,7 +2326,7 @@ static int gtp_genl_dump_pdp(struct sk_buff *skb,
 					    NETLINK_CB(cb->skb).portid,
 					    cb->nlh->nlmsg_seq,
 					    NLM_F_MULTI,
-					    cb->nlh->nlmsg_type, pctx)) {
+					    GTP_CMD_GETPDP, pctx)) {
 					cb->args[0] = i;
 					cb->args[1] = j;
 					cb->args[2] = (unsigned long)gtp;
Signature · 1 line
2.53.0
author maintainer
#2335 lore raw

PATCH 2314/2651 gtp: hold RCU for the device lookup when adding a PDP context

In reply to Greg Kroah-Hartman

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

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

From: Anil Kaushik <[email protected]>

[ Upstream commit fe3e1a42fb7eb18d8c55d714b50a3d51f8cd6ffe ]

gtp_genl_new_pdp() calls gtp_find_dev(), which looks the device up with dev_get_by_index_rcu(). Since commit e2d1baca2b33 ("gtp: remove useless rcu_read_lock()"), this only runs under the rtnl lock, and kernels with CONFIG_PROVE_RCU_LIST warn:

WARNING: suspicious RCU usage
net/core/dev.c:1047 RCU-list traversed in non-reader section!!
...
dev_get_by_index_rcu
gtp_find_dev
gtp_genl_new_pdp

Hold the RCU read lock around the lookup only: gtp_pdp_add() allocates with GFP_KERNEL, and the rtnl lock keeps the device alive afterwards.

Found with the gtp selftest on a debug kernel.

Fixes e2d1baca2b33 ("gtp: remove useless rcu_read_lock()")
---
 drivers/net/gtp.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/net/gtp.c +3 -0
index 3dd97d75551ce..df182cdd3bd4a 100644
@@ -2050,7 +2050,10 @@ static int gtp_genl_new_pdp(struct sk_buff *skb, struct genl_info *info)
 
 	rtnl_lock();
 
+	/* the rtnl lock keeps the device alive once found */
+	rcu_read_lock();
 	gtp = gtp_find_dev(sock_net(skb->sk), info->attrs);
+	rcu_read_unlock();
 	if (!gtp) {
 		err = -ENODEV;
 		goto out_unlock;
Signature · 1 line
2.53.0
author maintainer
#2336 lore raw

PATCH 2315/2651 net/mlx5: HWS, fix modify header pattern compare on big-endian

In reply to Greg Kroah-Hartman

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

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

From: Alexandre Cassen <[email protected]>

[ Upstream commit 7eed173447fba937a19e2f5f2dc79780793f72e7 ]

mlx5hws_pat_compare_pattern() casts each __be64 action to __be32 to compare only its control dword. On big-endian this keeps the data dword instead, which HWS clears from the pattern of set and add actions. Two such actions writing the same value into different fields then share a pattern and the second rule modifies the wrong field.

Read the first dword of each action from memory instead. Little-endian behavior is unchanged.

Discovered by an AI code review agent [1] and confirmed by code inspection. Not reproduced for lack of big-endian hardware running HWS. Tested for regressions on ConnectX-7 with firmware 28.48.1000 on a little-endian host.

---
 .../net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.c    | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.c +2 -2
index 9af449c2b4d5a..512299b59fd0d 100644
@@ -116,8 +116,8 @@ static bool mlx5hws_pat_compare_pattern(int cur_num_of_actions,
 				return false;
 		} else {
 			/* Compare just the control, not the values */
-			if ((__force __be32)actions[i] !=
-			    (__force __be32)cur_actions[i])
+			if (*(__be32 *)&actions[i] !=
+			    *(__be32 *)&cur_actions[i])
 				return false;
 		}
 	}
Signature · 1 line
2.53.0
author maintainer
#2337 lore raw

PATCH 2316/2651 net/mlx5: HWS, fix modify header pool match for copy actions

In reply to Greg Kroah-Hartman

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

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

From: Alexandre Cassen <[email protected]>

[ Upstream commit d425ec9bb9371d52d492ac4d09f0da6e26561684 ]

mlx5_fs_hws_mh_pool_match() compares a single dword of each action since rules pass their values as arguments. Copy and add_field actions keep their destination in the second dword and HWS reads them from the pattern alone. Two modify headers whose copies differ only in destination then share a pool and the second rule writes to the wrong field.

Use the HWS core comparison that checks these actions in full.

Found while checking a Sashiko AI review report and confirmed against the HWS pattern code. Not reproduced. No in-kernel user puts such actions on the FDB but RDMA flow actions can. Tested for regressions on ConnectX-7 with firmware 28.48.1000 on a little-endian host.

Fixes b36315ca69cb ("net/mlx5: fs, add HWS modify header API function")
---
 .../mellanox/mlx5/core/steering/hws/fs_hws_pools.c    | 11 ++++-------
 .../mellanox/mlx5/core/steering/hws/pat_arg.c         |  8 ++++----
 .../mellanox/mlx5/core/steering/hws/pat_arg.h         |  5 +++++
 3 files changed, 13 insertions(+), 11 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws_pools.c +4 -7
index 86828e329187d..05aa143fa088c 100644
@@ -3,6 +3,7 @@
 
 #include <mlx5_core.h>
 #include "fs_hws_pools.h"
+#include "internal.h"
 
 #define MLX5_FS_HWS_DEFAULT_BULK_LEN 65536
 #define MLX5_FS_HWS_POOL_MAX_THRESHOLD BIT(18)
@@ -389,7 +390,7 @@ bool mlx5_fs_hws_mh_pool_match(struct mlx5_fs_pool *mh_pool,
 			       struct mlx5hws_action_mh_pattern *pattern)
 {
 	struct mlx5hws_action_mh_pattern *pool_pattern;
-	int num_actions, i;
+	int num_actions;
 
 	pool_pattern = mh_pool->pool_ctx;
 	if (WARN_ON_ONCE(!pool_pattern))
@@ -398,12 +399,8 @@ bool mlx5_fs_hws_mh_pool_match(struct mlx5_fs_pool *mh_pool,
 	if (pattern->sz != pool_pattern->sz)
 		return false;
 	num_actions = pattern->sz / MLX5_UN_SZ_BYTES(set_add_copy_action_in_auto);
-	for (i = 0; i < num_actions; i++) {
-		if ((__force __be32)pattern->data[i] !=
-		    (__force __be32)pool_pattern->data[i])
-			return false;
-	}
-	return true;
+	return mlx5hws_pat_compare_pattern(num_actions, pool_pattern->data,
+					   num_actions, pattern->data);
 }
 
 struct mlx5hws_action *mlx5_fc_get_hws_action(struct mlx5hws_context *ctx,
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.c +4 -4
index 512299b59fd0d..a49115f040251 100644
@@ -96,10 +96,10 @@ void mlx5hws_pat_uninit_pattern_cache(struct mlx5hws_pattern_cache *cache)
 	kfree(cache);
 }
 
-static bool mlx5hws_pat_compare_pattern(int cur_num_of_actions,
-					__be64 cur_actions[],
-					int num_of_actions,
-					__be64 actions[])
+bool mlx5hws_pat_compare_pattern(int cur_num_of_actions,
+				 __be64 cur_actions[],
+				 int num_of_actions,
+				 __be64 actions[])
 {
 	int i;
 
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.h +5 -0
index 7fbd8dc7aa186..2be7787104e10 100644
@@ -49,6 +49,11 @@ int mlx5hws_pat_init_pattern_cache(struct mlx5hws_pattern_cache **cache);
 
 void mlx5hws_pat_uninit_pattern_cache(struct mlx5hws_pattern_cache *cache);
 
+bool mlx5hws_pat_compare_pattern(int cur_num_of_actions,
+				 __be64 cur_actions[],
+				 int num_of_actions,
+				 __be64 actions[]);
+
 bool mlx5hws_pat_verify_actions(struct mlx5hws_context *ctx, __be64 pattern[], size_t sz);
 
 int mlx5hws_arg_create(struct mlx5hws_context *ctx,
Signature · 1 line
2.53.0
author maintainer
#2338 lore raw

PATCH 2317/2651 selftests: ALSA: pcmtest: Compare all captured bytes in ni_capture

In reply to Greg Kroah-Hartman

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

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

From: HyeongJun An <[email protected]>

[ Upstream commit c8c199e1b1b3bb0ef52a2a02d1ec87bee574ce13 ]

The ni_capture test reads rate * time frames into each channel buffer and then compares rate * time bytes. A frame is sample_size bytes per channel, so with S16_LE only the first half of each channel is checked. If the second half is wrong the test still passes.

Compare rate * time * sample_size bytes per channel.

Fixes 10b98a4db11a ("selftests: ALSA: Add test for the 'pcmtest' driver")
Assisted-by Claude:claude-opus-5-5
---
 tools/testing/selftests/alsa/test-pcmtest-driver.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/alsa/test-pcmtest-driver.c +1 -1
index e025a7bac26b7..18ee72d5d4c96 100644
@@ -265,7 +265,7 @@ TEST_F(pcmtest, ni_capture) {
 	snd_pcm_close(handle);
 
 	for (i = 0; i < CH_NUM; i++) {
-		for (j = 0; j < params.rate * params.time; j++)
+		for (j = 0; j < params.rate * params.time * params.sample_size; j++)
 			ASSERT_EQ(chan_samples[i][j], patterns[i].buf[j % patterns[i].len]);
 		free(chan_samples[i]);
 	}
Signature · 1 line
2.53.0
author maintainer
#2339 lore raw

PATCH 2318/2651 ALSA: hda/realtek: Add mute and mic-mute LEDs for HP ENVY 16 (103c:8be5)

In reply to Greg Kroah-Hartman

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

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

From: Ajanesh Lal <[email protected]>

[ Upstream commit ed7995e4ec3789a90e37eb826bfccf43cc85d2fd ]

The HP ENVY Laptop 16-h1xxx (PCI SSID 103c:8be5) uses an ALC245 codec with CS35L41 I2C speaker amplifiers. No LED fixup is applied for this subsystem ID, so the speaker mute LED and the microphone mute LED are never driven and do not follow their keys.

Add a fixup that calls the existing ALC245 mute LED COEF helper and the GPIO mic-mute LED helper directly, then chains to the CS35L41 I2C amplifier setup so the speakers keep working. Use it for 103c:8be5.

Tested on an HP ENVY Laptop 16-h1xxx running kernel 7.2.11: the hda::mute and hda::micmute LEDs appear and follow their keys, and the speaker amplifiers still bind (CS35L41 Bound in dmesg). The mic LED GPIO pin and polarity are not verified on other hardware.

Fixes aa8e3ef4fe53 ("ALSA: hda/realtek: Add quirks for various HP ENVY models")
Assisted-by Claude:claude-haiku-5-5
---
 sound/hda/codecs/realtek/alc269.c | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)
sound/hda/codecs/realtek/alc269.c +16 -1
index 30417b1b050cb..350003d406e79 100644
@@ -1642,6 +1642,14 @@ static void alc245_fixup_hp_mute_led_coefbit(struct hda_codec *codec,
 	}
 }
 
+/* mute LED via COEF bit and mic-mute LED via GPIO, called directly */
+static void alc245_fixup_cs35l41_mute_micmute(struct hda_codec *codec,
+					      const struct hda_fixup *fix, int action)
+{
+	alc245_fixup_hp_mute_led_coefbit(codec, fix, action);
+	alc245_fixup_hp_gpio_led(codec, fix, action);
+}
+
 static void alc245_fixup_hp_mute_led_v1_coefbit(struct hda_codec *codec,
 					  const struct hda_fixup *fix,
 					  int action)
@@ -4424,6 +4432,7 @@ enum {
 	ALC245_FIXUP_BASS_HP_DAC,
 	ALC245_FIXUP_ACER_MICMUTE_LED,
 	ALC245_FIXUP_CS35L41_I2C_2_MUTE_LED,
+	ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED,
 	ALC256_FIXUP_HONOR_MRB_XXX_M1020_AUDIO,
 	ALC245_FIXUP_HP_ENVY_X360_15_FH0XXX,
 	ALC287_FIXUP_ACER_MICMUTE_LED,
@@ -7189,6 +7198,12 @@ static const struct hda_fixup alc269_fixups[] = {
 		.chained = true,
 		.chain_id = ALC287_FIXUP_CS35L41_I2C_2,
 	},
+	[ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED] = {
+		.type = HDA_FIXUP_FUNC,
+		.v.func = alc245_fixup_cs35l41_mute_micmute,
+		.chained = true,
+		.chain_id = ALC287_FIXUP_CS35L41_I2C_2,
+	},
 	[ALC256_FIXUP_HONOR_MRB_XXX_M1020_AUDIO] = {
 		.type = HDA_FIXUP_PINS,
 		.v.pins = (const struct hda_pintbl[]) {
@@ -7760,7 +7775,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x103c, 0x8be1, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be2, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be3, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
-	SND_PCI_QUIRK(0x103c, 0x8be5, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2),
+	SND_PCI_QUIRK(0x103c, 0x8be5, "HP Envy 16", ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED),
 	SND_PCI_QUIRK(0x103c, 0x8be6, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be7, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be8, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS),
Signature · 1 line
2.53.0
author maintainer
#2340 lore raw

PATCH 2319/2651 ASoC: wm8994: fix MCLK gating for AIF clocks sourced from MCLK2

In reply to Greg Kroah-Hartman

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

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

From: Marek Szyprowski <[email protected]>

[ Upstream commit 872215109fc880de7a03fa30437346f9212649e8 ]

aif_mclk_set() masks the AIFnCLK_SRC field of the AIFn clocking register, but compares the result with unshifted field values. The MCLK2 source (0x08) therefore never matches, so MCLK2 is never enabled for an AIF clocked from it, and the AIF relies on other users of that clock to keep it running.

On the Exynos4412 Trats2 board, AIF1 and SYSCLK run from MCLK2, the 32768Hz PMIC clock, while the codec is idle. That clock is shared with the WLAN and Bluetooth chips, which enable it only once their drivers are loaded. Until then the codec runs from a stopped clock: FLL1 fails to lock when configured from that state, and the codec floods the kernel log with FIFO error interrupts once a digital path is powered up:

wm8994-codec wm8994-codec: Timed out waiting for FLL lock wm8994-codec wm8994-codec: FIFO error

Booting with clk_ignore_unused, which keeps that clock running from the bootloader, makes both issues disappear.

Fixing just the comparison is not enough. The AIF clock source can be changed while the AIF clock is running, for example the Midas machine driver switches AIF1 between MCLK2 and FLL1 while AIF1CLK is kept enabled for jack detection. Looking up the clock again on disable can then release a different MCLK than the one enabled, leaking the enable count of one clock and underflowing the other.

Shift the field value before decoding it, and remember which MCLK has been enabled for each AIF, so that the same clock is released on disable. While at it, report the MCLK number 1-based in the error message.

---
 sound/soc/codecs/wm8994.c | 28 ++++++++++++++++++----------
 sound/soc/codecs/wm8994.h |  1 +
 2 files changed, 19 insertions(+), 10 deletions(-)
sound/soc/codecs/wm8994.c +18 -10
index 3214cf2a4c916..e166a377e1ed4 100644
@@ -1059,13 +1059,24 @@ static int aif_mclk_set(struct snd_soc_component *component, int aif, bool enabl
 	unsigned int offset, val, clk_idx;
 	int ret;
 
+	/*
+	 * The AIF clock source may be changed while the AIF clock is
+	 * running, so release the MCLK which has been enabled for it
+	 * instead of the one currently selected.
+	 */
+	if (!enable) {
+		clk_disable_unprepare(wm8994->aif_mclk[aif]);
+		wm8994->aif_mclk[aif] = NULL;
+		return 0;
+	}
+
 	if (aif)
 		offset = 4;
 	else
 		offset = 0;
 
 	val = snd_soc_component_read(component, WM8994_AIF1_CLOCKING_1 + offset);
-	val &= WM8994_AIF1CLK_SRC_MASK;
+	val = (val & WM8994_AIF1CLK_SRC_MASK) >> WM8994_AIF1CLK_SRC_SHIFT;
 
 	switch (val) {
 	case 0:
@@ -1078,16 +1089,13 @@ static int aif_mclk_set(struct snd_soc_component *component, int aif, bool enabl
 		return 0;
 	}
 
-	if (enable) {
-		ret = clk_prepare_enable(wm8994->mclk[clk_idx].clk);
-		if (ret < 0) {
-			dev_err(component->dev,	"Failed to enable MCLK%d\n",
-				clk_idx);
-			return ret;
-		}
-	} else {
-		clk_disable_unprepare(wm8994->mclk[clk_idx].clk);
+	ret = clk_prepare_enable(wm8994->mclk[clk_idx].clk);
+	if (ret < 0) {
+		dev_err(component->dev,	"Failed to enable MCLK%d\n",
+			clk_idx + 1);
+		return ret;
 	}
+	wm8994->aif_mclk[aif] = wm8994->mclk[clk_idx].clk;
 
 	return 0;
 }
sound/soc/codecs/wm8994.h +1 -0
index b28398aa9e48f..5b22cfab317e1 100644
@@ -81,6 +81,7 @@ struct wm8994_priv {
 	struct wm_hubs_data hubs;
 	struct wm8994 *wm8994;
 	struct clk_bulk_data mclk[WM8994_NUM_MCLK];
+	struct clk *aif_mclk[2];
 	int sysclk[2];
 	int sysclk_rate[2];
 	int mclk_rate[2];
Signature · 1 line
2.53.0
author maintainer
#2341 lore raw

PATCH 2320/2651 ASoC: wm8994: dont lose the AIF clock ratio when staying at 32kHz SYSCLK

In reply to Greg Kroah-Hartman

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

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

From: Marek Szyprowski <[email protected]>

[ Upstream commit 693574504051a19383640cfb99524a6b69e4624f ]

When SYSCLK drops below 50kHz, the AIFnCLK rate ratio is saved and temporarily lowered to 128fs for accessory detection, then restored once SYSCLK gets fast enough again. The ratio is however saved again on each clock reconfiguration done while SYSCLK is still slow, which overwrites the original ratio with the 128fs one.

This happens on the Exynos4412 Trats2 board, which set MCLK2 as SYSCLK twice during the card probe and then configure FLL1 while still running from MCLK2. Once SYSCLK is switched to FLL1, the 128fs ratio is "restored", so AIF1 is left configured for 48kHz at 128fs while being clocked at 256fs. If any digital path is powered up before a stream reconfigures the AIF, the codec raises FIFO error interrupts every 10ms, flooding the kernel log:

wm8994-codec wm8994-codec: FIFO error

Save the original ratio only when entering the low SYSCLK mode. While at it, move the code duplicated in _wm8994_set_fll() and wm8994_set_dai_sysclk() to a common helper.

Fixes 6730049a4763 ("ASoC: wm8994: Lower AIFnCLK divisor when dropping to 32kHz")
---
 sound/soc/codecs/wm8994.c | 94 +++++++++++++++++----------------------
 1 file changed, 40 insertions(+), 54 deletions(-)
sound/soc/codecs/wm8994.c +40 -54
index e166a377e1ed4..eb2ff1e27be72 100644
@@ -2207,6 +2207,44 @@ static int wm8994_get_fll_config(struct wm8994 *control, struct fll_div *fll,
 	return 0;
 }
 
+/*
+ * If SYSCLK is less than 50kHz adjust AIFnCLK dividers for detection,
+ * restoring the original ones once SYSCLK is fast enough again.
+ */
+static void wm8994_update_aif_clk_rate(struct snd_soc_component *component)
+{
+	struct wm8994_priv *wm8994 = snd_soc_component_get_drvdata(component);
+
+	if (max(wm8994->aifclk[0], wm8994->aifclk[1]) < 50000) {
+		/* Don't overwrite the saved dividers with the 128fs ones */
+		if (!wm8994->aifdiv[0]) {
+			dev_dbg(component->dev, "Configuring AIFs for 128fs\n");
+
+			wm8994->aifdiv[0] = snd_soc_component_read(component,
+								   WM8994_AIF1_RATE)
+				& WM8994_AIF1CLK_RATE_MASK;
+			wm8994->aifdiv[1] = snd_soc_component_read(component,
+								   WM8994_AIF2_RATE)
+				& WM8994_AIF1CLK_RATE_MASK;
+		}
+
+		snd_soc_component_update_bits(component, WM8994_AIF1_RATE,
+				    WM8994_AIF1CLK_RATE_MASK, 0x1);
+		snd_soc_component_update_bits(component, WM8994_AIF2_RATE,
+				    WM8994_AIF2CLK_RATE_MASK, 0x1);
+	} else if (wm8994->aifdiv[0]) {
+		snd_soc_component_update_bits(component, WM8994_AIF1_RATE,
+				    WM8994_AIF1CLK_RATE_MASK,
+				    wm8994->aifdiv[0]);
+		snd_soc_component_update_bits(component, WM8994_AIF2_RATE,
+				    WM8994_AIF2CLK_RATE_MASK,
+				    wm8994->aifdiv[1]);
+
+		wm8994->aifdiv[0] = 0;
+		wm8994->aifdiv[1] = 0;
+	}
+}
+
 static int _wm8994_set_fll(struct snd_soc_component *component, int id, int src,
 			  unsigned int freq_in, unsigned int freq_out)
 {
@@ -2441,33 +2479,7 @@ static int _wm8994_set_fll(struct snd_soc_component *component, int id, int src,
 
 	configure_clock(component);
 
-	/*
-	 * If SYSCLK will be less than 50kHz adjust AIFnCLK dividers
-	 * for detection.
-	 */
-	if (max(wm8994->aifclk[0], wm8994->aifclk[1]) < 50000) {
-		dev_dbg(component->dev, "Configuring AIFs for 128fs\n");
-
-		wm8994->aifdiv[0] = snd_soc_component_read(component, WM8994_AIF1_RATE)
-			& WM8994_AIF1CLK_RATE_MASK;
-		wm8994->aifdiv[1] = snd_soc_component_read(component, WM8994_AIF2_RATE)
-			& WM8994_AIF1CLK_RATE_MASK;
-
-		snd_soc_component_update_bits(component, WM8994_AIF1_RATE,
-				    WM8994_AIF1CLK_RATE_MASK, 0x1);
-		snd_soc_component_update_bits(component, WM8994_AIF2_RATE,
-				    WM8994_AIF2CLK_RATE_MASK, 0x1);
-	} else if (wm8994->aifdiv[0]) {
-		snd_soc_component_update_bits(component, WM8994_AIF1_RATE,
-				    WM8994_AIF1CLK_RATE_MASK,
-				    wm8994->aifdiv[0]);
-		snd_soc_component_update_bits(component, WM8994_AIF2_RATE,
-				    WM8994_AIF2CLK_RATE_MASK,
-				    wm8994->aifdiv[1]);
-
-		wm8994->aifdiv[0] = 0;
-		wm8994->aifdiv[1] = 0;
-	}
+	wm8994_update_aif_clk_rate(component);
 
 	return 0;
 }
@@ -2585,33 +2597,7 @@ static int wm8994_set_dai_sysclk(struct snd_soc_dai *dai,
 
 	configure_clock(component);
 
-	/*
-	 * If SYSCLK will be less than 50kHz adjust AIFnCLK dividers
-	 * for detection.
-	 */
-	if (max(wm8994->aifclk[0], wm8994->aifclk[1]) < 50000) {
-		dev_dbg(component->dev, "Configuring AIFs for 128fs\n");
-
-		wm8994->aifdiv[0] = snd_soc_component_read(component, WM8994_AIF1_RATE)
-			& WM8994_AIF1CLK_RATE_MASK;
-		wm8994->aifdiv[1] = snd_soc_component_read(component, WM8994_AIF2_RATE)
-			& WM8994_AIF1CLK_RATE_MASK;
-
-		snd_soc_component_update_bits(component, WM8994_AIF1_RATE,
-				    WM8994_AIF1CLK_RATE_MASK, 0x1);
-		snd_soc_component_update_bits(component, WM8994_AIF2_RATE,
-				    WM8994_AIF2CLK_RATE_MASK, 0x1);
-	} else if (wm8994->aifdiv[0]) {
-		snd_soc_component_update_bits(component, WM8994_AIF1_RATE,
-				    WM8994_AIF1CLK_RATE_MASK,
-				    wm8994->aifdiv[0]);
-		snd_soc_component_update_bits(component, WM8994_AIF2_RATE,
-				    WM8994_AIF2CLK_RATE_MASK,
-				    wm8994->aifdiv[1]);
-
-		wm8994->aifdiv[0] = 0;
-		wm8994->aifdiv[1] = 0;
-	}
+	wm8994_update_aif_clk_rate(component);
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#2342 lore raw

PATCH 2321/2651 ASoC: wm8994: fix MCLK index used for setting MCLK rate

In reply to Greg Kroah-Hartman

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

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

From: Marek Szyprowski <[email protected]>

[ Upstream commit 7916b55b100973b5fb5b974e8f7c8ae9f3ac1d2e ]

wm8994_set_dai_sysclk() passes the AIF index (dai->id - 1) to wm8994_set_mclk_rate(), which uses it to index the MCLK clocks and their cached rates. As a result, selecting MCLK2 as the AIF1 clock source sets and reads back the rate of MCLK1 instead, and the rate of MCLK1 is then stored as the MCLK2 rate.

On the Exynos4412 Trats2 board, where MCLK1 is a fixed 24MHz clock and MCLK2 a 32768Hz clock used when the codec is idle, this gives:

wm8994-codec wm8994-codec: AIF1 using MCLK2 at 24000000Hz

so the driver assumes a 12MHz SYSCLK while it actually runs at 32kHz. This skips the 128fs AIF clock ratio setup for low SYSCLK rates and makes the mic detection rate configuration use the wrong clock rate.

Pass the MCLK index matching the selected clock source instead.

---
 sound/soc/codecs/wm8994.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
sound/soc/codecs/wm8994.c +2 -2
index eb2ff1e27be72..dd6a9a3c73610 100644
@@ -2539,7 +2539,7 @@ static int wm8994_set_dai_sysclk(struct snd_soc_dai *dai,
 	case WM8994_SYSCLK_MCLK1:
 		wm8994->sysclk[dai->id - 1] = WM8994_SYSCLK_MCLK1;
 
-		ret = wm8994_set_mclk_rate(wm8994, dai->id - 1, &freq);
+		ret = wm8994_set_mclk_rate(wm8994, WM8994_MCLK1, &freq);
 		if (ret < 0)
 			return ret;
 
@@ -2552,7 +2552,7 @@ static int wm8994_set_dai_sysclk(struct snd_soc_dai *dai,
 		/* TODO: Set GPIO AF */
 		wm8994->sysclk[dai->id - 1] = WM8994_SYSCLK_MCLK2;
 
-		ret = wm8994_set_mclk_rate(wm8994, dai->id - 1, &freq);
+		ret = wm8994_set_mclk_rate(wm8994, WM8994_MCLK2, &freq);
 		if (ret < 0)
 			return ret;
 
Signature · 1 line
2.53.0
author maintainer
#2343 lore raw

PATCH 2322/2651 ASoC: samsung: midas_wm1811: run FLL1 at the AIF1 configured rate when idle

In reply to Greg Kroah-Hartman

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

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

From: Marek Szyprowski <[email protected]>

[ Upstream commit d9c23ac1217ab094e6bd9ab95e159ec72c8baca5 ]

When the codec is brought up without an active stream, for example because the mixer state restored by alsactl powers up a digital path, midas_start_fll1() sets FLL1 to the default 11.2896MHz rate. The codec's AIF1 however keeps the configuration of the last stream, or its reset default of 48kHz at 256fs before the first stream, which needs a 12.288MHz AIF1 clock. The digital paths then run with AIF1 clocked at a rate not matching its configuration.

Remember the FLL1 rate requested by the last hw_params() call, which matches the AIF1 configuration kept in the codec, and use it when no specific rate is requested. Change the default rate used before the first stream to 12.288MHz, matching the codec's default AIF1 configuration.

Fixes fd0ea9cd9698 ("ASoC: samsung: Add sound support for Midas boards")
---
 sound/soc/samsung/midas_wm1811.c | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)
sound/soc/samsung/midas_wm1811.c +10 -4
index d43af5069baf9..11466dd3539e8 100644
@@ -25,7 +25,8 @@
  */
 #define MCLK1_RATE 24000000U
 #define MCLK2_RATE 32768U
-#define DEFAULT_FLL1_RATE 11289600U
+/* Matches the codec's default AIF1 configuration: 48kHz, 256fs */
+#define DEFAULT_FLL1_RATE 12288000U
 
 struct midas_priv {
 	struct gpio_desc *gpio_fm_sel;
@@ -34,6 +35,7 @@ struct midas_priv {
 	struct gpio_desc *gpio_headset_key;
 	struct iio_channel *adc_headset_detect;
 	unsigned int fll1_rate;
+	unsigned int aif1clk_rate;
 
 	struct snd_soc_jack headset_jack;
 };
@@ -171,11 +173,12 @@ static int midas_start_fll1(struct snd_soc_pcm_runtime *rtd, unsigned int rate)
 	if (!rate)
 		rate = priv->fll1_rate;
 	/*
-	 * If no new rate is requested, set FLL1 to a sane default for jack
-	 * detection.
+	 * If no new rate is requested, set FLL1 to the rate the codec's AIF1
+	 * is currently configured for, as its digital paths can be powered
+	 * up without an active stream.
 	 */
 	if (!rate)
-		rate = DEFAULT_FLL1_RATE;
+		rate = priv->aif1clk_rate ?: DEFAULT_FLL1_RATE;
 
 	if (rate != priv->fll1_rate && priv->fll1_rate) {
 		/* while reconfiguring, switch to MCLK2 for SYSCLK */
@@ -241,6 +244,7 @@ static int midas_aif1_hw_params(struct snd_pcm_substream *substream,
 				struct snd_pcm_hw_params *params)
 {
 	struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream);
+	struct midas_priv *priv = snd_soc_card_get_drvdata(rtd->card);
 	unsigned int pll_out;
 
 	/* AIF1CLK should be at least 3MHz for "optimal performance" */
@@ -249,6 +253,8 @@ static int midas_aif1_hw_params(struct snd_pcm_substream *substream,
 	else
 		pll_out = params_rate(params) * 256;
 
+	priv->aif1clk_rate = pll_out;
+
 	return midas_start_fll1(rtd, pll_out);
 }
 
Signature · 1 line
2.53.0
author maintainer
#2344 lore raw

PATCH 2323/2651 rust: i2c: remove TryFrom<&Device> implementation for &I2cClient

In reply to Greg Kroah-Hartman

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

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

From: Nicolás Antinori <[email protected]>

[ Upstream commit e7755b5f29ccbfd1222dd52dc2d6eebf39d02289 ]

Remove the TryFrom<&device::Device<Ctx>> implementation for &I2cClient<Ctx> since it has had no users since its introduction.

Fixes 57c5bd9aee94 ("rust: i2c: add basic I2C device and driver abstractions")
---
 rust/kernel/i2c.rs | 21 ---------------------
 1 file changed, 21 deletions(-)
rust/kernel/i2c.rs +0 -21
index 0487bae811fba..b4ff25c830fc0 100644
@@ -5,7 +5,6 @@
 // I2C Driver abstractions.
 use crate::{
     acpi,
-    container_of,
     device,
     device_id::{
         RawDeviceId,
@@ -517,26 +516,6 @@ fn as_ref(&self) -> &device::Device<Ctx> {
     }
 }
 
-impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &I2cClient<Ctx> {
-    type Error = kernel::error::Error;
-
-    fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
-        // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
-        // `struct device`.
-        if unsafe { bindings::i2c_verify_client(dev.as_raw()).is_null() } {
-            return Err(EINVAL);
-        }
-
-        // SAFETY: We've just verified that the type of `dev` equals to
-        // `bindings::i2c_client_type`, hence `dev` must be embedded in a valid
-        // `struct i2c_client` as guaranteed by the corresponding C code.
-        let idev = unsafe { container_of!(dev.as_raw(), bindings::i2c_client, dev) };
-
-        // SAFETY: `idev` is a valid pointer to a `struct i2c_client`.
-        Ok(unsafe { &*idev.cast() })
-    }
-}
-
 // SAFETY: A `I2cClient` is always reference-counted and can be released from any thread.
 unsafe impl Send for I2cClient {}
 
Signature · 1 line
2.53.0
author maintainer
#2345 lore raw

PATCH 2324/2651 selftests/bpf: Time tc_edt from its first packet with data

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit b116ac6087541d3d98031e786adbe9c733cd6df3 ]

tc_edt sends 1MB over a TCP connection that a BPF program shapes with EDT, and checks that the rate it measures is within 2% of the target rate. The transfer takes about 200ms, so the margin is about 4ms.

The measurement starts before send_recv_data(), which first creates the sender thread and accepts the connection. On a KASAN kernel, x86_64 VM with 32 vCPUs, that takes 0.7ms when idle and up to 4.7ms with all CPUs busy, while the BPF program spreads the data over 200.08ms in the median. The test also fails without test_progs -j where everything runs slower, e.g. on s390x and with ASAN in BPF CI.

Have the BPF program note when the first packet with data goes out, and start the measurement there.

tc_edt run 100 times on the same VM, idle and with 32 busy loops in the background, before and after this patch:

                 before                after
  idle           0 of 100 failed       0 of 100 failed
  busy loops     3 of 100 failed       0 of 100 failed
---
 .../testing/selftests/bpf/prog_tests/test_tc_edt.c  | 13 ++++++++++---
 tools/testing/selftests/bpf/progs/test_tc_edt.c     | 13 ++++++++++---
 2 files changed, 20 insertions(+), 6 deletions(-)
tools/testing/selftests/bpf/prog_tests/test_tc_edt.c +10 -3
index 462512fb191f1..1391978a3e309 100644
@@ -90,7 +90,7 @@ static void cleanup(void)
 	remove_netns(SERVER_NS);
 }
 
-static void run_test(void)
+static void run_test(struct test_tc_edt *skel)
 {
 	int server_fd, client_fd, err;
 	double rate_mbps, rate_error;
@@ -113,12 +113,19 @@ static void run_test(void)
 	if (!ASSERT_OK_FD(client_fd, "connect client"))
 		return;
 
-	ts_start = get_time_ns();
 	err = send_recv_data(server_fd, client_fd, TX_BYTES_COUNT);
 	ts_end = get_time_ns();
 	close_netns(nstoken);
 	ASSERT_OK(err, "send_recv_data");
 
+	/*
+	 * Start from the first packet with data rather than before
+	 * send_recv_data(), which also sets up the sender.
+	 */
+	ts_start = skel->bss->tx_start_ns;
+	if (!ASSERT_GT(ts_start, 0, "tx_start_ns"))
+		return;
+
 	rate_mbps = TX_BYTES_COUNT / ((ts_end - ts_start) / 1000.0);
 	rate_error =
 		fabs((rate_mbps - TARGET_RATE_MBPS) * 100.0 / TARGET_RATE_MBPS);
@@ -138,7 +145,7 @@ void test_tc_edt(void)
 	if (!ASSERT_OK(setup(skel), "global setup"))
 		return;
 
-	run_test();
+	run_test(skel);
 
 	cleanup();
 	test_tc_edt__destroy(skel);
tools/testing/selftests/bpf/progs/test_tc_edt.c +10 -3
index 4f6f03122d61d..69f4b16acbef6 100644
@@ -24,6 +24,7 @@ struct {
 } flow_map SEC(".maps");
 
 __uint64_t target_rate;
+__uint64_t tx_start_ns;
 
 static inline int throttle_flow(struct __sk_buff *skb)
 {
@@ -62,7 +63,8 @@ static inline int throttle_flow(struct __sk_buff *skb)
 	return TC_ACT_OK;
 }
 
-static inline int handle_tcp(struct __sk_buff *skb, struct tcphdr *tcp)
+static inline int handle_tcp(struct __sk_buff *skb, struct tcphdr *tcp,
+			     uint32_t hdr_len)
 {
 	void *data_end = (void *)(long)skb->data_end;
 
@@ -70,8 +72,12 @@ static inline int handle_tcp(struct __sk_buff *skb, struct tcphdr *tcp)
 	if ((void *)(tcp + 1) > data_end)
 		return TC_ACT_SHOT;
 
-	if (tcp->source == bpf_htons(9000))
+	if (tcp->source == bpf_htons(9000)) {
+		/* Note when the first packet with data goes out */
+		if (!tx_start_ns && skb->len > hdr_len + tcp->doff * 4)
+			tx_start_ns = bpf_ktime_get_ns();
 		return throttle_flow(skb);
+	}
 
 	return TC_ACT_OK;
 }
@@ -94,7 +100,8 @@ static inline int handle_ipv4(struct __sk_buff *skb)
 		return TC_ACT_SHOT;
 
 	if (iph->protocol == IPPROTO_TCP)
-		return handle_tcp(skb, (struct tcphdr *)(((void *)iph) + ihl));
+		return handle_tcp(skb, (struct tcphdr *)(((void *)iph) + ihl),
+				  sizeof(struct ethhdr) + ihl);
 
 	return TC_ACT_OK;
 }
Signature · 1 line
2.53.0
author maintainer
#2346 lore raw

PATCH 2325/2651 sh: Select BINFMT_FLAT_NO_DATA_START_OFFSET for !MMU

In reply to Greg Kroah-Hartman

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

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

From: Waldemar Brodkorb <[email protected]>

[ Upstream commit f45711b39e03ff5e80b60dcc1fd34b3fc7d3d36c ]

binfmt_flat offsets the in-memory start of the data segment by MAX_SHARED_LIBS words and then aligns it to FLAT_DATA_ALIGN, so FLAT_FLAG_RAM binaries end up with a gap between text and data (commit 2217b9826246 ("binfmt_flat: revert "binfmt_flat: don't offset the data start"")).

SH position-independent code finds the GOT with a PC-relative mova of _GLOBAL_OFFSET_TABLE_, which assumes data follows text directly, as elf2flt lays out the image. With the gap, the GOT register points below the real GOT, so every GOT load reads the neighbouring slot and gets a wrong pointer. On a J2 (sh2eb, no MMU) this made userland crash or hang right after start-up. In my case the data was moved up by 0x20 bytes.

Commit 04d82a6d0881 ("binfmt_flat: allow not offsetting data start") added CONFIG_BINFMT_FLAT_NO_DATA_START_OFFSET for architectures that cannot tolerate such a gap; currently only riscv !MMU selects it. Select it on SH as well when building without an MMU.

Tested on a J2 board (Numato Mimas V2, sh2eb, no MMU) with Linux 7.3 and FLAT binaries built with elf2flt: with this change the data segment starts exactly at the end of text and init runs.

Without the patch bootup fails with:

[   12.080472] Fixing up unaligned userspace access in "init" pid=1 pc=0x(ptrval) ins=0x6583
[   12.123609] Fixing up unaligned userspace access in "init" pid=1 pc=0x(ptrval) ins=0x6583
[   12.175153] Kernel panic - not syncing: Attempted to kill init! exitcode=0x00007f00
Fixes 2217b9826246 ("binfmt_flat: revert "binfmt_flat: don't offset the data start"")
Assisted-by LLM
---
 arch/sh/Kconfig | 1 +
 1 file changed, 1 insertion(+)
arch/sh/Kconfig +1 -0
index d60f1d5a94c0f..b501153551c04 100644
@@ -15,6 +15,7 @@ config SUPERH
 	select ARCH_MIGHT_HAVE_PC_PARPORT
 	select ARCH_WANT_IPC_PARSE_VERSION
 	select ARCH_NEED_CMPXCHG_1_EMU
+	select BINFMT_FLAT_NO_DATA_START_OFFSET if !MMU
 	select CPU_NO_EFFICIENT_FFS
 	select DMA_DECLARE_COHERENT
 	select GENERIC_ATOMIC64
Signature · 1 line
2.53.0
author maintainer
#2347 lore raw

PATCH 2326/2651 PCI/pwrctrl: Power off child devices on power-on failure

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit b6087ff2b7a4c9f98c78f56f0f357557fc008768 ]

pci_pwrctrl_power_on_device() recursively powers on the child nodes of a device before powering on the device itself. If powering on a child fails (e.g. returning -EPROBE_DEFER), the function returned immediately, leaving the sibling children that were already powered on in the same loop iteration enabled.

Since probe deferral is a standard boot path, this leads to unbounded regulator and clock enable increments across retries. The error path in pci_pwrctrl_power_on_devices() only powers off the top-level children processed before the failing one and explicitly stops at it, so it can never clean up the siblings leaked deeper in the failed subtree.

Power off the sibling children that were successfully powered on before a child fails, and power off all children if the device's own power_on() fails after its children were already enabled. Switch to a manual child iterator so the failing node can be tracked and its reference released in the error path.

---
 drivers/pci/pwrctrl/core.c | 19 +++++++++++++++++--
 1 file changed, 17 insertions(+), 2 deletions(-)
drivers/pci/pwrctrl/core.c +17 -2
index c14df117ece37..0e2387cf46577 100644
@@ -252,14 +252,16 @@ static int __pci_pwrctrl_power_on_device(struct device *dev)
 static int pci_pwrctrl_power_on_device(struct device_node *np)
 {
 	struct platform_device *pdev;
+	struct device_node *child;
 	int ret = 0;
 
-	for_each_available_child_of_node_scoped(np, child) {
+	for_each_available_child_of_node(np, child) {
 		ret = pci_pwrctrl_power_on_device(child);
 		if (ret)
-			return ret;
+			goto err_power_off;
 	}
 
+	child = NULL;
 	if (!pci_pwrctrl_is_required(np))
 		return 0;
 
@@ -279,6 +281,19 @@ static int pci_pwrctrl_power_on_device(struct device_node *np)
 
 	platform_device_put(pdev);
 
+	if (ret)
+		goto err_power_off;
+
+	return 0;
+
+err_power_off:
+	for_each_available_child_of_node_scoped(np, tmp) {
+		if (tmp == child)
+			break;
+		pci_pwrctrl_power_off_device(tmp);
+	}
+	of_node_put(child);
+
 	return ret;
 }
 
Signature · 1 line
2.53.0
author maintainer
#2348 lore raw

PATCH 2327/2651 perf c2c: Fix memory leaks on output fields

In reply to Greg Kroah-Hartman

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

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

From: Namhyung Kim <[email protected]>

[ Upstream commit 7d0fe18bc905a4bf59271e2f7ecc95479caebd7b ]

The perf_hpp_list was not freed after use. Let's add it for the main c2c hists list in perf c2c report and a local list in print_pareto().

Previously it was detected by ASAN like below.

=================================================================
==42183==ERROR: LeakSanitizer: detected memory leaks

Indirect leak of 1064 byte(s) in 7 object(s) allocated from:

      #0 0x7f17334ef24f in calloc (/lib64/libasan.so.8+0xef24f) (BuildId: 61e8165ca90f7a4f06b73f064a938c76deaae079)
      #1 0x0000005fa099 in zalloc  ../../lib/zalloc.c:8
      #2 0x0000004faf6d in get_format  tools/perf/builtin-c2c.c:1978
      #3 0x0000004fb45e in c2c_hists__init_output  tools/perf/builtin-c2c.c:2004
      #4 0x0000004fb7de in __hpp_list__parse  tools/perf/builtin-c2c.c:2047
      #5 0x0000004fbae9 in hpp_list__parse  tools/perf/builtin-c2c.c:2085
      #6 0x0000004fee13 in print_pareto  tools/perf/builtin-c2c.c:2563
      #7 0x0000004ffcd7 in perf_c2c__hists_fprintf  tools/perf/builtin-c2c.c:2708
      #8 0x000000500ab5 in perf_c2c_display  tools/perf/builtin-c2c.c:2949
      #9 0x0000005045c3 in perf_c2c__report  tools/perf/builtin-c2c.c:3522
      #10 0x000000505caa in cmd_c2c  tools/perf/builtin-c2c.c:3676
      #11 0x0000005df50e in run_builtin  tools/perf/perf.c:383
      #12 0x0000005df9b1 in handle_internal_command  tools/perf/perf.c:436
      #13 0x0000005dfd7f in run_argv  tools/perf/perf.c:480
      #14 0x0000005e02d6 in main  tools/perf/perf.c:581
      #15 0x7f1729450680 in __libc_start_call_main (/lib64/libc.so.6+0x3680) (BuildId: 85075e2ae2e13352a1413d41c327dacf6461526c)
      #16 0x7f1729450797 in __libc_start_main@GLIBC_2.2.5 (/lib64/libc.so.6+0x3797) (BuildId: 85075e2ae2e13352a1413d41c327dacf6461526c)
      #17 0x000000409c34 in _start (tools/perf/perf+0x409c34) (BuildId: 36a64600776d92e4ab7dfd5ca20c92280d72a645)

SUMMARY: AddressSanitizer: 1064 byte(s) leaked in 7 allocation(s).

Fixes c75540e3160fb586 ("perf c2c report: Add dimension support")
Cc Jiri Olsa <[email protected]>
---
 tools/perf/builtin-c2c.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
tools/perf/builtin-c2c.c +13 -3
index 715b75d42f2a8..0beda148cdf36 100644
@@ -2087,6 +2087,11 @@ static int c2c_hists__reinit(struct c2c_hists *c2c_hists,
 	return ret;
 }
 
+static void c2c_hists__exit(struct c2c_hists *c2c_hists)
+{
+	perf_hpp__reset_output_field(&c2c_hists->list);
+}
+
 #define DISPLAY_LINE_LIMIT  0.001
 
 static u8 filter_display(u32 val, u32 sum)
@@ -2495,7 +2500,7 @@ static void print_pareto(FILE *out, struct perf_env *env)
 	ret = hpp_list__parse(&hpp_list, cl_output, /*evlist=*/NULL, env);
 
 	if (WARN_ONCE(ret, "failed to setup sort entries\n"))
-		return;
+		goto out;
 
 	nd = rb_first_cached(&c2c.hists.hists.entries);
 
@@ -2509,6 +2514,9 @@ static void print_pareto(FILE *out, struct perf_env *env)
 		c2c_he = container_of(he, struct c2c_hist_entry, he);
 		print_cacheline(c2c_he->hists, he, &hpp_list, out);
 	}
+
+out:
+	perf_hpp__reset_output_field(&hpp_list);
 }
 
 static void print_c2c_info(FILE *out, struct perf_session *session)
@@ -3211,12 +3219,12 @@ static int perf_c2c__report(int argc, const char **argv)
 	err = setup_nodes(session);
 	if (err) {
 		pr_err("Failed setup nodes\n");
-		goto out_session;
+		goto out_hists;
 	}
 
 	err = mem2node__init(&c2c.mem2node, env);
 	if (err)
-		goto out_session;
+		goto out_hists;
 
 	err = setup_callchain(session->evlist);
 	if (err)
@@ -3336,6 +3344,8 @@ static int perf_c2c__report(int argc, const char **argv)
 
 out_mem2node:
 	mem2node__exit(&c2c.mem2node);
+out_hists:
+	c2c_hists__exit(&c2c.hists);
 out_session:
 	perf_session__delete(session);
 out:
Signature · 1 line
2.53.0
author maintainer
#2349 lore raw

PATCH 2328/2651 perf cs-etm: Dont add global v0 HW_IDs to unformatted queues

In reply to Greg Kroah-Hartman

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

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

From: James Clark <[email protected]>

[ Upstream commit 31627cfb63ae4af5a233dc6ced04e5172789aa92 ]

In the case of mixed formatted and unformatted trace with v0 HW_IDs, or no HW_IDs at all resulting in the cs_etm__map_trace_ids_metadata() fallback, formatted queues will write their HW_IDs to unformatted queues. This will result in an assert because of multiple decoders on an unformatted queue.

Fix it by not inserting trace ID nodes on other unformatted queues. This isn't an issue for v0.1 HW_IDs because they aren't global so will only add to their own queue.

Fixes 19c3e4db38c5bf30 ("perf: cs-etm: Create decoders based on the trace ID mappings")
---
 tools/perf/util/cs-etm.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
tools/perf/util/cs-etm.c +6 -6
index 114b3cd2da495..1ac627d339828 100644
@@ -309,27 +309,27 @@ static int cs_etm__map_trace_id_v0(struct cs_etm_auxtrace *etm, u8 trace_chan_id
 {
 	struct cs_etm_queue *etmq;
 
-	/*
-	 * If the queue is unformatted then only save one mapping in the
-	 * queue associated with that CPU so only one decoder is made.
-	 */
 	etmq = cs_etm__get_queue(etm, cpu_metadata[CS_ETM_CPU]);
 	if (!etmq)
 		return -EINVAL;
 
+	/*
+	 * If the queue is unformatted then only save one mapping in the
+	 * queue associated with that CPU so only one decoder is made.
+	 */
 	if (etmq->format == UNFORMATTED)
 		return cs_etm__insert_trace_id_node(etmq, trace_chan_id,
 						    cpu_metadata);
 
 	/*
 	 * Otherwise, version 0 trace IDs are global so save them into every
-	 * queue.
+	 * formatted queue.
 	 */
 	for (unsigned int i = 0; i < etm->queues.nr_queues; ++i) {
 		int ret;
 
 		etmq = etm->queues.queue_array[i].priv;
-		if (!etmq)
+		if (!etmq || etmq->format == UNFORMATTED)
 			continue;
 
 		ret = cs_etm__insert_trace_id_node(etmq, trace_chan_id,
Signature · 1 line
2.53.0
author maintainer
#2350 lore raw

PATCH 2329/2651 nvme-fabrics: reset io_queues before computing the queue mapping

In reply to Greg Kroah-Hartman

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

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

From: Daniel Wagner <[email protected]>

[ Upstream commit 9588769af5fc8ac12290d48ce1014a78916681fc ]

nvmf_set_io_queues only sets the io_queues entries of the queue types it hands out, but the array is reused on every reconnect. When the controller grants fewer queues on a reconnect, stale entries survive and nvmf_map_queues maps CPUs to hardware contexts that don't exist anymore, which crashes blk_mq_map_swqueue with a NULL pointer dereference. E.g. with nr_io_queues=8, nr_write_queues=8 and nr_poll_queues=8, 24 queues are mapped 8/8/8 (default/read/poll). If the controller grants only 16 queues on the reconnect, the poll map still starts at hardware context 16.

Clear the array before computing the new mapping.

Fixes 6486199378a5 ("nvme-tcp: fix queue mapping when queue count is limited")
Fixes 5651cd3c4336 ("nvme-rdma: fix queue mapping when queue count is limited")
---
 drivers/nvme/host/fabrics.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/nvme/host/fabrics.c +2 -0
index 59f823dfbbccb..571de549fbafc 100644
@@ -1125,6 +1125,8 @@ static int nvmf_parse_options(struct nvmf_ctrl_options *opts,
 void nvmf_set_io_queues(struct nvmf_ctrl_options *opts, u32 nr_io_queues,
 			u32 io_queues[HCTX_MAX_TYPES])
 {
+	memset(io_queues, 0, sizeof(*io_queues) * HCTX_MAX_TYPES);
+
 	if (opts->nr_write_queues && opts->nr_io_queues < nr_io_queues) {
 		/*
 		 * separate read/write queues
Signature · 1 line
2.53.0
author maintainer
#2351 lore raw

PATCH 2330/2651 nvme-fabrics: limit each queue type to the number of online CPUs

In reply to Greg Kroah-Hartman

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

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

From: Daniel Wagner <[email protected]>

[ Upstream commit 99fd0cbae84988e0af34784aa18ddd51ae094ade ]

nvmf_nr_io_queues limits each queue type to the number of online CPUs when asking for I/O queues, but nvmf_set_io_queues hands out the granted queues without these limits, and only nr_io_queues is clamped when parsing the options.

E.g. with 2 CPUs, nr_io_queues=2, nr_write_queues=10 and nr_poll_queues=10, 2 + 2 + 2 = 6 queues are requested, but handed out as 4 default, 2 read and 0 poll queues. blk_mq_map_queues can't create more CPU masks than there are CPUs, so default queues 2 and 3 take over the CPUs of default queues 0 and 1, and connecting the I/O queue of default queue 1 fails with -EXDEV.

Apply the same limits in nvmf_set_io_queues. A queue type with more queues than online CPUs always has a hardware context without an online CPU, so no working setup changes. The options are not modified, so the limits follow CPU hotplug on reconnect.

Fixes 6486199378a5 ("nvme-tcp: fix queue mapping when queue count is limited")
Fixes a249d3066de6 ("nvme-fabrics: add queue setup helpers")
---
 drivers/nvme/host/fabrics.c | 21 +++++++++++++++------
 1 file changed, 15 insertions(+), 6 deletions(-)
drivers/nvme/host/fabrics.c +15 -6
index 571de549fbafc..27a8ce51d2b35 100644
@@ -1125,18 +1125,27 @@ static int nvmf_parse_options(struct nvmf_ctrl_options *opts,
 void nvmf_set_io_queues(struct nvmf_ctrl_options *opts, u32 nr_io_queues,
 			u32 io_queues[HCTX_MAX_TYPES])
 {
+	/*
+	 * Each queue type is mapped to the CPUs separately, so a type with
+	 * more queues than online CPUs has hardware contexts without an online
+	 * CPU.  Use the same limits as nvmf_nr_io_queues.
+	 */
+	u32 nr_io = min(opts->nr_io_queues, num_online_cpus());
+	u32 nr_write = min(opts->nr_write_queues, num_online_cpus());
+	u32 nr_poll = min(opts->nr_poll_queues, num_online_cpus());
+
 	memset(io_queues, 0, sizeof(*io_queues) * HCTX_MAX_TYPES);
 
-	if (opts->nr_write_queues && opts->nr_io_queues < nr_io_queues) {
+	if (nr_write && nr_io < nr_io_queues) {
 		/*
 		 * separate read/write queues
 		 * hand out dedicated default queues only after we have
 		 * sufficient read queues.
 		 */
-		io_queues[HCTX_TYPE_READ] = opts->nr_io_queues;
+		io_queues[HCTX_TYPE_READ] = nr_io;
 		nr_io_queues -= io_queues[HCTX_TYPE_READ];
 		io_queues[HCTX_TYPE_DEFAULT] =
-			min(opts->nr_write_queues, nr_io_queues);
+			min(nr_write, nr_io_queues);
 		nr_io_queues -= io_queues[HCTX_TYPE_DEFAULT];
 	} else {
 		/*
@@ -1145,14 +1154,14 @@ void nvmf_set_io_queues(struct nvmf_ctrl_options *opts, u32 nr_io_queues,
 		 * sufficient queue count to have dedicated default queues.
 		 */
 		io_queues[HCTX_TYPE_DEFAULT] =
-			min(opts->nr_io_queues, nr_io_queues);
+			min(nr_io, nr_io_queues);
 		nr_io_queues -= io_queues[HCTX_TYPE_DEFAULT];
 	}
 
-	if (opts->nr_poll_queues && nr_io_queues) {
+	if (nr_poll && nr_io_queues) {
 		/* map dedicated poll queues only if we have queues left */
 		io_queues[HCTX_TYPE_POLL] =
-			min(opts->nr_poll_queues, nr_io_queues);
+			min(nr_poll, nr_io_queues);
 	}
 }
 EXPORT_SYMBOL_GPL(nvmf_set_io_queues);
Signature · 1 line
2.53.0
author maintainer
#2352 lore raw

PATCH 2331/2651 nvme-fabrics: clear the poll map if no poll queues are mapped

In reply to Greg Kroah-Hartman

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

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

From: Daniel Wagner <[email protected]>

[ Upstream commit 36ede1aa85d5d74c39ed375a906f6eadb15cee5b ]

blk_mq_alloc_tag_set sets the nr_queues of every map to nr_hw_queues. When nr_poll_queues is set but no queues are left for polling, nvmf_map_queues skips the poll map and leaves it this way, with all CPUs mapped to hctx 0. The queue then claims poll support, polled I/O ends up on hctx 0, which isn't a poll queue, and hctx 0 is marked as a poll hctx, so even the Connect command of the first I/O queue is marked as polled.

Clear the poll map when no poll queues are mapped, so polled I/O is rejected with -EOPNOTSUPP.

Fixes 1a9460cef571 ("nvme-tcp: support simple polling")
Fixes 5651cd3c4336 ("nvme-rdma: fix queue mapping when queue count is limited")
---
 drivers/nvme/host/fabrics.c | 7 +++++++
 1 file changed, 7 insertions(+)
drivers/nvme/host/fabrics.c +7 -0
index 27a8ce51d2b35..3d7ad86c1955f 100644
@@ -1199,6 +1199,13 @@ void nvmf_map_queues(struct blk_mq_tag_set *set, struct nvme_ctrl *ctrl,
 			io_queues[HCTX_TYPE_DEFAULT] +
 			io_queues[HCTX_TYPE_READ];
 		blk_mq_map_queues(&set->map[HCTX_TYPE_POLL]);
+	} else {
+		/*
+		 * blk_mq_alloc_tag_set sets nr_queues of all maps to
+		 * nr_hw_queues.  Clear the poll map, otherwise the queue claims
+		 * poll support and polled I/O ends up on hctx 0.
+		 */
+		set->map[HCTX_TYPE_POLL].nr_queues = 0;
 	}
 
 	dev_info(ctrl->device,
Signature · 1 line
2.53.0
author maintainer
#2353 lore raw

PATCH 2332/2651 sched_ext: Reject oversized automatic CID shards

In reply to Greg Kroah-Hartman

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

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

From: Hui Su <[email protected]>

[ Upstream commit 651694bc47a15b99e756ebb27f4e6be6d59bf397 ]

Automatic topology packing starts a new shard before adding a core when the current shard would exceed its target size. However, a first core is always accepted so that cores remain indivisible. An indivisible core with more than SCX_CID_SHARD_MAX_CPUS CPUs cannot be represented without exceeding the hard shard limit.

Per-shard state uses fixed-size inline cmask storage sized for SCX_CID_SHARD_MAX_CPUS. Passing an oversized shard to alloc_pshard() can therefore make cmask initialization overwrite the following fields.

Reject an indivisible core larger than SCX_CID_SHARD_MAX_CPUS before adding it to a shard. Existing non-empty shard splitting already keeps the total within the hard cap, while an indivisible core may still exceed cid_shard_size when it fits within the hard limit.

Report the oversized core and the hard limit with scx_error() so that the rejection is diagnosable.

tj: The bug is only reproducible with artificial VM topologies. It can't
happen on real hardware.

Fixes e2c841b91bf9 ("sched_ext: Add CID sharding")
---
 kernel/sched/ext/cid.c | 6 ++++++
 1 file changed, 6 insertions(+)
kernel/sched/ext/cid.c +6 -0
index 4b08866d75f6a..3d0687184b448 100644
@@ -287,6 +287,12 @@ s32 scx_cid_init(struct scx_sched *sch)
 				 * empty shard.
 				 */
 				cids_in_core = cpumask_weight(core_scratch);
+				if (cids_in_core > SCX_CID_SHARD_MAX_CPUS) {
+					scx_error(sch, "core with %u cpus exceeds max shard size %d",
+						  cids_in_core, SCX_CID_SHARD_MAX_CPUS);
+					return -E2BIG;
+				}
+
 				max_cores = cores_per_shard + (shard_local < nr_large ? 1 : 0);
 				if (cores_in_shard &&
 				    (cores_in_shard >= max_cores ||
Signature · 1 line
2.53.0
author maintainer
#2354 lore raw

PATCH 2333/2651 perf lock contention: Filter events before creating lock_stat

In reply to Greg Kroah-Hartman

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

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

From: Ian Rogers <[email protected]>

[ Upstream commit c58d1598e79554cc8f587668ab2ebcaeb616b076 ]

In report_lock_contention_begin_event(), lock_stat_findnew() was called before checking filters.nr_types (-Y), filters.nr_addrs (-L), and match_callstack_filter() (-S).

When a filtered-out lock event (such as a mutex contention when running with -Y spinlock) shared the same aggregation key as a subsequent matching event (for example, contention on the mutex's internal wait_lock spinlock from the same caller), the first event created the lock_stat entry with the filtered-out lock's flags and the second event reused that entry, causing non-spinlock entries to appear in -Y spinlock output.

Check the type, address, and callstack filters before looking up or creating the lock_stat entry.

Fixes b4a7eff93c39f985 ("perf lock contention: Add -Y/--type-filter option")
---
 tools/perf/builtin-lock.c | 61 +++++++++++++++++++++------------------
 1 file changed, 33 insertions(+), 28 deletions(-)
tools/perf/builtin-lock.c +33 -28
index d5c0d55cb82d9..778923c92f420 100644
@@ -975,6 +975,7 @@ static int report_lock_contention_begin_event(struct perf_sample *sample)
 	struct machine *machine = &session->machines.host;
 	struct map *kmap;
 	struct symbol *sym;
+	u64 *callstack = NULL;
 
 	ret = get_key_by_aggr_mode(&key, addr, sample);
 	if (ret < 0)
@@ -1010,33 +1011,6 @@ static int report_lock_contention_begin_event(struct perf_sample *sample)
 		}
 	}
 
-	ls = lock_stat_find(key);
-	if (!ls) {
-		char buf[128];
-		const char *name = "";
-
-		switch (aggr_mode) {
-		case LOCK_AGGR_ADDR:
-			sym = machine__find_kernel_symbol(machine, key, &kmap);
-			if (sym)
-				name = sym->name;
-			break;
-		case LOCK_AGGR_CALLER:
-			name = buf;
-			if (lock_contention_caller(sample, buf, sizeof(buf)) < 0)
-				name = "Unknown";
-			break;
-		case LOCK_AGGR_CGROUP:
-		case LOCK_AGGR_TASK:
-		default:
-			break;
-		}
-
-		ls = lock_stat_findnew(key, name, flags);
-		if (!ls)
-			return -ENOMEM;
-	}
-
 	if (filters.nr_types) {
 		bool found = false;
 
@@ -1066,7 +1040,7 @@ static int report_lock_contention_begin_event(struct perf_sample *sample)
 	}
 
 	if (needs_callstack()) {
-		u64 *callstack = get_callstack(sample, max_stack_depth);
+		callstack = get_callstack(sample, max_stack_depth);
 		if (callstack == NULL)
 			return 0;
 
@@ -1074,7 +1048,38 @@ static int report_lock_contention_begin_event(struct perf_sample *sample)
 			free(callstack);
 			return 0;
 		}
+	}
+
+	ls = lock_stat_find(key);
+	if (!ls) {
+		char buf[128];
+		const char *name = "";
+
+		switch (aggr_mode) {
+		case LOCK_AGGR_ADDR:
+			sym = machine__find_kernel_symbol(machine, key, &kmap);
+			if (sym)
+				name = sym->name;
+			break;
+		case LOCK_AGGR_CALLER:
+			name = buf;
+			if (lock_contention_caller(sample, buf, sizeof(buf)) < 0)
+				name = "Unknown";
+			break;
+		case LOCK_AGGR_CGROUP:
+		case LOCK_AGGR_TASK:
+		default:
+			break;
+		}
+
+		ls = lock_stat_findnew(key, name, flags);
+		if (!ls) {
+			free(callstack);
+			return -ENOMEM;
+		}
+	}
 
+	if (callstack) {
 		if (ls->callstack == NULL)
 			ls->callstack = callstack;
 		else
Signature · 1 line
2.53.0
author maintainer
#2355 lore raw

PATCH 2334/2651 mailbox: qcom-cpucp: read mbox hardware register using readq()

In reply to Greg Kroah-Hartman

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

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

From: Sivansh Gupta <[email protected]>

[ Upstream commit 74f1cf02d9fe0fd32ca299cd4d71bc29d3bf2a54 ]

Mailbox hardware registers are 64 bit wide, but the interrupt handler currently reads only 32 bits with readl() at offset 0x4 (upper 32 bits). This returns an incorrect value, while reading using readq() returns the expected value.

Use readq() to access the 64 bit register and pass the expected value to the mailbox client.

Fixes 0e2a9a03106c ("mailbox: Add support for QTI CPUCP mailbox controller")
---
 drivers/mailbox/qcom-cpucp-mbox.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/mailbox/qcom-cpucp-mbox.c +1 -1
index 515d2d12c01be..b88ea2527265a 100644
@@ -61,7 +61,7 @@ static irqreturn_t qcom_cpucp_mbox_irq_fn(int irq, void *data)
 	status = readq(cpucp->rx_base + APSS_CPUCP_RX_MBOX_STAT);
 
 	for_each_set_bit(i, (unsigned long *)&status, cpucp->mbox.num_chans) {
-		u32 val = readl(cpucp->rx_base + APSS_CPUCP_RX_MBOX_CMD(i) + APSS_CPUCP_MBOX_CMD_OFF);
+		u64 val = readq(cpucp->rx_base + APSS_CPUCP_RX_MBOX_CMD(i));
 		struct mbox_chan *chan = &cpucp->chans[i];
 		struct mbox_client *cl;
 		unsigned long flags;
Signature · 1 line
2.53.0
author maintainer
#2356 lore raw

PATCH 2335/2651 ionic: fix port_info use-after-free on firmware recovery

In reply to Greg Kroah-Hartman

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

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

From: Nikhil P. Rao <[email protected]>

[ Upstream commit d90d1a768b3b022c52beafb3a4701ee2ee3d2b5e ]

ionic_port_init() allocates port_info when the pointer is NULL, but its error path frees it without checking whether this call allocated it. Before commit ddc5911b9bd2 ("ionic: call ionic_port_init after fw-upgrade") the function returned early when the buffer already existed, so the two were symmetric.

Since then a failed PORT_INIT on either recovery path - fw_up or reset_done - frees a buffer an earlier init owns, while the netdev is registered and the ethtool ops are reading it.

Free only what this call allocated.

---
 drivers/net/ethernet/pensando/ionic/ionic_main.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
drivers/net/ethernet/pensando/ionic/ionic_main.c +9 -4
index 10501be9ef956..38b47b959a114 100644
@@ -722,6 +722,7 @@ int ionic_port_init(struct ionic *ionic)
 {
 	struct ionic_identity *ident = &ionic->ident;
 	struct ionic_dev *idev = &ionic->idev;
+	bool allocated = false;
 	size_t sz;
 	int err;
 
@@ -733,6 +734,8 @@ int ionic_port_init(struct ionic *ionic)
 						     GFP_KERNEL);
 		if (!idev->port_info)
 			return -ENOMEM;
+
+		allocated = true;
 	}
 
 	/* If the driver knows about more "extra stats" than the firmware,
@@ -757,10 +760,12 @@ int ionic_port_init(struct ionic *ionic)
 	mutex_unlock(&ionic->dev_cmd_lock);
 	if (err) {
 		dev_err(ionic->dev, "Failed to init port\n");
-		dma_free_coherent(ionic->dev, idev->port_info_sz,
-				  idev->port_info, idev->port_info_pa);
-		idev->port_info = NULL;
-		idev->port_info_pa = 0;
+		if (allocated) {
+			dma_free_coherent(ionic->dev, idev->port_info_sz,
+					  idev->port_info, idev->port_info_pa);
+			idev->port_info = NULL;
+			idev->port_info_pa = 0;
+		}
 	}
 
 	return err;
Signature · 1 line
2.53.0
author maintainer
#2357 lore raw

PATCH 2336/2651 ionic: free port_info when probe fails after the port is set up

In reply to Greg Kroah-Hartman

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

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

From: Eric Joyner <[email protected]>

[ Upstream commit 4e15e0a941ce901d51b5f203713fa90feee9c4d3 ]

ionic_probe() allocates the port_info DMA buffer via ionic_setup_one() -> ionic_port_init(). If probe then fails anywhere after that, it unwinds through err_out_pci, which never calls ionic_port_reset(); ionic_dev_teardown() and ionic_clear_pci() do not touch port_info, and so the buffer is leaked. The call was lost when the setup code was moved into ionic_setup_one().

Since ionic_remove() already frees the port_info DMA buffer with ionic_port_reset(), call that on the probe error path too. Every path to err_out_pci runs after ionic_setup_one() succeeded, so the BARs are still mapped and the firmware gets a PORT_RESET before the buffer is freed, the same order as in ionic_remove().

Fixes 0de38d9f1dba ("ionic: extract common bits from ionic_probe")
---
 drivers/net/ethernet/pensando/ionic/ionic_bus_pci.c | 1 +
 1 file changed, 1 insertion(+)
drivers/net/ethernet/pensando/ionic/ionic_bus_pci.c +1 -0
index 05f19489ec5c8..68b3bceedd999 100644
@@ -397,6 +397,7 @@ static int ionic_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
 err_out_free_irqs:
 	ionic_bus_free_irq_vectors(ionic);
 err_out_pci:
+	ionic_port_reset(ionic);
 	ionic_dev_teardown(ionic);
 	ionic_clear_pci(ionic);
 	ionic_debugfs_del_dev(ionic);
Signature · 1 line
2.53.0
author maintainer
#2358 lore raw

PATCH 2337/2651 net: hibmcge: set netdev_ops before hbg_init() to fix NULL pointer dereference

In reply to Greg Kroah-Hartman

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

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

From: Jijie Shao <[email protected]>

[ Upstream commit 9b8ae9aaa1b8e2b6c1cbf5613d3a37923cf53bc5 ]

The driver assigns netdev_ops after hbg_init(), but hbg_init() calls hbg_mdio_init() -> hbg_phy_connect() -> phy_connect_direct() -> phy_attach_direct() -> phy_link_topo_add_phy(), which invokes netdev_need_ops_lock(). With CONFIG_NET_SHAPER enabled, this function dereferences dev->netdev_ops->net_shaper_ops. Since netdev_ops is still NULL at this point, a NULL pointer dereference occurs.

Move the netdev_ops assignment before hbg_init() so that netdev_need_ops_lock() can safely access netdev_ops during PHY attachment.

The issue was hit and verified on an evaluation board.

Fixes ff4edac6e9bd ("net: hibmcge: Implement some .ndo functions")
---
 drivers/net/ethernet/hisilicon/hibmcge/hbg_main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/hisilicon/hibmcge/hbg_main.c +1 -1
index 66792e2b0fadc..a518dc66d9ef8 100644
@@ -448,6 +448,7 @@ static int hbg_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
 	if (ret)
 		return ret;
 
+	netdev->netdev_ops = &hbg_netdev_ops;
 	ret = hbg_init(priv);
 	if (ret)
 		return ret;
@@ -460,7 +461,6 @@ static int hbg_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
 	netdev->pcpu_stat_type = NETDEV_PCPU_STAT_TSTATS;
 	netdev->max_mtu = priv->dev_specs.max_mtu;
 	netdev->min_mtu = priv->dev_specs.min_mtu;
-	netdev->netdev_ops = &hbg_netdev_ops;
 	netdev->watchdog_timeo = 5 * HZ;
 
 	hbg_hw_set_mtu(priv, ETH_DATA_LEN);
Signature · 1 line
2.53.0
author maintainer
#2359 lore raw

PATCH 2338/2651 virtio-net: fix frag overflow in big packets receive

In reply to Greg Kroah-Hartman

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

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

From: Willem de Bruijn <[email protected]>

[ Upstream commit b0e4ea3a0cd42eccad9cc4153afcad555480b9e6 ]

In big packets mode with guest GSO, add_recvbuf_big() posts a chain of MAX_SKB_FRAGS + 1 pages. page_to_skb() copies only ETH_HLEN of the first page into the linear area and adds the rest of that page as a frag, then one frag per remaining page. A device that fills the entire buffer therefore causes MAX_SKB_FRAGS + 1 frags, writing one skb_frag_t past the end of skb_shinfo(skb)->frags[].

Post one page less. The buffer still fits a maximal GSO packet. A well behaved device does not trigger this, as GSO packets are at most 64KB.

Also check the frag count in page_to_skb() before adding any frag as defense in depth.

Fixes 9ab86bbcf8be ("virtio_net: Defer skb allocation in receive path Date: Wed, 13 Jan 2010 12:53:38 -0800")
---
 drivers/net/virtio_net.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
drivers/net/virtio_net.c +11 -1
index 4e8a792cec0e7..584bc05c577c7 100644
@@ -900,6 +900,15 @@ static struct sk_buff *page_to_skb(struct virtnet_info *vi,
 	}
 
 	BUG_ON(offset >= PAGE_SIZE);
+
+	/* The first frag starts at offset, each next frag is a full page. */
+	if (unlikely(DIV_ROUND_UP(offset + len, PAGE_SIZE) > MAX_SKB_FRAGS)) {
+		pr_debug("%s: rx error: len %u needs more than %d frags\n",
+			 vi->dev->name, len, MAX_SKB_FRAGS);
+		kfree_skb(skb);
+		return NULL;
+	}
+
 	while (len) {
 		unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
 		skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
@@ -6709,7 +6718,8 @@ static void virtnet_set_big_packets(struct virtnet_info *vi, const int mtu)
 	 */
 	if (mtu > ETH_DATA_LEN || guest_gso) {
 		vi->big_packets = true;
-		vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS : DIV_ROUND_UP(mtu, PAGE_SIZE);
+		vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS - 1 :
+							   DIV_ROUND_UP(mtu, PAGE_SIZE);
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#2360 lore raw

PATCH 2339/2651 net: lan969x: fix DSM calendar for empty taxis

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit a031ec9ff5a2e55867430e74e9b497fe844116ba ]

lan969x_dsm_calendar_calc() computes the DSM calendar schedule of one taxi. sparx5_config_dsm_calendar() calls it for each taxi, reusing the same sparx5_calendar_data.

Before this patch, the schedule is only cleared after the n_devs == 0 early return. For a taxi with no active ports, the function writes SPX5_DSM_CAL_EMPTY only to schedule[0] and leaves the remaining slots at whatever they held before. For the first taxi that is zero from kzalloc(), so sparx5_dsm_cal_len() returns a bogus length and sparx5_dsm_calendar_check() fails, which fails the probe:

Port 0: distance 20 above limit 0

A later empty taxi inherits the previous taxi's schedule instead, which passes the check, so only an empty taxi 0 triggers the failure.

Clear the full schedule up front on every path, and on the empty path place a single idle marker (SPX5_DSM_CAL_MAX_DEVS_PER_TAXI) in slot 0, so the update step sees a calendar length of one and programs one idle slot into the hardware, matching what sparx5_dsm_calendar_calc() does.

Reported by a customer whose DT enables none of the ports in a taxi. Reproduced on lan969x by disabling all taxi 0 ports in the DT.

Fixes 5d2ba3941016 ("net: lan969x: add function for calculating the DSM calendar")
---
 .../ethernet/microchip/sparx5/lan969x/lan969x_calendar.c  | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_calendar.c +4 -4
index e857640df185e..4442c0c1a957b 100644
@@ -82,6 +82,9 @@ int lan969x_dsm_calendar_calc(struct sparx5 *sparx5, u32 taxi,
 	struct lan969x_dsm_cal_dev_speed *speed;
 	int err;
 
+	for (u32 i = 0; i < SPX5_DSM_CAL_LEN; i++)
+		data->schedule[i] = SPX5_DSM_CAL_EMPTY;
+
 	/* Maximum bandwidth for this taxi */
 	taxi_bw = (128 * 1000000) / sparx5_clk_period(sparx5->coreclock);
 
@@ -125,7 +128,7 @@ int lan969x_dsm_calendar_calc(struct sparx5 *sparx5, u32 taxi,
 	}
 
 	if (n_devs == 0) {
-		data->schedule[0] = SPX5_DSM_CAL_EMPTY;
+		data->schedule[0] = SPX5_DSM_CAL_MAX_DEVS_PER_TAXI;
 		return 0;
 	}
 
@@ -167,9 +170,6 @@ int lan969x_dsm_calendar_calc(struct sparx5 *sparx5, u32 taxi,
 		return -EINVAL;
 	}
 
-	for (u32 i = 0; i < SPX5_DSM_CAL_LEN; i++)
-		data->schedule[i] = SPX5_DSM_CAL_EMPTY;
-
 	/* Place the remaining devices */
 	for (u32 i = 0; i < DSM_CAL_DEV_MAX; i++) {
 		speed = &dev_speeds[i];
Signature · 1 line
2.53.0
author maintainer
#2361 lore raw

PATCH 2340/2651 net: sparx5/lan969x: do not clobber the PSFP cycle timer update period

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit 5a3dcad8e101ddcd3a886907c8992df54472f749 ]

sparx5_psfp_init() enables the periodic stream gate cycle timer update, which keeps the cycle start time of each stream gate within one cycle time of the current time. SG_CT_CLKS sets the update period, in system clock cycles.

Before this patch, the update is enabled with a full register write of SG_CT_UPDATE_ENA only, which also sets SG_CT_CLKS to zero. That is below the documented minimum, the number of stream gates (1024 on sparx5 and 256 on lan969x).

Write both fields, and set the period to the recommended 10 us, computed from the core clock since it differs per target (6250 cycles at 625 MHz, 3280 at 328 MHz).

Found by an AI code review agent, and confirmed on lan969x and sparx5 by reading the register back as 0x80000000.

Fixes e116b19db202 ("net: microchip: sparx5: initialize PSFP")
---
 drivers/net/ethernet/microchip/sparx5/sparx5_psfp.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
drivers/net/ethernet/microchip/sparx5/sparx5_psfp.c +9 -1
index 83b37f95ee467..fa19a48f941d1 100644
@@ -322,6 +322,7 @@ void sparx5_psfp_init(struct sparx5 *sparx5)
 {
 	const struct sparx5_ops *ops = sparx5->data->ops;
 	const struct sparx5_sdlb_group *group;
+	u32 sg_ct_clks;
 	int i;
 
 	for (i = 0; i < sparx5->data->consts->n_lb_groups; i++) {
@@ -330,7 +331,14 @@ void sparx5_psfp_init(struct sparx5 *sparx5)
 				       group->min_burst, group->frame_size, i);
 	}
 
-	spx5_wr(ANA_AC_SG_CYCLETIME_UPDATE_PERIOD_SG_CT_UPDATE_ENA_SET(1),
+	/* Poll the stream gate cycle start times every 10 us. The core clock
+	 * period is in picoseconds.
+	 */
+	sg_ct_clks = 10 * NSEC_PER_USEC * PSEC_PER_NSEC /
+		     sparx5_clk_period(sparx5->coreclock);
+
+	spx5_wr(ANA_AC_SG_CYCLETIME_UPDATE_PERIOD_SG_CT_CLKS_SET(sg_ct_clks) |
+		ANA_AC_SG_CYCLETIME_UPDATE_PERIOD_SG_CT_UPDATE_ENA_SET(1),
 		sparx5, ANA_AC_SG_CYCLETIME_UPDATE_PERIOD);
 
 	spx5_rmw(ANA_L2_FWD_CFG_ISDX_LOOKUP_ENA_SET(1),
Signature · 1 line
2.53.0
author maintainer
#2362 lore raw

PATCH 2341/2651 net: lan969x: dont disable hardirqs in fdma tx clear

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit 9770818b8a92fb5fb77725bd5055f165eee3f52e ]

lan969x_fdma_tx_clear_buf() runs from the NAPI poll and frees the skbs of completed tx DCBs with napi_consume_skb(), under sparx5->tx_lock.

Before this patch, the lock is taken with spin_lock_irqsave(), so the skbs are freed with hardirqs disabled. RX skbs are marked for page_pool recycling, so when such an skb is forwarded back out and its tx completion frees it here, the free path reaches __page_pool_put_page(), which warns via lockdep_assert_no_hardirq().

Take tx_lock with a plain spin_lock(), as the only other tx_lock user, sparx5_port_xmit_impl(), already does. tx_clear_buf() is only called from softirq context, so disabling hardirqs is not needed.

Found with lockdep enabled (CONFIG_PROVE_LOCKING), which the assert depends on. Reproduced on lan969x by redirecting received frames out of another port with tc mirred.

---
 drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c +2 -3
index c7e0e58ff0f7b..053d125eda658 100644
@@ -54,10 +54,9 @@ static void lan969x_fdma_tx_clear_buf(struct sparx5 *sparx5, int weight)
 {
 	struct fdma *fdma = &sparx5->tx.fdma;
 	struct sparx5_tx_buf *db;
-	unsigned long flags;
 	int i;
 
-	spin_lock_irqsave(&sparx5->tx_lock, flags);
+	spin_lock(&sparx5->tx_lock);
 
 	for (i = 0; i < fdma->n_dcbs; ++i) {
 		db = &sparx5->tx.dbs[i];
@@ -83,7 +82,7 @@ static void lan969x_fdma_tx_clear_buf(struct sparx5 *sparx5, int weight)
 		db->used = false;
 	}
 
-	spin_unlock_irqrestore(&sparx5->tx_lock, flags);
+	spin_unlock(&sparx5->tx_lock);
 }
 
 static void lan969x_fdma_free_pages(struct sparx5_rx *rx)
Signature · 1 line
2.53.0
author maintainer
#2363 lore raw

PATCH 2342/2651 veth: schedule the peers NAPI after XDP_TX when only GRO is enabled

In reply to Greg Kroah-Hartman

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

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

From: Tianyi Gao <[email protected]>

[ Upstream commit f16b8c6a656e62bfa7bb6a3b876f9ccdaf53bd43 ]

veth_xdp_xmit() queues XDP_TX frames on the peer's ring if the peer has NAPI. A peer with GRO enabled and no XDP program also has NAPI.

veth_xdp_flush() then schedules the peer's NAPI, but only if the peer's xdp_prog is set, so for such a peer the frames are never processed. Nothing else schedules that NAPI by default.

Once the ring is full, every XDP_TX frame is dropped, and so are the skbs that veth_xmit() queues on the same ring.

Commit 0e672f306a28 ("veth: check for NAPI instead of xdp_prog before xmit of XDP frame") changed the check in veth_xdp_xmit() but not the one in veth_xdp_flush(). Make veth_xdp_flush() check the napi pointer instead of xdp_prog, as veth_xdp_xmit() does.

---
 drivers/net/veth.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/veth.c +1 -1
index 8e61f67dc37c1..e5ea979005d2a 100644
@@ -617,7 +617,7 @@ static void veth_xdp_flush(struct veth_rq *rq, struct veth_xdp_tx_bq *bq)
 	rcv_priv = netdev_priv(rcv);
 	rcv_rq = &rcv_priv->rq[veth_select_rxq(rcv)];
 	/* xdp_ring is initialized on receive side? */
-	if (unlikely(!rcu_access_pointer(rcv_rq->xdp_prog)))
+	if (unlikely(!rcu_access_pointer(rcv_rq->napi)))
 		goto out;
 
 	__veth_xdp_flush(rcv_rq);
Signature · 1 line
2.53.0
author maintainer
#2364 lore raw

PATCH 2343/2651 net: shrink the payload-only part of skb dataref to one bit

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 4957ea03bf2696f5da12c09144f48d040696ecc2 ]

skb_shinfo(skb)->dataref is split in two 16-bit halves: the lower one counts all references, the upper one the payload-only (nohdr) references.

__skb_clone() increments dataref without bound, and skb_cloned() only checks the low 16 bits. With 65,537 references the low half reads 1, the head looks private, and pskb_expand_head() (or skb_unclone(), skb_cow(), ...) frees it while clones still point to it.

An unprivileged user can reach this from a user and network namespace:
about 32,770 AF_PACKET sockets on lo bring dataref to 0x10001, then any pskb_expand_head() on the receive path (here a pull of a large IPv6 Hop-by-Hop header) frees the shared head:

BUG: KASAN: slab-use-after-free in _copy_to_iter+0x187/0x1330
Read of size 1590 at addr ff110001104a9002 by task dataref_wrap/87
 skb_copy_datagram_iter+0x60/0x190
 packet_recvmsg+0x1f5/0x12b0
 __sys_recvfrom+0x18d/0x290
Freed by task 87:
 kfree+0xf3/0x3b0
 pskb_expand_head+0x344/0xeb0
 __pskb_pull_tail+0xf9/0x1bf0
 ipv6_parse_hopopts+0x377/0x4f0
 ip6_rcv_core+0xc67/0x1620

The upper half never holds more than 1. It is only set by __skb_header_release(), with atomic_set() on an skb owning its head (TCP/SCTP output, and GRO which never sees cloned skbs). __skb_clone() clears nohdr, and __copy_skb_header() does not copy it.

Move SKB_DATAREF_SHIFT to 30, so that the reference count gets 30 bits, and dataref stays positive. Wrapping it would need 2^30 live clones of a single skb, which socket buffer limits and memory make unreachable.

This issue was found by Anthropic using Claude, and validated by Ada Logics.

---
 include/linux/skbuff.h | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
include/linux/skbuff.h +4 -4
index d6894f463bf43..707082f68f210 100644
@@ -633,9 +633,9 @@ struct skb_shared_info {
  *
  * Transport layers send out clones of payload skbs they hold for
  * retransmissions. To allow lower layers of the stack to prepend their headers
- * we split &skb_shared_info.dataref into two halves.
- * The lower 16 bits count the overall number of references.
- * The higher 16 bits indicate how many of the references are payload-only.
+ * we split &skb_shared_info.dataref into two parts.
+ * The lower 30 bits count the overall number of references.
+ * Bit 30 indicates whether one of the references is payload-only.
  * skb_header_cloned() checks if skb is allowed to add / write the headers.
  *
  * The creator of the skb (e.g. TCP) marks its skb as &sk_buff.nohdr
@@ -655,7 +655,7 @@ struct skb_shared_info {
  * Having multiple payload-only skbs with different lengths of hdr_len is not
  * possible. The payload-only skbs should never leave their owner.
  */
-#define SKB_DATAREF_SHIFT 16
+#define SKB_DATAREF_SHIFT 30
 #define SKB_DATAREF_MASK ((1 << SKB_DATAREF_SHIFT) - 1)
 
 
Signature · 1 line
2.53.0
author maintainer
#2365 lore raw

PATCH 2344/2651 net/mlx5e: Stop asserting for RTNL when closing channels

In reply to Greg Kroah-Hartman

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

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

From: Cosmin Ratiu <[email protected]>

[ Upstream commit e0a958ddfc89f2e1c43448cdaeb5b30e54e19448 ]

mlx5e_close_channels() has an ASSERT_RTNL() from the time when RTNL was required for closing channels.
But the driver has been switched to using the netdev lock a while back, and this fired from a flow which was forgotten during the conversion:

mlx5e_tx_timeout_work()
-> mlx5e_reporter_tx_timeout()
-> mlx5e_health_report()
-> mlx5e_tx_reporter_timeout_recover()
-> mlx5e_safe_reopen_channels()
-> mlx5e_safe_switch_params()
-> mlx5e_close_channels()

The RTNL is not acquired here, but the netdev lock is, and it is enough.

Rather than switching to netdev_assert_locked(), simply drop the assert. Upper layers (networking core, ethtool core) provide locking and lower layers (NAPI helpers) assert that the netdev lock is held.

---
 drivers/net/ethernet/mellanox/mlx5/core/en_main.c | 1 -
 1 file changed, 1 deletion(-)
drivers/net/ethernet/mellanox/mlx5/core/en_main.c +0 -1
index 4c6060d54fbed..38ce7d0a9001e 100644
@@ -3075,7 +3075,6 @@ void mlx5e_close_channels(struct mlx5e_channels *chs)
 {
 	int i;
 
-	ASSERT_RTNL();
 	if (chs->ptp) {
 		mlx5e_ptp_close(chs->ptp);
 		chs->ptp = NULL;
Signature · 1 line
2.53.0
author maintainer
#2366 lore raw

PATCH 2345/2651 tg3: Add Datto SIRIS 5 1U Server to restart AER quirk table

In reply to Greg Kroah-Hartman

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

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

From: Travis Howard <[email protected]>

[ Upstream commit a55eb6a622141352131aa6156bbd6ce5da79d9b5 ]

The Datto SIRIS 5 1U Server is a Dell OEMR XL R640 (Dell's OEM-ready variant of the PowerEdge R640) sold under Datto's identity. Its DMI strings report sys_vendor "datto" and product_name "SIRIS 5 1U Server", so it does not match the existing "PowerEdge R640" entry in tg3_restart_aer_quirk_table.

As on the PowerEdge R640, a system restart triggers a fatal PCIe AER on the BCM5720 during ACPI _PTS for S5, which the iDRAC logs as PCI1318 and which hangs the reboot. Power off is unaffected.

Clearing the same PCI_EXP_DEVCTL error-reporting bits on both BCM5720 functions from userspace immediately before restart allows the system to reboot normally, confirming the quirk applies to this platform.

---
 drivers/net/ethernet/broadcom/tg3.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/net/ethernet/broadcom/tg3.c +6 -0
index fd1c95f1111c5..e85f7e909a839 100644
@@ -18205,6 +18205,12 @@ static const struct dmi_system_id tg3_restart_snp_quirk_table[] = {
 			DMI_MATCH(DMI_PRODUCT_NAME, "PowerEdge R750"),
 		},
 	},
+	{
+		.matches = {
+			DMI_MATCH(DMI_SYS_VENDOR, "datto"),
+			DMI_MATCH(DMI_PRODUCT_NAME, "SIRIS 5 1U Server"),
+		},
+	},
 	{}
 };
 
Signature · 1 line
2.53.0
author maintainer
#2367 lore raw

PATCH 2346/2651 ata: libata-core: Ignore forced transfer modes the host does not support

In reply to Greg Kroah-Hartman

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

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

From: Rand Deeb <[email protected]>

[ Upstream commit ea5a5af9159cc89e8bcb7a95336e02c8b70aa3d2 ]

The libata.force parameter can force a transfer mode (pio0-6, mwdma0-4, udma0-7) for a port or device. ata_force_xfermask() applies it in ata_do_set_mode() right after ata_dev_xfermask() has limited the device masks to what the host supports. It replaces those masks with the forced mode without checking the host masks, so a mode the controller does not support is passed to the driver's ->set_piomode() or ->set_dmamode().

Several PATA drivers rely on the host masks to keep the mode number in range when indexing their timing tables. ata_piix, pata_efar, pata_it8213, pata_oldpiix, pata_radisys and pata_rdc declare ATA_PIO4 and ATA_MWDMA12_ONLY, index a five-entry PIO timing table with pio_mode - XFER_PIO_0, and index a three-entry needed_pio[] table with dma_mode - XFER_MW_DMA_0. Booting with libata.force=pio5, pio6, mwdma3 or mwdma4 makes them read past those tables, use the values read as further indices into the timing table, and write the result to the controller's timing registers.

Make ata_force_xfermask() skip, with a warning, a forced transfer mode that is not in the port's PIO, MWDMA or UDMA mask, and keep looking for an earlier matching libata.force entry, as it already does for entries that do not apply to the device. With libata.force=pio4,1.0:pio5 on a PIO4 host, device 1.0 now gets pio4 instead of pio5. Forcing a mode the host supports still works as before, including a mode that ata_dev_xfermask() removed for the device or cable.

Found by Linux Verification Center (linuxtesting.org) with SVACE.

Fixes 332673257056 ("libata: implement libata.force module parameter")
---
 drivers/ata/libata-core.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
drivers/ata/libata-core.c +12 -0
index 1fe222008abd2..30572ca510de9 100644
@@ -434,6 +434,7 @@ static void ata_force_link_limits(struct ata_link *link)
  */
 static void ata_force_xfermask(struct ata_device *dev)
 {
+	struct ata_port *ap = dev->link->ap;
 	int devno = dev->link->pmp + dev->devno;
 	int alt_devno = devno;
 	int i;
@@ -458,6 +459,17 @@ static void ata_force_xfermask(struct ata_device *dev)
 
 		ata_unpack_xfermask(fe->param.xfer_mask,
 				    &pio_mask, &mwdma_mask, &udma_mask);
+
+		/* Make sure that the port supports the specified xfer modes. */
+		if (!(pio_mask & ap->pio_mask) &&
+		    !(mwdma_mask & ap->mwdma_mask) &&
+		    !(udma_mask & ap->udma_mask)) {
+			ata_dev_warn(dev,
+				     "FORCE: ignoring unsupported xfer_mask %s\n",
+				     fe->param.name);
+			continue;
+		}
+
 		if (udma_mask)
 			dev->udma_mask = udma_mask;
 		else if (mwdma_mask) {
Signature · 1 line
2.53.0
author maintainer
#2368 lore raw

PATCH 2347/2651 gpiolib: Propagate emulated drive errors when setting arrays

In reply to Greg Kroah-Hartman

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

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

From: Baek Kyu, Kim <[email protected]>

[ Upstream commit 15665047024e30f9c2227563d03034061c99ac2c ]

gpiod_set_array_value_complex() ignores errors from the open-drain and open-source emulation helpers. If a direction change fails, GPIO_V2_LINE_SET_VALUES_IOCTL still reports success, including when updating a single line.

Return the first emulation error after freeing the temporary bitmaps. Keep updates already made to earlier lines and stop processing the remaining lines, as for errors from gpiochip_set_multiple().

Fixes 8ce258f62f90 ("gpiolib: make value setters have return values")

Signed-off-by:

---
 drivers/gpio/gpiolib.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/gpio/gpiolib.c +6 -2
index 9c05d36ccd74f..90731a547ed63 100644
@@ -3950,9 +3950,13 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep,
 			 * open drain and open source outputs are set individually
 			 */
 			if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
-				gpio_set_open_drain_value_commit(desc, value);
+				ret = gpio_set_open_drain_value_commit(desc, value);
+				if (ret)
+					goto cleanup_bitmap;
 			} else if (test_bit(GPIOD_FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
-				gpio_set_open_source_value_commit(desc, value);
+				ret = gpio_set_open_source_value_commit(desc, value);
+				if (ret)
+					goto cleanup_bitmap;
 			} else {
 				__set_bit(hwgpio, mask);
 				__assign_bit(hwgpio, bits, value);
Signature · 1 line
2.53.0
#2369 lore raw

Re: [PATCH 7.3 2347/2651] gpiolib: Propagate emulated drive errors when setting arrays

Quoted 13 lines · Greg Kroah-Hartman

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

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

From: Baek Kyu, Kim <[email protected]>

[ Upstream commit 15665047024e30f9c2227563d03034061c99ac2c ]

gpiod_set_array_value_complex() ignores errors from the open-drain and open-source emulation helpers. If a direction change fails, GPIO_V2_LINE_SET_VALUES_IOCTL still reports success, including when updating a single line.

Quoted 6 lines

Return the first emulation error after freeing the temporary bitmaps. Keep updates already made to earlier lines and stop processing the remaining lines, as for errors from gpiochip_set_multiple().

Fixes 8ce258f62f90 ("gpiolib: make value setters have return values")

Signed-off-by:

How much illegal is to have this without the author's proper S-O-B?

Quoted 27 lines
---
  drivers/gpio/gpiolib.c | 8 ++++++--
  1 file changed, 6 insertions(+), 2 deletions(-)
drivers/gpio/gpiolib.c +6 -2
index 9c05d36ccd74f..90731a547ed63 100644
@@ -3950,9 +3950,13 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep,
  			 * open drain and open source outputs are set individually
  			 */
  			if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
-				gpio_set_open_drain_value_commit(desc, value);
+				ret = gpio_set_open_drain_value_commit(desc, value);
+				if (ret)
+					goto cleanup_bitmap;
  			} else if (test_bit(GPIOD_FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
-				gpio_set_open_source_value_commit(desc, value);
+				ret = gpio_set_open_source_value_commit(desc, value);
+				if (ret)
+					goto cleanup_bitmap;
  			} else {
  				__set_bit(hwgpio, mask);
  				__assign_bit(hwgpio, bits, value);
Signature · 2 lines
js
suse labs
author maintainer
#2370 lore raw

Re: [PATCH 7.3 2347/2651] gpiolib: Propagate emulated drive errors when setting arrays

Quoted 14 lines · Jiri Slaby
Quoted 13 lines · Greg Kroah-Hartman

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

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

From: Baek Kyu, Kim <[email protected]>

[ Upstream commit 15665047024e30f9c2227563d03034061c99ac2c ]

gpiod_set_array_value_complex() ignores errors from the open-drain and open-source emulation helpers. If a direction change fails, GPIO_V2_LINE_SET_VALUES_IOCTL still reports success, including when updating a single line.

Quoted 8 lines
Quoted 6 lines

Return the first emulation error after freeing the temporary bitmaps. Keep updates already made to earlier lines and stop processing the remaining lines, as for errors from gpiochip_set_multiple().

Fixes 8ce258f62f90 ("gpiolib: make value setters have return values")

Signed-off-by:

How much illegal is to have this without the author's proper S-O-B?

Not good, but that's what the commit looks like in Linus's tree :(

author maintainer
#2371 lore raw

PATCH 2348/2651 tipc: fix use-after-free of broadcast reception link at node release

In reply to Greg Kroah-Hartman

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

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

From: Binbin Deng <[email protected]>

[ Upstream commit 473167593f42551ce6b00c05cee8cd20309d45ac ]

When the last reference to a tipc_node is dropped, the node itself is deferred to the RCU callback tipc_node_free(), but the nested broadcast reception link, n->bc_entry.link, is kfree()d synchronously in tipc_node_kref_release(), before call_rcu(), and the pointer is never cleared. Readers that obtained the node from node_list and then dereference bc_entry.link deep into the link (tipc_link_name() in tipc_nl_node_reset_link_stats(), bcl->name/stats in tipc_nl_add_bc_link() on the link dump path) therefore touch freed memory although the enclosing node stays alive for a full grace period. The sibling per-bearer links get "kfree + NULL" under the node write lock in tipc_node_clear_links(); the broadcast entry was missed.

The race is reachable through the node cleanup timer: once a peer has been unreachable for NODE_CLEANUP_AFTER (300 s), tipc_node_timeout() -> tipc_node_cleanup() unlinks the node under the write lock, and the final tipc_node_put() at the caller runs outside node_list_lock, so the kfree executes in timer softirq context, concurrently with genl dump/ reset walkers that hold only rcu_read_lock(). (A netlink "peer remove" cannot race those walkers itself: tipc_genl_family has no parallel_ops, so all doit/dumpit calls serialize on the global genl lock.)

Reproduced in a QEMU/KVM guest running v7.3.0 with KASAN and PREEMPT(full): 10 TIPC peer namespaces on veth bearers, bearer removal staggered so the 300 s node cleanup timers expire while other tasks loop link dumps with the broadcast filter and reset-link-stats lookups. KASAN hit within two cleanup cycles:

  BUG: KASAN: slab-use-after-free in strlen+0x85/0xa0
  Read of size 1 at addr ffff88800b54a004 by task poc_eth/371
   strlen+0x85/0xa0
   tipc_nl_add_bc_link+0x2f9/0xd40
   __tipc_nl_add_node_links+0x10c/0x140
   tipc_nl_node_dump_link+0x8d5/0xd50
  Freed by task 0:
   kfree+0x121/0x380
   tipc_node_timeout+0xa33/0xcf0
   run_timer_softirq+0x144/0x250
   sysvec_apic_timer_interrupt

with the freed object being the kmalloc-1k tipc_link allocated by tipc_link_bc_create() during peer discovery. The same defect fires in strcmp() called from tipc_nl_node_reset_link_stats().

Move the kfree of n->bc_entry.link into the tipc_node_free() RCU callback so the broadcast link lives exactly as long as the enclosing node. All readers are covered: the netlink walkers are inside rcu_read_lock(), and the packet reception path reaches the node via tipc_node_find(), whose kref defers kref_release itself.

Found during a static-analysis-assisted audit: candidate sites were surfaced by a Coccinelle rule, and the reader/writer paths were confirmed by LLM-assisted (GLM-5.3) code inspection.

Fixes d25a01257e42 ("tipc: fix crash during node removal")
Assisted-by GLM-5.3 coccinelle
---
 net/tipc/node.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/tipc/node.c +1 -1
index d7cbfa786c132..53b0993c2c233 100644
@@ -303,6 +303,7 @@ static void tipc_node_free(struct rcu_head *rp)
 #ifdef CONFIG_TIPC_CRYPTO
 	tipc_crypto_stop(&n->crypto_rx);
 #endif
+	kfree(n->bc_entry.link);
 	kfree(n);
 }
 
@@ -310,7 +311,6 @@ static void tipc_node_kref_release(struct kref *kref)
 {
 	struct tipc_node *n = container_of(kref, struct tipc_node, kref);
 
-	kfree(n->bc_entry.link);
 	call_rcu(&n->rcu, tipc_node_free);
 }
 
Signature · 1 line
2.53.0
author maintainer
#2372 lore raw

PATCH 2349/2651 ntfs: reject index blocks with a too small entries offset

In reply to Greg Kroah-Hartman

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

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

From: Hang Nan <[email protected]>

[ Upstream commit 20e14268ef410cbabff54a79405813a8b9ce8e89 ]

Index blocks read from the volume are checked for a plausible header, but nothing keeps a block from placing its entries closer to the header than ntfs_ib_alloc() does when it creates one. The allocation adds the update sequence array, one entry per 512-byte sector plus the terminator, to the index header and aligns the result to 8 bytes, so the first entry of a 4096-byte block starts at offset 40, while a corrupt block may declare 16.

ntfs_ib_copy_tail() then copies the entries that follow the median entry from the source block into a freshly allocated destination. The tail is sized as index_length minus entries_offset and the median entry, both from the source, while the destination only has allocated_size minus the canonical offset of room. With the values above the tail is 4040 bytes and the destination holds 4032, so the last 8 bytes are written past the end of the new allocation, with contents taken from the mounted image.

Reject such a block when it is read: entries_offset must not be smaller than the canonical offset for the block size. Derive it from block_size rather than from the block's own usa_count, which post_read_mst_fixup() treats as "not protected" when it does not match the block size, and use the same helper in ntfs_ib_alloc() so both stay in sync.

Fixes 0a8ac0c1fa0b ("ntfs: update directory operations")
---
 fs/ntfs/index.c | 22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)
fs/ntfs/index.c +20 -2
index 03de4c97c1620..9a23d0786959b 100644
@@ -489,6 +489,14 @@ static struct index_entry *ntfs_ie_dup_novcn(struct index_entry *ie)
 	return dup;
 }
 
+/* Offset of the first entry in an index block created by ntfs_ib_alloc(). */
+static u32 ntfs_ib_canonical_entries_offset(u32 block_size)
+{
+	u32 usa_count = block_size / NTFS_BLOCK_SIZE + 1;
+
+	return (sizeof(struct index_header) + usa_count * 2 + 7) & ~7;
+}
+
 /*
  * Check the consistency of an index block
  *
@@ -548,6 +556,16 @@ int ntfs_index_block_inconsistent(struct ntfs_volume *vol,
 					   offsetof(struct index_block, index),
 					   inum))
 		return -EIO;
+
+	if (le32_to_cpu(ib->index.entries_offset) <
+	    ntfs_ib_canonical_entries_offset(block_size)) {
+		ntfs_error(sb,
+			   "Index block: entries offset %u is below the minimum for a %u-byte block: vcn %lld inode %llu\n",
+			   le32_to_cpu(ib->index.entries_offset), block_size,
+			   vcn, inum);
+		return -EIO;
+	}
+
 	if (ntfs_index_entries_inconsistent(vol, &ib->index, cr, inum))
 		return -EIO;
 	return 0;
@@ -960,8 +978,8 @@ static struct index_block *ntfs_ib_alloc(s64 ib_vcn, u32 ib_size,
 	*(__le16 *)((char *)ib + le16_to_cpu(ib->usa_ofs)) = cpu_to_le16(1);
 	ib->lsn = 0;
 	ib->index_block_vcn = cpu_to_le64(ib_vcn);
-	ib->index.entries_offset = cpu_to_le32((ih_size +
-				le16_to_cpu(ib->usa_count) * 2 + 7) & ~7);
+	ib->index.entries_offset =
+		cpu_to_le32(ntfs_ib_canonical_entries_offset(ib_size));
 	ib->index.index_length = 0;
 	ib->index.allocated_size = cpu_to_le32(ib_size -
 			(sizeof(struct index_block) - ih_size));
Signature · 1 line
2.53.0
author maintainer
#2373 lore raw

PATCH 2350/2651 ntfs: fix u16 truncation of the update sequence array count check

In reply to Greg Kroah-Hartman

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

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

From: Zhan Xusheng <[email protected]>

[ Upstream commit b713b69cf79ef52b1737a1a6c09df2522ff875af ]

ntfs_check_restart_page_header() bounds the on-disk system page size by recomputing the update sequence array count from it:

	u16 ra_ofs, usa_count, usa_ofs, usa_end = 0;
	...
	usa_count = 1 + (logfile_system_page_size >> NTFS_BLOCK_SIZE_BITS);
	if (usa_count != le16_to_cpu(rp->usa_count))
		return false;

The right hand side is computed in u32 but stored in a u16, so the count wraps once the system page size reaches 0x2000000. An image claiming any larger power of two passes the check by also claiming usa_count == 1.

Nothing else limits the value, so ntfs_check_and_load_restart_page() goes on to kvzalloc() up to 2 GiB for the restart page and copy that many bytes a page at a time. The size is only rejected afterwards, by the (size >> NTFS_BLOCK_SIZE_BITS) != usa_count test in post_read_mst_fixup().

Compute the count in a u32 so the existing check rejects an over-large system page size instead of being defeated by the truncation. This adds no new limit: the array holds one u16 per protected sector plus the update sequence number and must end within the first sector, which caps usa_count at 240 and the system page size at 64 KiB.

Widen ra_ofs and usa_ofs as well, as ntfs_check_restart_area() already
does: both are loaded from __le16 on-disk fields and every comparison is against a non-negative value, so no result changes.

Fixes 1e9ea7e04472 ("Revert "fs: Remove NTFS classic"")
---
 fs/ntfs/logfile.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ntfs/logfile.c +1 -1
index ce38ce87f8fc8..2f27ae7a3927f 100644
@@ -27,7 +27,7 @@ static bool ntfs_check_restart_page_header(struct inode *vi,
 		struct restart_page_header *rp, s64 pos)
 {
 	u32 logfile_system_page_size, logfile_log_page_size;
-	u16 ra_ofs, usa_count, usa_ofs, usa_end = 0;
+	u32 ra_ofs, usa_count, usa_ofs, usa_end = 0;
 	bool have_usa = true;
 
 	ntfs_debug("Entering.");
Signature · 1 line
2.53.0
author maintainer
#2374 lore raw

PATCH 2351/2651 ASoC: wm8994: follow AIF clock source changes in MCLK gating

In reply to Greg Kroah-Hartman

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

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

From: Marek Szyprowski <[email protected]>

[ Upstream commit 8731e33a3b98ea1ccade059b3a1ce06b7dd66b17 ]

The AIF clock source can be changed by configure_aif_clock() while the AIF clock is running, for example the Midas machine driver switches AIF1 between MCLK2 and FLL1 while AIF1CLK is kept enabled for jack detection. aif_mclk_set() only enables the MCLK selected at the time the AIF clock is turned on, so an MCLK selected later this way is never enabled, and the codec may run from a stopped clock.

Track whether the AIF clock is running and, if so, enable the newly selected MCLK in configure_aif_clock() before switching to it, then release the previously enabled one.

Fixes 001b83d395ab ("ASoC: wm8994: Add support for MCLKn clock gating")
---
 sound/soc/codecs/wm8994.c | 27 +++++++++++++++++++++++++++
 sound/soc/codecs/wm8994.h |  1 +
 2 files changed, 28 insertions(+)
sound/soc/codecs/wm8994.c +27 -0
index dd6a9a3c73610..5d27cefd9d543 100644
@@ -163,9 +163,12 @@ static void wm8958_micd_set_rate(struct snd_soc_component *component)
 static int configure_aif_clock(struct snd_soc_component *component, int aif)
 {
 	struct wm8994_priv *wm8994 = snd_soc_component_get_drvdata(component);
+	struct clk *mclk = NULL;
+	bool switch_mclk;
 	int rate;
 	int reg1 = 0;
 	int offset;
+	int ret;
 
 	if (aif)
 		offset = 4;
@@ -174,11 +177,13 @@ static int configure_aif_clock(struct snd_soc_component *component, int aif)
 
 	switch (wm8994->sysclk[aif]) {
 	case WM8994_SYSCLK_MCLK1:
+		mclk = wm8994->mclk[WM8994_MCLK1].clk;
 		rate = wm8994->mclk_rate[0];
 		break;
 
 	case WM8994_SYSCLK_MCLK2:
 		reg1 |= 0x8;
+		mclk = wm8994->mclk[WM8994_MCLK2].clk;
 		rate = wm8994->mclk_rate[1];
 		break;
 
@@ -196,6 +201,20 @@ static int configure_aif_clock(struct snd_soc_component *component, int aif)
 		return -EINVAL;
 	}
 
+	/*
+	 * If the AIF clock is running, enable the new MCLK before switching
+	 * to it and release the previous one afterwards.
+	 */
+	switch_mclk = wm8994->aif_clk_on[aif] && mclk != wm8994->aif_mclk[aif];
+	if (switch_mclk) {
+		ret = clk_prepare_enable(mclk);
+		if (ret < 0) {
+			dev_err(component->dev,
+				"Failed to enable MCLK for AIF%d\n", aif + 1);
+			return ret;
+		}
+	}
+
 	if (rate >= 13500000) {
 		rate /= 2;
 		reg1 |= WM8994_AIF1CLK_DIV;
@@ -210,6 +229,11 @@ static int configure_aif_clock(struct snd_soc_component *component, int aif)
 			    WM8994_AIF1CLK_SRC_MASK | WM8994_AIF1CLK_DIV,
 			    reg1);
 
+	if (switch_mclk) {
+		clk_disable_unprepare(wm8994->aif_mclk[aif]);
+		wm8994->aif_mclk[aif] = mclk;
+	}
+
 	return 0;
 }
 
@@ -1067,6 +1091,7 @@ static int aif_mclk_set(struct snd_soc_component *component, int aif, bool enabl
 	if (!enable) {
 		clk_disable_unprepare(wm8994->aif_mclk[aif]);
 		wm8994->aif_mclk[aif] = NULL;
+		wm8994->aif_clk_on[aif] = false;
 		return 0;
 	}
 
@@ -1086,6 +1111,7 @@ static int aif_mclk_set(struct snd_soc_component *component, int aif, bool enabl
 		clk_idx = WM8994_MCLK2;
 		break;
 	default:
+		wm8994->aif_clk_on[aif] = true;
 		return 0;
 	}
 
@@ -1096,6 +1122,7 @@ static int aif_mclk_set(struct snd_soc_component *component, int aif, bool enabl
 		return ret;
 	}
 	wm8994->aif_mclk[aif] = wm8994->mclk[clk_idx].clk;
+	wm8994->aif_clk_on[aif] = true;
 
 	return 0;
 }
sound/soc/codecs/wm8994.h +1 -0
index 5b22cfab317e1..e7df0a1a2314c 100644
@@ -82,6 +82,7 @@ struct wm8994_priv {
 	struct wm8994 *wm8994;
 	struct clk_bulk_data mclk[WM8994_NUM_MCLK];
 	struct clk *aif_mclk[2];
+	bool aif_clk_on[2];
 	int sysclk[2];
 	int sysclk_rate[2];
 	int mclk_rate[2];
Signature · 1 line
2.53.0
author maintainer
#2375 lore raw

PATCH 2352/2651 proc/kcore: advance the vmalloc retry by the last copy, not the total

In reply to Greg Kroah-Hartman

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

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

From: Nickolai Zeldovich <[email protected]>

[ Upstream commit 88c3f9d6145204cfd88e5d9cbc9463ffd892e10a ]

A readv() or preadv() of /proc/kcore fails with EFAULT, although every byte of the destination is writable, when the page of a later iovec is not present at the moment the copy of a KCORE_VMALLOC chunk is retried:
swapped out, migrated by compaction or NUMA balancing, write-protected by KSM, or unmapped by MADV_DONTNEED from another thread. Only root can read /proc/kcore, and the read must use more than one iovec. On an x86_64 defconfig kernel (v7.3-rc7) a preadv() of one vmalloc page into two 2 KiB iovecs on separate pages, with a second thread repeatedly unmapping the second page, failed 77701 of 200000 calls with EFAULT; with the fix all 200000 succeed. Affected since v6.4.

read_kcore_iter() copies a KCORE_VMALLOC chunk with vread_iter(), which writes to the user buffer with page faults disabled and stops at the first iovec whose page is absent, after the earlier iovecs were written; the loop then faults the rest of the buffer in and calls vread_iter() again for what is left. It keeps the running total in read and advances the source address and the remaining length by that total:

	read += vread_iter(iter, src, left);
	if (read == tsz)
		break;
	src += read;
	left -= read;

In the reproducer the first call copies the 2048 bytes of the first iovec and stops at the second: read is 2048, and src and left move by 2048, which is right. The page that fault_in_iov_iter_writeable() then faults in is unmapped again before the second call, which copies 0
bytes: read is still 2048, but src moves by another 2048 to the end of the chunk and left drops to 0. The third call has nothing to copy, src moves by 2048 once more, left wraps around, and fault_in_iov_iter_writeable() fails on that length, so the read returns -EFAULT. When both short copies are non-zero (three or more iovecs) the extra call also copies bytes from the wrong offset of the page into the buffer before the failure. A single iovec is not affected: its nofault copy is all or nothing, so a short copy is always empty and the advance by the total is still the advance by the last copy.

Keep the return value of each vread_iter() call and advance src and left by that; read stays the running total compared with tsz.

Found while formally verifying vread_iter() against the kernel binary.

---
 fs/proc/kcore.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
fs/proc/kcore.c +5 -3
index 390547b992acd..3264c99bd68ac 100644
@@ -531,12 +531,14 @@ static ssize_t read_kcore_iter(struct kiocb *iocb, struct iov_iter *iter)
 			 * again until we are done.
 			 */
 			while (true) {
-				read += vread_iter(iter, src, left);
+				size_t n = vread_iter(iter, src, left);
+
+				read += n;
 				if (read == tsz)
 					break;
 
-				src += read;
-				left -= read;
+				src += n;
+				left -= n;
 
 				if (fault_in_iov_iter_writeable(iter, left)) {
 					ret = -EFAULT;
Signature · 1 line
2.53.0
author maintainer
#2376 lore raw

PATCH 2353/2651 eventpoll: propagate wakeup source creation failure in ep_modify()

In reply to Greg Kroah-Hartman

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

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

From: Tianyi Chen <[email protected]>

[ Upstream commit 9f2b8f4a452db79741c06e6ea91448347f4a975c ]

When EPOLL_CTL_MOD adds EPOLLWAKEUP, ep_modify() ignores the return value of ep_create_wakeup_source(). If allocation fails, it returns success with EPOLLWAKEUP set but no per-item wakeup source, so the requested suspend protection is missing.

This can happen without fault injection on SELinux systems: creating the wakeup source's sysfs nodes can require GFP_KERNEL_ACCOUNT allocations for security.selinux xattrs, which can fail when the caller's memory cgroup is over its limit.

Create the wakeup source before updating the event mask and data, and return the error if creation fails. Leave any newly created per-epoll source in place until ep_free(), as ep_insert() does on failure.

Fixes 4d7e30d98939 ("epoll: Add a flag, EPOLLWAKEUP, to prevent suspend while epoll events are ready")
---
 fs/eventpoll.c | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)
fs/eventpoll.c +13 -5
index e0c4bf88a8383..872396a0ad64a 100644
@@ -1982,11 +1982,22 @@ static int ep_modify(struct eventpoll *ep, struct epitem *epi,
 {
 	int pwake = 0;
 	poll_table pt;
+	int error;
 
 	lockdep_assert_irqs_enabled();
 
 	init_poll_funcptr(&pt, NULL);
 
+	/*
+	 * Create the wakeup source before committing the new event mask.
+	 * Leave the old mask and data unchanged if allocation fails.
+	 */
+	if ((event->events & EPOLLWAKEUP) && !ep_has_wakeup_source(epi)) {
+		error = ep_create_wakeup_source(epi);
+		if (error)
+			return error;
+	}
+
 	/*
 	 * Set the new event interest mask before calling f_op->poll();
 	 * otherwise we might miss an event that happens between the
@@ -1994,12 +2005,9 @@ static int ep_modify(struct eventpoll *ep, struct epitem *epi,
 	 */
 	epi->event.events = event->events; /* need barrier below */
 	epi->event.data = event->data; /* protected by mtx */
-	if (epi->event.events & EPOLLWAKEUP) {
-		if (!ep_has_wakeup_source(epi))
-			ep_create_wakeup_source(epi);
-	} else if (ep_has_wakeup_source(epi)) {
+	if (!(epi->event.events & EPOLLWAKEUP) &&
+	    ep_has_wakeup_source(epi))
 		ep_destroy_wakeup_source(epi);
-	}
 
 	/*
 	 * The following barrier has two effects:
Signature · 1 line
2.53.0
author maintainer
#2377 lore raw

PATCH 2354/2651 nsfs: check the trailing bytes of a file handle in bytes, not words

In reply to Greg Kroah-Hartman

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

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

From: Nickolai Zeldovich <[email protected]>

[ Upstream commit ad0312e1decd40d18e0e75de96c9c52013ec05be ]

open_by_handle_at(2) gets the wrong answer for a namespace file handle longer than struct nsfs_file_handle: a 16-byte handle padded with zeros to 48 bytes or more, which is what the comment above the check promises to accept, is refused with -ESTALE, while a 20-byte handle whose extra word is garbage is accepted. Reproduced on v7.0 and on mainline with the handle of /proc/self/ns/net from name_to_handle_at(AT_SYMLINK_FOLLOW); no privilege is needed, as nsfs_fh_to_dentry() admits the caller's own namespaces. Since v6.18.

nsfs_fh_to_dentry() receives fh_len in 32-bit words, like every fh_to_dentry(), and NSFS_FID_SIZE_U32_LATEST is the struct size in words (4). The check that the bytes past the struct are zero adds that word count to a byte pointer and passes the word difference to memchr_inv() as a byte count: it inspects bytes 4 .. fh_len - 1 of the handle instead of bytes 16 .. 4 * fh_len - 1. Up to a 44-byte handle that range lies inside ns_id, ns_type and ns_inum, so the outcome depends on the values of those fields (a padded net namespace handle passes because the upper bytes of its ns_id and ns_type are zero) and the real trailing bytes are never looked at; from 48 bytes on the range always covers a non-zero field byte and every padded handle is refused.

Start NSFS_FILE_HANDLE_SIZE_LATEST bytes into the handle and check (fh_len - NSFS_FID_SIZE_U32_LATEST) * sizeof(u32) bytes.

Tested with a program that encodes /proc/self/ns/net and opens the handle with handle_bytes 16, 20, 36, 48 and 128 (zero padding), and 20 and 48 with a non-zero last byte. Before: 48 and 128 refused, the 20-byte garbage handle accepted; after: every padded handle opens, both garbage handles are refused.

---
 fs/nsfs.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/nsfs.c +2 -2
index c3b6ae76594a8..0ef4e1455b7a0 100644
@@ -529,8 +529,8 @@ static struct dentry *nsfs_fh_to_dentry(struct super_block *sb, struct fid *fh,
 
 	/* Check that any trailing bytes are zero. */
 	if ((fh_len > NSFS_FID_SIZE_U32_LATEST) &&
-	    memchr_inv((void *)fid + NSFS_FID_SIZE_U32_LATEST, 0,
-		       fh_len - NSFS_FID_SIZE_U32_LATEST))
+	    memchr_inv((void *)fid + NSFS_FILE_HANDLE_SIZE_LATEST, 0,
+		       (fh_len - NSFS_FID_SIZE_U32_LATEST) * sizeof(u32)))
 		return NULL;
 
 	switch (fh_type) {
Signature · 1 line
2.53.0
author maintainer
#2378 lore raw

PATCH 2355/2651 netfs: Restore selective debug mask handling

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

The netfs debug macros test only whether netfs_debug is nonzero. Consequently, selecting one debug point enables every entry, exit and general debug message.

Documentation/filesystems/caching/fscache.rst and the NETFS_DEBUG Kconfig help still describe /sys/module/netfs/parameters/debug as a bitmask of per-stream function entry, exit and general debugging points, and the fscache_*.c files still define FSCACHE_DEBUG_LEVEL, but nothing has decoded either since the mask handling was dropped when FS-Cache was folded into netfs.

Restore the per-level and per-point mask decoding. Files that do not define FSCACHE_DEBUG_LEVEL, which includes the netfs core, fall under the cache management stream, the same default the FS-Cache macros had.

---
 fs/netfs/internal.h | 32 +++++++++++++++++++++++++++++---
 1 file changed, 29 insertions(+), 3 deletions(-)
fs/netfs/internal.h +29 -3
index 786af76da98c2..947dbf4c538dd 100644
@@ -473,6 +473,32 @@ void fscache_create_volume(struct fscache_volume *volume, bool wait);
 #define kleave(FMT, ...) dbgprintk("<== %s()"FMT"", __func__, ##__VA_ARGS__)
 #define kdebug(FMT, ...) dbgprintk(FMT, ##__VA_ARGS__)
 
+#define FSCACHE_DEBUG_CACHE	0
+#define FSCACHE_DEBUG_COOKIE	1
+#define FSCACHE_DEBUG_OBJECT	2
+#define FSCACHE_DEBUG_OPERATION	3
+
+#define FSCACHE_POINT_ENTER	1
+#define FSCACHE_POINT_LEAVE	2
+#define FSCACHE_POINT_DEBUG	4
+
+#ifndef FSCACHE_DEBUG_LEVEL
+#define FSCACHE_DEBUG_LEVEL CACHE
+#endif
+
+/*
+ * Determine whether a particular optional debugging point should be logged.
+ * Three levels of indirection are needed to expand FSCACHE_DEBUG_LEVEL before
+ * joining it with its prefix.
+ */
+#define ____do_kdebug(LEVEL, POINT) \
+	unlikely(netfs_debug & \
+		 (FSCACHE_POINT_##POINT << (FSCACHE_DEBUG_ ## LEVEL * 3)))
+#define ___do_kdebug(LEVEL, POINT) \
+	____do_kdebug(LEVEL, POINT)
+#define __do_kdebug(POINT) \
+	___do_kdebug(FSCACHE_DEBUG_LEVEL, POINT)
+
 #ifdef __KDEBUG
 #define _enter(FMT, ...) kenter(FMT, ##__VA_ARGS__)
 #define _leave(FMT, ...) kleave(FMT, ##__VA_ARGS__)
@@ -481,19 +507,19 @@ void fscache_create_volume(struct fscache_volume *volume, bool wait);
 #elif defined(CONFIG_NETFS_DEBUG)
 #define _enter(FMT, ...)			\
 do {						\
-	if (netfs_debug)			\
+	if (__do_kdebug(ENTER))			\
 		kenter(FMT, ##__VA_ARGS__);	\
 } while (0)
 
 #define _leave(FMT, ...)			\
 do {						\
-	if (netfs_debug)			\
+	if (__do_kdebug(LEAVE))			\
 		kleave(FMT, ##__VA_ARGS__);	\
 } while (0)
 
 #define _debug(FMT, ...)			\
 do {						\
-	if (netfs_debug)			\
+	if (__do_kdebug(DEBUG))			\
 		kdebug(FMT, ##__VA_ARGS__);	\
 } while (0)
 
Signature · 1 line
2.53.0
author maintainer
#2379 lore raw

PATCH 2356/2651 super: convert to plain hashtable

In reply to Greg Kroah-Hartman

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

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

From: Christian Brauner <[email protected]>

[ Upstream commit c84de57efe88c9c513cfbc3746361502db0978e2 ]

Convert the rhltable to a plain hashtable under a spinlock. The walks keep their place with a cursor entry in the chain. A claim is unhashed the moment it's dropped and a walk that finds a superblock that isn't born yet waits for it to be born or to die and looks again. Since hashing can't fail anymore the entry for the superblock's own s_dev is embedded in struct super_block and the preallocation in alloc_super() goes away. This all simplifies things quite a lot.

It also fixes a btrfs bug where fs_bdev_freeze() ended up freezing a btrfs filesystem through a stale member that open_ctree() had already released while the freeze was waiting for SB_BORN. The resume doesn't find a holder for that device anymore so the filesystem stays frozen for good.

The walks return superblocks instead of table entries now and user_get_super() hands out the passive reference the walk took.

Reproducer, a three device btrfs with a stale copy of a removed member. dm-delay under the remaining members stretches the window between btrfs_open_devices() and btrfs_free_extra_devids():

  truncate -s 1G a1 a2 b
  A1=$(losetup -f --show a1); A2=$(losetup -f --show a2); B=$(losetup -f --show b)
  mkfs.btrfs -f -d single -m single $A1 $A2 $B
  cp b b.old
  mount $A1 /mnt && btrfs device remove 3 /mnt && umount /mnt
  OLD=$(losetup -f --show b.old)
  dmsetup create d1 --table "0 $(blockdev --getsz $A1) delay $A1 0 200"
  dmsetup create d2 --table "0 $(blockdev --getsz $A2) delay $A2 0 200"
  dmsetup create old --table "0 $(blockdev --getsz $OLD) linear $OLD 0"
  mount -o device=/dev/mapper/d2,device=/dev/mapper/old /dev/mapper/d1 /mnt &
  sleep 1; dmsetup suspend old; wait
  dmsetup resume old
  touch /mnt/foo     # hangs until fsfreeze -u /mnt

That left btrfs frozen in 5 of 5 rounds with the same tables issued through raw dm ioctls. The -o degraded variant needs the mount held between the insertion and the bd_fsfreeze_count check in fs_bdev_register() with a kprobe.

Fixes cdb5146f8d5f ("fs: look up superblocks via the device table in fs_holder_ops")
---
 block/bdev.c                   |   2 +-
 fs/internal.h                  |   1 -
 fs/namespace.c                 |   2 -
 fs/super.c                     | 336 ++++++++++++++-------------------
 include/linux/fs/super_types.h |  11 +-
 5 files changed, 147 insertions(+), 205 deletions(-)
block/bdev.c +1 -1
index fac74319e9fba..5efb259ab3a7f 100644
@@ -1283,7 +1283,7 @@ int lookup_bdev(const char *pathname, dev_t *dev)
 	 * registers major 0.  Fake block device inodes (e.g. fuse with
 	 * rootmode=S_IFBLK) can expose i_rdev == 0, and letting that
 	 * propagate would confuse superblock lookup and trigger warnings
-	 * in the device-to-superblock table (super_dev_register).
+	 * in the device-to-superblock table (sget_fc).
 	 */
 	error = -ENODEV;
 	if (!inode->i_rdev)
fs/internal.h +0 -1
index c658c8a5ebd56..67aa0444351b1 100644
@@ -137,7 +137,6 @@ extern int reconfigure_super(struct fs_context *);
 extern bool super_trylock_shared(struct super_block *sb);
 struct super_block *user_get_super(dev_t, bool excl);
 void put_super(struct super_block *sb);
-void __init super_dev_init(void);
 extern bool mount_capable(struct fs_context *);
 
 /*
fs/namespace.c +0 -2
index cf627543572b3..48b90ffd6b1a6 100644
@@ -6486,8 +6486,6 @@ void __init mnt_init(void)
 				HASH_ZERO,
 				&mp_hash_shift, &mp_hash_mask, 0, 0);
 
-	super_dev_init();
-
 	kernfs_init();
 
 	err = sysfs_init();
fs/super.c +137 -199

518 lines not on this page · raw message

include/linux/fs/super_types.h +9 -2
index ecd96aeb1cee7..72f4288e16c52 100644
@@ -30,7 +30,6 @@ struct mount;
 struct mtd_info;
 struct quotactl_ops;
 struct shrinker;
-struct super_dev;
 struct unicode_map;
 struct user_namespace;
 struct workqueue_struct;
@@ -132,10 +131,18 @@ struct super_operations {
 	void (*report_error)(const struct fserror_event *event);
 };
 
+/* A superblock's claim on a device, see fs/super.c. */
+struct super_dev {
+	struct hlist_node			sd_hash;
+	struct super_block			*sd_sb;
+	dev_t					sd_dev;
+	unsigned int				sd_claims;
+};
+
 struct super_block {
 	struct list_head			s_list;		/* Keep this first */
 	dev_t					s_dev;		/* search index; _not_ kdev_t */
-	struct super_dev			*s_super_dev;	/* sget_fc()'s device table claim */
+	struct super_dev			s_super_dev;	/* claim on s_dev */
 	unsigned char				s_blocksize_bits;
 	unsigned long				s_blocksize;
 	loff_t					s_maxbytes;	/* Max file size */
Signature · 1 line
2.53.0
author maintainer
#2380 lore raw

PATCH 2357/2651 fs: fix ramfs_fs_info leak when rootfs is unmounted

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

When rootfs is a ramfs, for example with root= on the command line, its superblock carries a struct ramfs_fs_info from ramfs_init_fs_context(). ramfs_kill_sb() frees it, but rootfs_fs_type uses kill_anon_super().

Before commit 576ee5dfd459 ("fs: add immutable rootfs") rootfs could not be unmounted. Since then prepare_namespace() pivots into the real root and unmounts rootfs. When the superblock is destroyed, the structure is leaked. kmemleak on an SH7785LCR board:

unreferenced object 0x8100a720 (size 32):

    comm "swapper/0", pid 0, jiffies 4294892299
    backtrace (crc c8bfd23b):
      ...
      ramfs_init_fs_context+0x16/0x48
      rootfs_init_fs_context+0x16/0x2c
      alloc_fs_context+0x98/0x114
      fs_context_for_mount+0x16/0x24
      ...

Call ramfs_kill_sb() when rootfs is a ramfs. tmpfs frees its own data in put_super and keeps kill_anon_super().

---
 init/do_mounts.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
init/do_mounts.c +9 -1
index 95e0b3a0f711b..b088021b1546d 100644
@@ -503,10 +503,18 @@ static int rootfs_init_fs_context(struct fs_context *fc)
 	return ramfs_init_fs_context(fc);
 }
 
+static void rootfs_kill_sb(struct super_block *sb)
+{
+	if (IS_ENABLED(CONFIG_TMPFS) && is_tmpfs)
+		kill_anon_super(sb);
+	else
+		ramfs_kill_sb(sb);
+}
+
 struct file_system_type rootfs_fs_type = {
 	.name		= "rootfs",
 	.init_fs_context = rootfs_init_fs_context,
-	.kill_sb	= kill_anon_super,
+	.kill_sb	= rootfs_kill_sb,
 };
 
 void __init init_rootfs(void)
Signature · 1 line
2.53.0
author maintainer
#2381 lore raw

PATCH 2358/2651 signal: skip blocked signals in dequeue_synchronous_signal()

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit 4bd3a0e8e53decd614853fbb487a268f139f679e ]

dequeue_synchronous_signal() checks whether an unblocked synchronous signal is pending, but its queue scan can select a different blocked entry with a positive si_code. This can deliver a signal while it is still blocked.

Check the blocked mask for each queued entry. Forced faults are unblocked when necessary by force_sig_info_to_task(), and the existing pending bookkeeping is unchanged.

---
 kernel/signal.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
kernel/signal.c +3 -2
index 6e3950939acbb..f13be2963332c 100644
@@ -684,12 +684,13 @@ static int dequeue_synchronous_signal(kernel_siginfo_t *info)
 		return 0;
 
 	/*
-	 * Return the first synchronous signal in the queue.
+	 * Return the first unblocked synchronous signal in the queue.
 	 */
 	list_for_each_entry(q, &pending->list, list) {
 		/* Synchronous signals have a positive si_code */
 		if ((q->info.si_code > SI_USER) &&
-		    (sigmask(q->info.si_signo) & SYNCHRONOUS_MASK)) {
+		    (sigmask(q->info.si_signo) & SYNCHRONOUS_MASK) &&
+		    !sigismember(&tsk->blocked, q->info.si_signo)) {
 			sync = q;
 			goto next;
 		}
Signature · 1 line
2.53.0
author maintainer
#2382 lore raw

PATCH 2359/2651 nsproxy: Fix cred leak in the error path of prepare_nsset()

In reply to Greg Kroah-Hartman

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

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

From: Nickolai Zeldovich <[email protected]>

[ Upstream commit e08601d3a7b2236f4915497dca353dcf117bab5c ]

A task that calls setns() with CLONE_NEWUSER together with CLONE_NEWNS and at least one more namespace flag leaks a struct cred (and the user_namespace, ucounts and group_info references it holds) whenever the call fails at the fs_struct copy. On a kernel with CONFIG_USER_NS the leak is one cred per failed setns(); under memory pressure, or driven by a fault-injecting attacker, it accumulates and pins user namespaces that can then never be freed.

prepare_nsset() sets nsset->flags only on the success path:

	if (flags & CLONE_NEWUSER)
		nsset->cred = prepare_creds();
	...
	} else if (flags & CLONE_NEWNS) {
		nsset->fs = copy_fs_struct(me->fs);
		if (!nsset->fs)
			goto out;	/* flags still 0 here */
	}
	nsset->flags = flags;
	return 0;
out:
	put_nsset(nsset);

put_nsset() decides what to release from nsset->flags:

	if (flags & CLONE_NEWUSER)
		put_cred(nsset_cred(nsset));

On the copy_fs_struct() failure arm prepare_creds() has already allocated the cred, but nsset->flags is still the zero from the caller's "struct nsset nsset = {}", so put_nsset() does not see CLONE_NEWUSER and never drops it. The caller (__do_sys_setns) returns the error without touching nsset, so the cred is lost.

Set nsset->flags at the start of prepare_nsset(), before anything can fail, so every error exit through put_nsset() releases what was taken. commit_nsset(), which clears nsset->cred on success, is unaffected.

Reproduced on x86_64 under QEMU with failslab aimed at the fs_struct cache and kmemleak enabled: 500 calls of
setns(pidfd, CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWUTS) each fail with -ENOMEM and leave 851 unreferenced cred objects allocated from prepare_creds() via setns() before the fix, and none after (the program is in the notes below).

Found by formal verification of kernel/nsproxy.c.

---
 kernel/nsproxy.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/nsproxy.c +1 -1
index 3fb1595a4a593..028019f3e387c 100644
@@ -355,6 +355,7 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)
 {
 	struct task_struct *me = current;
 
+	nsset->flags = flags;
 	nsset->nsproxy = create_new_namespaces(0, me, current_user_ns(), me->fs);
 	if (IS_ERR(nsset->nsproxy))
 		return PTR_ERR(nsset->nsproxy);
@@ -375,7 +376,6 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)
 			goto out;
 	}
 
-	nsset->flags = flags;
 	return 0;
 
 out:
Signature · 1 line
2.53.0
author maintainer
#2383 lore raw

PATCH 2360/2651 ACPI: platform_profile: Separate handler locking from sysfs lifetime

In reply to Greg Kroah-Hartman

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

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

From: Daniel Lezcano <[email protected]>

[ Upstream commit b66621ad2a8fb553c4cb75b9d69fead4f0532933 ]

Registration and removal currently hold profile_lock across device_unregister() and sysfs_update_group(). These operations can remove sysfs attributes and wait for their active callbacks to finish. The profile read and write callbacks acquire profile_lock themselves, so a concurrent access can deadlock:

  Removal/update path             Active sysfs callback
  -------------------             ---------------------
  acquire profile_lock            hold kernfs active reference

remove a sysfs attribute wait for profile_lock
wait for its active references

The removal path cannot finish until the callback returns, and the callback cannot return until the removal path releases profile_lock. This applies both to per-provider device teardown and to updates of the legacy aggregate attribute group.

Commit 041142d7d252 ("ACPI: platform-profile: Fix possible deadlock in platform_profile_remove()") previously fixed this lock ordering by moving sysfs_remove_group() outside profile_lock. Commit 55b1e68134bf ("ACPI:
platform_profile: Use guard(mutex) for register/unregister") reintroduced the issue by extending the mutex guard over sysfs_remove_group(). Later, commit 77be5cacb2c2 ("ACPI: platform_profile: Create class for ACPI platform profile") replaced that teardown with device_unregister() and sysfs_update_group(), still under the same mutex, extending the problem to class-device teardown and aggregate attribute updates.

Simply dropping profile_lock around these operations is insufficient. Aggregate operations currently discover providers through the class device list. A provider being unregistered could therefore still be selected for an aggregate read, write or cycle while its sysfs files are being torn down. Concurrent registrations and removals would also race when updating aggregate attribute visibility.

Introduce profile_registration_lock to serialize registration, removal and aggregate sysfs updates. Sysfs callbacks never acquire this mutex. Retain profile_lock for profile operations and use it to protect an explicit list of handlers participating in the aggregate interface.

Add a handler to that list only after device_register() succeeds. On removal, unlink it under profile_lock before calling device_unregister(). Acquiring profile_lock first waits for any aggregate operation already using the handler to complete; unlinking prevents later aggregate operations from finding it. Release profile_lock before draining sysfs callbacks, allowing active per-provider callbacks to complete before the device is released. Apply the same unlink-before-unregister ordering to registration error cleanup.

Walk this list for aggregate reads, writes and profile cycling, and use its emptiness to determine aggregate attribute visibility. The class devices remain the per-provider userspace interface.

There can now be an interval between removing the last handler from the list and removing the aggregate attributes. Explicitly reject choices reads and writes during that interval: the intersection bitmap starts with every bit set, so an empty traversal must not advertise all profiles or report a successful write without updating a provider.

This separates aggregate membership from class device teardown while preserving the existing class and ACPI sysfs interfaces.

Fixes 55b1e68134bf ("ACPI: platform_profile: Use guard(mutex) for register/unregister")
Fixes 77be5cacb2c2 ("ACPI: platform_profile: Create class for ACPI platform profile")
[ rjw: Subject adjustment, added two empty code lines ]
[ rjw: Renamed profile_walk_handlers() to profile_for_each_handler() ]
---
 drivers/acpi/platform_profile.c | 82 ++++++++++++++++++++-------------
 1 file changed, 49 insertions(+), 33 deletions(-)
drivers/acpi/platform_profile.c +49 -33
index 79d2e92e5c28d..b4c91d57f3d48 100644
@@ -8,15 +8,25 @@
 #include <linux/bits.h>
 #include <linux/cleanup.h>
 #include <linux/init.h>
+#include <linux/list.h>
 #include <linux/mutex.h>
 #include <linux/platform_profile.h>
 #include <linux/sysfs.h>
 
 #define to_pprof_handler(d)	(container_of(d, struct platform_profile_handler, dev))
 
+/*
+ * Protects profile_handlers membership and serializes profile operations
+ * against each other and handler removal. Never held across sysfs teardown,
+ * which can wait for callbacks that acquire this lock.
+ */
 static DEFINE_MUTEX(profile_lock);
+/* Serialize registration and sysfs updates without blocking sysfs callbacks. */
+static DEFINE_MUTEX(profile_registration_lock);
+static LIST_HEAD(profile_handlers);
 
 struct platform_profile_handler {
+	struct list_head node;
 	const char *name;
 	struct device dev;
 	int minor;
@@ -44,6 +54,23 @@ static_assert(ARRAY_SIZE(profile_names) == PLATFORM_PROFILE_LAST);
 
 static DEFINE_IDA(platform_profile_ida);
 
+static int profile_for_each_handler(void *data,
+				    int (*fn)(struct device *dev, void *data))
+{
+	struct platform_profile_handler *handler;
+	int ret;
+
+	lockdep_assert_held(&profile_lock);
+
+	list_for_each_entry(handler, &profile_handlers, node) {
+		ret = fn(&handler->dev, data);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
 /**
  * _commmon_choices_show - Show the available profile choices
  * @choices: The available profile choices
@@ -306,20 +333,18 @@ static ssize_t platform_profile_choices_show(struct kobject *kobj,
 	int err;
 
 	scoped_cond_guard(mutex_intr, return -ERESTARTSYS, &profile_lock) {
-		err = class_for_each_device(&platform_profile_class, NULL,
-					    &data, _aggregate_choices);
+		err = profile_for_each_handler(&data, _aggregate_choices);
 		if (err)
 			return err;
 		if (data.count == 1) {
-			err = class_for_each_device(&platform_profile_class, NULL,
-						    &data, _remove_hidden_choices);
+			err = profile_for_each_handler(&data, _remove_hidden_choices);
 			if (err)
 				return err;
 		}
 	}
 
 	/* no profile handler registered any more */
-	if (bitmap_empty(data.aggregate, PLATFORM_PROFILE_LAST))
+	if (!data.count || bitmap_empty(data.aggregate, PLATFORM_PROFILE_LAST))
 		return -EINVAL;
 
 	return _commmon_choices_show(data.aggregate, buf);
@@ -384,8 +409,7 @@ static ssize_t platform_profile_show(struct kobject *kobj,
 	int err;
 
 	scoped_cond_guard(mutex_intr, return -ERESTARTSYS, &profile_lock) {
-		err = class_for_each_device(&platform_profile_class, NULL,
-					    &profile, _aggregate_profiles);
+		err = profile_for_each_handler(&profile, _aggregate_profiles);
 		if (err)
 			return err;
 	}
@@ -423,15 +447,13 @@ static ssize_t platform_profile_store(struct kobject *kobj,
 		return -EINVAL;
 
 	scoped_cond_guard(mutex_intr, return -ERESTARTSYS, &profile_lock) {
-		ret = class_for_each_device(&platform_profile_class, NULL,
-					    &data, _aggregate_choices);
+		ret = profile_for_each_handler(&data, _aggregate_choices);
 		if (ret)
 			return ret;
-		if (!test_bit(i, data.aggregate))
+		if (!data.count || !test_bit(i, data.aggregate))
 			return -EOPNOTSUPP;
 
-		ret = class_for_each_device(&platform_profile_class, NULL, &i,
-					    _store_and_notify);
+		ret = profile_for_each_handler(&i, _store_and_notify);
 		if (ret)
 			return ret;
 	}
@@ -450,22 +472,11 @@ static struct attribute *platform_profile_attrs[] = {
 	NULL
 };
 
-static int profile_class_registered(struct device *dev, const void *data)
-{
-	return 1;
-}
-
 static umode_t profile_class_is_visible(struct kobject *kobj, struct attribute *attr, int idx)
 {
-	struct device *dev;
-
-	dev = class_find_device(&platform_profile_class, NULL, NULL, profile_class_registered);
-	if (!dev)
-		return 0;
-
-	put_device(dev);
+	guard(mutex)(&profile_lock);
 
-	return attr->mode;
+	return list_empty(&profile_handlers) ? 0 : attr->mode;
 }
 
 static const struct attribute_group platform_profile_group = {
@@ -502,8 +513,7 @@ int platform_profile_cycle(void)
 	int err;
 
 	scoped_cond_guard(mutex_intr, return -ERESTARTSYS, &profile_lock) {
-		err = class_for_each_device(&platform_profile_class, NULL,
-					    &profile, _aggregate_profiles);
+		err = profile_for_each_handler(&profile, _aggregate_profiles);
 		if (err)
 			return err;
 
@@ -512,8 +522,7 @@ int platform_profile_cycle(void)
 		    profile == PLATFORM_PROFILE_LAST)
 			return -EINVAL;
 
-		err = class_for_each_device(&platform_profile_class, NULL,
-					    &data, _aggregate_choices);
+		err = profile_for_each_handler(&data, _aggregate_choices);
 		if (err)
 			return err;
 
@@ -525,8 +534,7 @@ int platform_profile_cycle(void)
 					  PLATFORM_PROFILE_LAST,
 					  profile + 1);
 
-		err = class_for_each_device(&platform_profile_class, NULL, &next,
-					    _store_and_notify);
+		err = profile_for_each_handler(&next, _store_and_notify);
 
 		if (err)
 			return err;
@@ -583,7 +591,7 @@ struct device *platform_profile_register(struct device *dev, const char *name,
 		}
 	}
 
-	guard(mutex)(&profile_lock);
+	guard(mutex)(&profile_registration_lock);
 
 	/* create class interface for individual handler */
 	minor = ida_alloc(&platform_profile_ida, GFP_KERNEL);
@@ -604,6 +612,8 @@ struct device *platform_profile_register(struct device *dev, const char *name,
 		put_device(ppdev);
 		goto cleanup_ida;
 	}
+	scoped_guard(mutex, &profile_lock)
+		list_add_tail(&to_pprof_handler(ppdev)->node, &profile_handlers);
 
 	sysfs_notify(acpi_kobj, NULL, "platform_profile");
 
@@ -614,6 +624,9 @@ struct device *platform_profile_register(struct device *dev, const char *name,
 	return ppdev;
 
 cleanup_cur:
+	scoped_guard(mutex, &profile_lock)
+		list_del(&to_pprof_handler(ppdev)->node);
+
 	device_unregister(ppdev);
 
 cleanup_ida:
@@ -636,7 +649,10 @@ void platform_profile_remove(struct device *dev)
 
 	pprof = to_pprof_handler(dev);
 
-	guard(mutex)(&profile_lock);
+	guard(mutex)(&profile_registration_lock);
+
+	scoped_guard(mutex, &profile_lock)
+		list_del(&pprof->node);
 
 	ida_free(&platform_profile_ida, pprof->minor);
 	device_unregister(&pprof->dev);
Signature · 1 line
2.53.0
author maintainer
#2384 lore raw

PATCH 2361/2651 ACPICA: Initialize parser_state.aml_end in acpi_install_method()

In reply to Greg Kroah-Hartman

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

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

From: Ivan Hu <[email protected]>

[ Upstream commit ec696f34774db985841bac9a2df179c0040ef073 ]

In AcpiInstallMethod(), the local ParserState is stack-allocated and only ParserState.Aml was initialized. Parser helpers called by this path read ParserState.AmlEnd for bounds checking: AcpiPsPeekOpcode() reads it before validating the first AML opcode, and AcpiPsGetNextPackageEnd() reads it indirectly via AcpiPsGetNextPackageLength(). The subsequent package-limit check also compares against ParserState.AmlEnd. Because AmlEnd was never set, these checks operated on an uninitialized value, which Coverity flagged as an uninitialized read (CID 1684785) and which could lead to incorrect parser bounds decisions.

Coverity report:

*** CID 1684785: Memory - illegal accesses (UNINIT)
/src/acpica/source/components/namespace/nsxfname.c: 712 in AcpiInstallMethod()

        ParserState.Aml += AcpiPsGetOpcodeSize (Opcode);
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

CID 1684785: Memory - illegal accesses (UNINIT)
Using uninitialized value "ParserState.AmlEnd" when calling

        "AcpiPsGetNextPackageEnd".
        ParserState.PkgEnd = AcpiPsGetNextPackageEnd (&ParserState);

Initialize ParserState.AmlEnd to the end of the table (Buffer + Table->Length) so the parser bounds checks operate on a valid limit.

---
 drivers/acpi/acpica/nsxfname.c | 1 +
 1 file changed, 1 insertion(+)
drivers/acpi/acpica/nsxfname.c +1 -0
index b6534187cd43c..fcd94947fedb8 100644
@@ -503,6 +503,7 @@ acpi_status acpi_install_method(u8 *buffer)
 	/* First AML opcode in the table must be a control method */
 
 	parser_state.aml = buffer + sizeof(struct acpi_table_header);
+	parser_state.aml_end = buffer + table->length;
 	opcode = acpi_ps_peek_opcode(&parser_state);
 	if (opcode != AML_METHOD_OP) {
 		return (AE_BAD_PARAMETER);
Signature · 1 line
2.53.0
author maintainer
#2385 lore raw

PATCH 2362/2651 ksmbd: select CRYPTO_AES

In reply to Greg Kroah-Hartman

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

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

From: Michail Andreas Michalopoulos <[email protected]>

[ Upstream commit 2c36c4a86104d763ee798d4a89e2d3384b4cd626 ]

ksmbd allocates "gcm(aes)" and "ccm(aes)" AEAD transforms for SMB3 encryption, but SMB_SERVER only selects CRYPTO_GCM and CRYPTO_CCM, not an AES cipher. With a configuration in which nothing else enables CRYPTO_AES, ksmbd builds but cannot allocate the transforms, and every session that uses encryption fails:

ksmbd: Failed to alloc encrypt aead : -2
ksmbd: crypto alloc failed

Select CRYPTO_AES, as the SMB client already does.

Fixes a848c4f15ab6 ("cifsd: add Kconfig and Makefile")
Assisted-by LLM
---
 fs/smb/server/Kconfig | 1 +
 1 file changed, 1 insertion(+)
fs/smb/server/Kconfig +1 -0
index 221ec9717a834..622d8f4d27735 100644
@@ -16,6 +16,7 @@ config SMB_SERVER
 	select CRYPTO_AEAD2
 	select CRYPTO_CCM
 	select CRYPTO_GCM
+	select CRYPTO_AES
 	select ASN1
 	select OID_REGISTRY
 	select CRC32
Signature · 1 line
2.53.0
author maintainer
#2386 lore raw

PATCH 2363/2651 perf: Fix UAF in attach_task_ctx_data()

In reply to Greg Kroah-Hartman

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

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

From: Lee Jia Jie <[email protected]>

[ Upstream commit 64ea0e8226ed98d14e0231af1beae10c3d5c043a ]

struct perf_ctx_data is RCU protected. In attach_task_ctx_data(), the cmpxchg retry loop runs without holding rcu_read_lock(). If task->perf_ctx_data already holds a pointer (call it cd1), then try_cmpxchg(&task->perf_ctx_data, &old, cd) fails and loads old = cd1. A concurrent thread running detach_task_ctx_data() could free cd1 leading to UAF and further memory corruption when cd1 is reclaimed by another thread.

CPU 0: attach_task_ctx_data() CPU 1: detach_task_ctx_data()
----------------------------- -----------------------------
try_cmpxchg(&task->perf_ctx_data,

              &old, cd2)
    -> fails; loads old = cd1

                                    refcount_dec_and_test(&cd1->refcount)
                                    try_cmpxchg(&task->perf_ctx_data,
                                                &cd1, NULL)
                                    perf_free_ctx_data_rcu(cd1)
                                    [ RCU grace period -> kfree(cd1) ]

refcount_inc_not_zero(&old->refcount)

    -> UAF on freed cd1

Fix this by taking rcu_read_lock across the race window.

Fixes 506e64e710ff ("perf: attach/detach PMU specific data")
---
 kernel/events/core.c | 3 +++
 1 file changed, 3 insertions(+)
kernel/events/core.c +3 -0
index 9b90b6831de7c..e8293a0e7945c 100644
@@ -5434,6 +5434,9 @@ attach_task_ctx_data(struct task_struct *task, struct kmem_cache *ctx_cache,
 		return -ENOMEM;
 
 	for (;;) {
+		/* Protect @old until inc_not_zero(&old->refcount) */
+		guard(rcu)();
+
 		if (try_cmpxchg(&task->perf_ctx_data, &old, cd)) {
 			if (old)
 				perf_free_ctx_data_rcu(old);
Signature · 1 line
2.53.0
author maintainer
#2387 lore raw

PATCH 2364/2651 ASoC: amd: raven: Fix memory leak in acp3x_dma_close()

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit e0b17f84f6e3fa1201b8e2857094023c42ce5636 ]

acp3x_dma_open() allocates a struct i2s_stream_instance for each substream, but acp3x_dma_close() never frees it, leaking it on every open/close cycle.

Free it in acp3x_dma_close().

---
 sound/soc/amd/raven/acp3x-pcm-dma.c | 2 ++
 1 file changed, 2 insertions(+)
sound/soc/amd/raven/acp3x-pcm-dma.c +2 -0
index 072f3dc35d402..01e6ac75f35bf 100644
@@ -354,6 +354,8 @@ static int acp3x_dma_close(struct snd_soc_component *component,
 		}
 	}
 
+	kfree(ins);
+
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#2388 lore raw

PATCH 2365/2651 cpuidle: haltpoll: Only define guest_halt_poll_ns tracepoint when used

In reply to Greg Kroah-Hartman

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

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

From: Steven Rostedt <[email protected]>

[ Upstream commit 107b87efc8fcd6a597f1b534f116385620770e56 ]

Tracepoints that are defined take up around 5K each, even if they are not used. When a tracepoint is used only in code when a specific config is enabled, their definition must also be only defined when the same config is enabled otherwise it wastes memory.

The tracepoint guest_halt_poll_ns is only used when CONFIG_CPU_IDLE_GOV_HALTPOLL is enabled. Guard the definition of that tracepoint with the same config.

Fixes 0da11bf0cab90 ("cpuidle: haltpoll: Add trace points for guest_halt_poll_ns grow/shrink")
---
 include/trace/events/power.h | 3 +++
 1 file changed, 3 insertions(+)
include/trace/events/power.h +3 -0
index 370f8df2fdb4b..4d17eb307b6ab 100644
@@ -497,6 +497,7 @@ DEFINE_EVENT(dev_pm_qos_request, dev_pm_qos_remove_request,
 	TP_ARGS(name, type, new_value)
 );
 
+#ifdef CONFIG_CPU_IDLE_GOV_HALTPOLL
 TRACE_EVENT(guest_halt_poll_ns,
 
 	TP_PROTO(bool grow, unsigned int new, unsigned int old),
@@ -525,6 +526,8 @@ TRACE_EVENT(guest_halt_poll_ns,
 	trace_guest_halt_poll_ns(true, new, old)
 #define trace_guest_halt_poll_ns_shrink(new, old) \
 	trace_guest_halt_poll_ns(false, new, old)
+#endif /* CONFIG_CPU_IDLE_GOV_HALTPOLL */
+
 #endif /* _TRACE_POWER_H */
 
 /* This part must be outside protection */
Signature · 1 line
2.53.0
author maintainer
#2389 lore raw

PATCH 2366/2651 regulator: irq: freeze deferred hardware access during suspend

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

The regulator IRQ helper delays status checks and recovery callbacks on non-freezable workqueues. Those callbacks may access regulator hardware after the backing bus has been suspended.

Use system_freezable_wq for normal-priority callbacks. Allocate a freezable high-priority workqueue when requested so the high_prio contract is preserved while hardware access is frozen across suspend.

Fixes 7111c6d1b31b ("regulator: IRQ based event/error notification helpers")
---
 drivers/regulator/irq_helpers.c | 38 +++++++++++++++++++--------------
 1 file changed, 22 insertions(+), 16 deletions(-)
drivers/regulator/irq_helpers.c +22 -16
index 5b3cfac286676..cdbd170d2b150 100644
@@ -15,6 +15,7 @@
 #include <linux/regmap.h>
 #include <linux/slab.h>
 #include <linux/spinlock.h>
+#include <linux/workqueue.h>
 #include <linux/regulator/driver.h>
 
 #include "internal.h"
@@ -27,6 +28,7 @@ struct regulator_irq {
 	int irq;
 	int retry_cnt;
 	struct delayed_work isr_work;
+	struct workqueue_struct *wq;
 };
 
 /*
@@ -145,12 +147,7 @@ static void regulator_notifier_isr_work(struct work_struct *work)
 	return;
 
 reschedule:
-	if (!d->high_prio)
-		mod_delayed_work(system_dfl_wq, &h->isr_work,
-				 msecs_to_jiffies(tmo));
-	else
-		mod_delayed_work(system_highpri_wq, &h->isr_work,
-				 msecs_to_jiffies(tmo));
+	mod_delayed_work(h->wq, &h->isr_work, msecs_to_jiffies(tmo));
 }
 
 static irqreturn_t regulator_notifier_isr(int irq, void *data)
@@ -248,13 +245,8 @@ static irqreturn_t regulator_notifier_isr(int irq, void *data)
 	}
 
 	if (d->irq_off_ms) {
-		if (!d->high_prio)
-			schedule_delayed_work(&h->isr_work,
-					      msecs_to_jiffies(d->irq_off_ms));
-		else
-			mod_delayed_work(system_highpri_wq,
-					 &h->isr_work,
-					 msecs_to_jiffies(d->irq_off_ms));
+		mod_delayed_work(h->wq, &h->isr_work,
+				 msecs_to_jiffies(d->irq_off_ms));
 	}
 
 	return IRQ_HANDLED;
@@ -363,13 +355,25 @@ void *regulator_irq_helper(struct device *dev,
 
 	init_rdev_errors(h);
 
-	if (h->desc.irq_off_ms)
+	if (h->desc.irq_off_ms) {
+		if (h->desc.high_prio) {
+			h->wq = alloc_workqueue("regulator_irq_highpri",
+						WQ_FREEZABLE | WQ_HIGHPRI, 0);
+			if (!h->wq)
+				return ERR_PTR(-ENOMEM);
+		} else {
+			h->wq = system_freezable_wq;
+		}
+
 		INIT_DELAYED_WORK(&h->isr_work, regulator_notifier_isr_work);
+	}
 
 	ret = request_threaded_irq(h->irq, NULL, regulator_notifier_isr,
 				   IRQF_ONESHOT | irq_flags, h->desc.name, h);
 	if (ret) {
 		dev_err(dev, "Failed to request IRQ %d\n", irq);
+		if (h->desc.irq_off_ms && h->desc.high_prio)
+			destroy_workqueue(h->wq);
 
 		return ERR_PTR(ret);
 	}
@@ -393,8 +397,11 @@ void regulator_irq_helper_cancel(void **handle)
 		struct regulator_irq *h = *handle;
 
 		free_irq(h->irq, h);
-		if (h->desc.irq_off_ms)
+		if (h->desc.irq_off_ms) {
 			cancel_delayed_work_sync(&h->isr_work);
+			if (h->desc.high_prio)
+				destroy_workqueue(h->wq);
+		}
 
 		h = NULL;
 	}
@@ -441,4 +448,3 @@ int regulator_irq_map_event_simple(int irq, struct regulator_irq_data *rid,
 	return 0;
 }
 EXPORT_SYMBOL_GPL(regulator_irq_map_event_simple);
-
Signature · 1 line
2.53.0
author maintainer
#2390 lore raw

PATCH 2367/2651 sctp: reject forged cookie peer_addr with unknown address family

In reply to Greg Kroah-Hartman

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

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

From: Xingyuan Mo <[email protected]>

[ Upstream commit 9802123ceca818aa69284c615114ca55b9cc94a1 ]

When cookie authentication is disabled, COOKIE-ECHO peer_addr is attacker-controlled. An invalid sa_family made sctp_get_af_specific() return NULL and crash in sctp_transport_init() on af_specific->sockaddr_len. Validate it with af->addr_valid() in sctp_unpack_cookie(), which also rejects a mismatched family, e.g. an AF_INET6 peer_addr on an IPv4 socket that would later crash in sctp_v6_get_dst() on inet6_sk(sk)->opt. Validate a copy of peer_addr, since addr_valid() rewrites a v4-mapped v6 address in place and the cookie still lives in the received skb, which is not guaranteed to be unshared. Store the validated copy in the new association and pass it to sctp_process_init() instead of the raw cookie, so a v4-mapped v6 address is normalised to AF_INET before the association and its primary transport are built from it.

For that, sctp_v6_addr_valid() has to return 0 for a non-v4-mapped address when it is called with a socket that is not PF_INET6, so that IPv6 addresses are never used on IPv4 sockets. The check is done after the v4-mapped handling, so v4-mapped addresses passed to an IPv4 socket through the socket API keep being accepted. As addr_valid() now also checks sk_family and ipv6_only_sock, simplify the address handling in sctp_process_param() with it, as it additionally filters out non-unicast addresses. As a side effect, a v4-mapped address in an IPv6 address parameter is now normalised to AF_INET before the transport is created, matching what the socket API paths already do.

Also add the missing !af check in sctp_process_init(), as sctp_get_af_specific(AF_INET6) returns NULL on CONFIG_IPV6=n builds.

  BUG: KASAN: null-ptr-deref in sctp_transport_new+0xa7/0x350
  Read of size 4 at addr 00000000000000b4 by task poc/682
  Call Trace:
   <IRQ>
   sctp_transport_new+0xa7/0x350
   sctp_assoc_add_peer+0x153/0x850
   sctp_process_init+0xf9/0x1180
   sctp_sf_do_5_1D_ce+0x464/0xbc0
   sctp_do_sm+0x114/0x2990
   sctp_endpoint_bh_rcv+0x280/0x430
   sctp_inq_push+0xdd/0x100
   sctp_rcv+0x17f5/0x1ae0
   sctp4_rcv+0x2b/0x40
   ip_protocol_deliver_rcu+0x25b/0x270
   ip_local_deliver+0xd1/0xe0
   </IRQ>
  Kernel panic - not syncing: Fatal exception in interrupt
---
 net/sctp/ipv6.c          |  6 +++++-
 net/sctp/sm_make_chunk.c | 24 +++++++++++++-----------
 net/sctp/sm_statefuns.c  |  2 +-
 3 files changed, 19 insertions(+), 13 deletions(-)
net/sctp/ipv6.c +5 -1
index ef26878f1282a..97390569c4bdc 100644
@@ -725,7 +725,8 @@ static int sctp_v6_available(union sctp_addr *addr, struct sctp_sock *sp)
  * SCTP.
  *
  * Output:
- * Return 0 - If the address is a non-unicast or an illegal address.
+ * Return 0 - If the address is a non-unicast or an illegal address,
+ *            or a non-v4-mapped address on a non-PF_INET6 socket.
  * Return 1 - If the address is a unicast.
  */
 static int sctp_v6_addr_valid(union sctp_addr *addr,
@@ -749,6 +750,9 @@ static int sctp_v6_addr_valid(union sctp_addr *addr,
 	if (!(ret & IPV6_ADDR_UNICAST))
 		return 0;
 
+	if (sp && sctp_opt2sk(sp)->sk_family != PF_INET6)
+		return 0;
+
 	return 1;
 }
 
net/sctp/sm_make_chunk.c +13 -11
index 0896ec6c75ce7..90de272842512 100644
@@ -1740,7 +1740,9 @@ struct sctp_association *sctp_unpack_cookie(
 	struct sctp_cookie *bear_cookie;
 	struct sctp_chunkhdr *ch;
 	unsigned int len, chlen;
+	union sctp_addr paddr;
 	enum sctp_scope scope;
+	struct sctp_af *af;
 	ktime_t kt;
 
 	/* Header size is static data prior to the actual cookie, including
@@ -1849,6 +1851,11 @@ struct sctp_association *sctp_unpack_cookie(
 		goto fail;
 	}
 
+	paddr = bear_cookie->peer_addr;
+	af = sctp_get_af_specific(paddr.sa.sa_family);
+	if (!af || !af->addr_valid(&paddr, sctp_sk(ep->base.sk), NULL))
+		goto malformed;
+
 	/* Make a new base association.  */
 	scope = sctp_scope(sctp_source(chunk));
 	retval = sctp_association_new(ep, ep->base.sk, scope, gfp);
@@ -1865,6 +1872,7 @@ struct sctp_association *sctp_unpack_cookie(
 
 	/* Populate the association from the cookie.  */
 	memcpy(&retval->c, bear_cookie, sizeof(*bear_cookie));
+	retval->c.peer_addr = paddr;
 
 	if (sctp_assoc_set_bind_addr_from_cookie(retval, bear_cookie,
 						 GFP_ATOMIC) < 0) {
@@ -2389,8 +2397,8 @@ int sctp_process_init(struct sctp_association *asoc, struct sctp_chunk *chunk,
 		    (param.p->type == SCTP_PARAM_IPV4_ADDRESS ||
 		     param.p->type == SCTP_PARAM_IPV6_ADDRESS)) {
 			af = sctp_get_af_specific(param_type2af(param.p->type));
-			if (!af->from_addr_param(&addr, param.addr,
-						 chunk->sctp_hdr->source, 0))
+			if (!af || !af->from_addr_param(&addr, param.addr,
+							chunk->sctp_hdr->source, 0))
 				continue;
 			if (sctp_cmp_addr_exact(sctp_source(chunk), &addr))
 				src_match = 1;
@@ -2562,17 +2570,11 @@ static int sctp_process_param(struct sctp_association *asoc,
 	 */
 	switch (param.p->type) {
 	case SCTP_PARAM_IPV6_ADDRESS:
-		if (PF_INET6 != asoc->base.sk->sk_family)
-			break;
-		goto do_addr_param;
-
 	case SCTP_PARAM_IPV4_ADDRESS:
-		/* v4 addresses are not allowed on v6-only socket */
-		if (ipv6_only_sock(asoc->base.sk))
-			break;
-do_addr_param:
 		af = sctp_get_af_specific(param_type2af(param.p->type));
-		if (!af->from_addr_param(&addr, param.addr, htons(asoc->peer.port), 0))
+		if (!af || !af->from_addr_param(&addr, param.addr,
+						htons(asoc->peer.port), 0) ||
+		    !af->addr_valid(&addr, sctp_sk(asoc->base.sk), NULL))
 			break;
 		scope = sctp_scope(peer_addr);
 		if (sctp_in_scope(net, &addr, scope))
net/sctp/sm_statefuns.c +1 -1
index 8dc65498763cc..b2f609f177fb9 100644
@@ -814,7 +814,7 @@ enum sctp_disposition sctp_sf_do_5_1D_ce(struct net *net,
 	 * effects--it is safe to run them here.
 	 */
 	if (!sctp_process_init(new_asoc, chunk,
-			       &chunk->subh.cookie_hdr->c.peer_addr,
+			       &new_asoc->c.peer_addr,
 			       peer_init, GFP_ATOMIC))
 		goto nomem_init;
 
Signature · 1 line
2.53.0
author maintainer
#2391 lore raw

PATCH 2368/2651 tcp: reject devmem tx with fastopen and repair

In reply to Greg Kroah-Hartman

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

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

From: Kaifeng Wang <[email protected]>

[ Upstream commit 89b9db72918bc209029fad8cccc42191b498d511 ]

tcp_sendmsg_locked() enforces that devmem TX can only proceed if the zero-copy path is active and a valid dmabuf binding exists. However, subsequent branches in tcp_sendmsg_locked() can still intercept the message before it reaches the devmem zero-copy loop:

1. TCP Fast Open (MSG_FASTOPEN or DEFER_CONNECT):
If TCP_FASTOPEN_CONNECT is set, the socket may have a valid dst with NETIF_F_SG (so zc == MSG_ZEROCOPY and binding is present), but tcp_sendmsg_fastopen() -> tcp_send_syn_data() will use copy_page_from_iter() to byte-copy from the iterator. Since iov_base represents dma-buf offsets rather than user virtual addresses, this misinterprets offsets as user pointers and copies the caller's memory at those addresses into the SYN packet.

2. TCP repair mode:
If tp->repair is enabled with TCP_RECV_QUEUE, tcp_send_rcvq() similarly calls skb_copy_datagram_from_iter(), byte-copying from the iterator.

Neither path supports or makes sense for devmem transmission. Reject devmem sends inside the Fast Open and TCP repair branches when a devmem binding is present. Checking inside the tp->repair branch also covers the case where repair mode is enabled while sk_stream_wait_connect() drops the socket lock.

Additionally, drop the !sockc_err gate from the devmem validation check and return sockc_err if set. Otherwise, if a valid SCM_DEVMEM_DMABUF is followed by a failing cmsg, sockc.dmabuf_id remains set while binding is not acquired, allowing the Fast Open and TCP_RECV_QUEUE repair paths to proceed and return before sockc_err is checked.

This pre-existing issue was identified by Sashiko AI review on commit 125755776bc6 ("tcp: reject non zerocopy devmem tx") and has not been hit in production.

Fixes 125755776bc6 ("tcp: reject non zerocopy devmem tx")
Fixes bd61848900bf ("net: devmem: Implement TX path")
---
 net/ipv4/tcp.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
net/ipv4/tcp.c +10 -2
index 87ef6d5cbfeba..2792923f07489 100644
@@ -1169,14 +1169,18 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 			zc = MSG_SPLICE_PAGES;
 	}
 
-	if (!sockc_err && sockc.dmabuf_id && (zc != MSG_ZEROCOPY || !binding)) {
-		err = -EINVAL;
+	if (sockc.dmabuf_id && (zc != MSG_ZEROCOPY || !binding)) {
+		err = sockc_err ?: -EINVAL;
 		goto out_err;
 	}
 
 	if (unlikely(flags & MSG_FASTOPEN ||
 		     inet_test_bit(DEFER_CONNECT, sk)) &&
 	    !tp->repair) {
+		if (binding) {
+			err = -EINVAL;
+			goto out_err;
+		}
 		err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size, uarg);
 		if (err == -EINPROGRESS && copied_syn > 0)
 			goto out;
@@ -1200,6 +1204,10 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 	}
 
 	if (unlikely(tp->repair)) {
+		if (binding) {
+			err = -EINVAL;
+			goto out_err;
+		}
 		if (tp->repair_queue == TCP_RECV_QUEUE) {
 			copied = tcp_send_rcvq(sk, msg, size);
 			goto out_nopush;
Signature · 1 line
2.53.0
author maintainer
#2392 lore raw

PATCH 2369/2651 cgroup/cpuset: check effective mems for a movable-only configuration

In reply to Greg Kroah-Hartman

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

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

From: Gregory Price (Meta) <[email protected]>

[ Upstream commit 4c047bd0499602161959478b90e66f4c8e523c9b ]

check_insane_mems_config() warns and enables cpusets_insane_config_key when a cpuset's tasks can allocate only from movable memory.

In cgroup v2 the request may name a memoryless node, which has no zones and cpusets reports it as a movable-only nodemask.

For example, with node 2 a CPU-only node:

  # echo +cpuset > /sys/fs/cgroup/cgroup.subtree_control
  # mkdir /sys/fs/cgroup/test
  # echo 2 > /sys/fs/cgroup/test/cpuset.mems
  # cat /sys/fs/cgroup/test/cpuset.mems.effective
    0-1
  # dmesg
    Unsupported (movable nodes only) cpuset configuration detected (nmask=2)!

This is a bit confusing, especially consider mems.effective ends up with a valid nodemask by-design (cpuset.mems is treated as-if it were empty).

Check each new effective mask in update_nodemasks_hier() instead, as the hotplug path already does. The allocator's bail-out tests the task's mems_allowed, which comes from the effective mask.

A request naming a movable-only not present in the parent's nodemask no longer warns (since, again, the cpuset.mems gets overridden and treated as empty). However, it will warn if the parent's mems include the node later.

For Example, with node 3 a movable-only node:

  # echo 0 > /sys/fs/cgroup/test/cpuset.mems
  # echo 3 > /sys/fs/cgroup/test/child/cpuset.mems
  # cat /sys/fs/cgroup/test/child/cpuset.mems.effective
    0
  # dmesg
    { empty }
  # echo 0,3 > /sys/fs/cgroup/test/cpuset.mems
  # cat /sys/fs/cgroup/test/child/cpuset.mems.effective
    3
  # dmesg
    Unsupported (movable nodes only) cpuset configuration detected (nmask=3)!
Fixes 8ca1b5a49885 ("mm/page_alloc: detect allocation forbidden by cpuset and bail out early")
---
 kernel/cgroup/cpuset.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/cgroup/cpuset.c +2 -2
index 5d1883d19319b..d39953799ad56 100644
@@ -2882,6 +2882,8 @@ static void update_nodemasks_hier(struct cpuset *cs, nodemask_t *new_mems)
 			continue;
 		rcu_read_unlock();
 
+		check_insane_mems_config(new_mems);
+
 		spin_lock_irq(&callback_lock);
 		cp->effective_mems = *new_mems;
 		spin_unlock_irq(&callback_lock);
@@ -2935,8 +2937,6 @@ static int update_nodemask(struct cpuset *cs, struct cpuset *trialcs,
 	if (retval < 0)
 		return retval;
 
-	check_insane_mems_config(&trialcs->mems_allowed);
-
 	spin_lock_irq(&callback_lock);
 	cs->mems_allowed = trialcs->mems_allowed;
 	spin_unlock_irq(&callback_lock);
Signature · 1 line
2.53.0
author maintainer
#2393 lore raw

PATCH 2370/2651 ALSA: sh: aica: Fix spu_memset() stride

In reply to Greg Kroah-Hartman

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

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

From: Florian Fuchs <[email protected]>

[ Upstream commit 0d01f90b07e877ef31f9959e9b0bc6bcca9b99df ]

spu_memset() writes one 32-bit word per iteration, but advances the destination offset by only one byte. spu_reset() calls it with 0x200000 / 4 words to clear the 2 MiB of sound RAM, so:

- three out of four writel() calls target an unaligned address. The SH4 can't do that. Each one traps and is emulated by the unaligned access fixup. This call to spu_memset() causes 393216 unaligned accesses, visible in /proc/cpu/alignment.
- the clear covered only about 512 KiB of sound RAM, not 2 MiB.

Advance the offset by the size of the written word, to clear the full sound RAM using aligned writes.

Fixes 198de43d758c ("[ALSA] Add ALSA support for the SEGA Dreamcast PCM device")
---
 sound/sh/aica.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/sh/aica.c +1 -1
index 078fc7fc08f9f..04f80c8c89c03 100644
@@ -94,7 +94,7 @@ static void spu_memset(u32 toi, u32 what, int length)
 		local_irq_save(flags);
 		writel(what, toi + SPU_MEMORY_BASE);
 		local_irq_restore(flags);
-		toi++;
+		toi += sizeof(what);
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#2394 lore raw

PATCH 2371/2651 net: ethernet: ti: am65-cpts: fix support for PTP_EXTTS_REQUEST2 ioctl

In reply to Greg Kroah-Hartman

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

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

From: James Clark <[email protected]>

[ Upstream commit e3aaeebbef56ceaa27001d1d5a0c1d73d648e6f4 ]

Commit 7c571ac57d9d ("net: ptp: introduce .supported_extts_flags to ptp_clock_info") modified the PTP core to validate the supported flags of external timestamp requests, rather than relying on each driver to check them.

am65_cpts_extts_enable() ignores the flags, and am65-cpts was not given any .supported_extts_flags. Since PTP_EXTTS_REQUEST2 always implies PTP_STRICT_FLAGS, the core now rejects every PTP_EXTTS_REQUEST2 for this driver with -EOPNOTSUPP, where before that commit the same requests succeeded. Only the PTP_EXTTS_REQUEST ioctl still works.

Tests on a BeagleY-AI (J722S) show that the CPTS hardware timestamp push inputs timestamp just the rising edge. Encode this in .supported_extts_flags. A PTP_EXTTS_REQUEST2 for the rising edge then succeeds, and one for the falling edge or for both edges fails with -EOPNOTSUPP.

---
 drivers/net/ethernet/ti/am65-cpts.c | 1 +
 1 file changed, 1 insertion(+)
drivers/net/ethernet/ti/am65-cpts.c +1 -0
index efbf2ef976a32..df5659ead72f6 100644
@@ -779,6 +779,7 @@ static long am65_cpts_ts_work(struct ptp_clock_info *ptp);
 static struct ptp_clock_info am65_ptp_info = {
 	.owner		= THIS_MODULE,
 	.name		= "CTPS timer",
+	.supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS,
 	.adjfine	= am65_cpts_ptp_adjfine,
 	.adjtime	= am65_cpts_ptp_adjtime,
 	.gettimex64	= am65_cpts_ptp_gettimex,
Signature · 1 line
2.53.0
author maintainer
#2395 lore raw

PATCH 2372/2651 eth: fbnic: Correct packet header prefetch

In reply to Greg Kroah-Hartman

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

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

From: Dimitri Daskalakis <[email protected]>

[ Upstream commit 286154ae6998a32cca698abd713e1d4728e81924 ]

The existing call to net_prefetch() fetched a stale address. The data pointer is not initialized until after the call to xdp_prepare_buff(). Thus, making the prefetch ineffective.

Open code the address calcuation to give the prefetch as much time as possible.

This was found by manual code inspection. No issues have been observed from this.

---
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +1 -1
index 10caacffee0f0..69cd96a4508f3 100644
@@ -1011,7 +1011,7 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 
 	/* Build frame around buffer */
 	hdr_start = page_address(page) + hdr_pg_start;
-	net_prefetch(pkt->buff.data);
+	net_prefetch(hdr_start + headroom);
 	xdp_prepare_buff(&pkt->buff, hdr_start, headroom,
 			 len - FBNIC_RX_PAD, true);
 
Signature · 1 line
2.53.0
author maintainer
#2396 lore raw

PATCH 2373/2651 net: pse-pd: si3474: keep detection enabled on the other PIs

In reply to Greg Kroah-Hartman

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

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

From: Piotr Kubik <[email protected]>

[ Upstream commit b530456be77160b13efe8dececb6c826538bd4a2 ]

DETECT_CLASS_ENABLE holds the detection and classification bits of all four channels of a quad. si3474_pi_enable() wrote the register with the bits of its own PI only, so it cleared them for the other PI of the quad. In AUTO mode that PI keeps its admin state and a PD that already has power keeps it, but the port runs no new detection: a PD plugged in later, or one waiting for detection when the other PI is enabled, gets no power.

Read the register and set the PI bits, as the PORT_MODE update above already does.

Discovered by an AI code review agent. Confirmed on an SDG-9000 board (MediaTek MT7988A, two Si3474 in AUTO pin mode) with Linux 6.18:
with both PIs of one quad disabled, enabling PI A and then PI B left DETECT_CLASS_ENABLE with the bits of PI B only, and a PD on PI A never got power. No kernel change was needed to reproduce it.

Tested on the same board with the same sequence in both orders:
DETECT_CLASS_ENABLE keeps the bits of both PIs, and the PD gets power. No kernel selftest covers PSE hardware.

Fixes a2317231df4b ("net: pse-pd: Add Si3474 PSE controller driver")
---
 drivers/net/pse-pd/si3474.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/net/pse-pd/si3474.c +7 -2
index 2f4f241a48af6..e4eff88ae6723 100644
@@ -312,8 +312,13 @@ static int si3474_pi_enable(struct pse_controller_dev *pcdev, int id)
 	/* DETECT_CLASS_ENABLE must be set when using AUTO mode,
 	 * otherwise PI does not power up - datasheet section 2.10.2
 	 */
-	val = CHAN_BIT(chan0) | CHAN_UPPER_BIT(chan0) |
-	      CHAN_BIT(chan1) | CHAN_UPPER_BIT(chan1);
+	ret = i2c_smbus_read_byte_data(client, DETECT_CLASS_ENABLE_REG);
+	if (ret < 0)
+		return ret;
+
+	val = (u8)ret;
+	val |= CHAN_BIT(chan0) | CHAN_UPPER_BIT(chan0) |
+	       CHAN_BIT(chan1) | CHAN_UPPER_BIT(chan1);
 
 	ret = i2c_smbus_write_byte_data(client, DETECT_CLASS_ENABLE_REG, val);
 	if (ret)
Signature · 1 line
2.53.0
author maintainer
#2397 lore raw

PATCH 2374/2651 net: pse-pd: si3474: validate the channels of a PI

In reply to Greg Kroah-Hartman

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

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

From: Piotr Kubik <[email protected]>

[ Upstream commit 110eb808324fd9713b04d874c97283d965e43d2a ]

si3474_get_of_channels() accepted channel 8, one past the last channel. The driver then accessed channel 4 instead: quad 1, channel index 0.

It also accepted a 4-pair PI whose two channels are not a channel pair of one quad. The chip forms a 4-pair port only from channels 0+1 or 2+3 of a quad (2P/4P mode bit in POWER_ALLOCATION, PORT_REMAP default), and the driver sends every register access of a PI to the quad of its first channel, so such a PI enabled and measured the wrong channels.

Reject both at probe.

Discovered by an AI code review agent; no shipped device tree triggers it. Validated and tested on an SDG-9000 board (MediaTek MT7988A, two Si3474) with Linux 6.18 and a modified device tree: one chip with a channel at reg 8, the other with a 4-pair PI on channels 1 and 2. The driver now rejects both at probe, and the unmodified device tree still probes all eight PIs. No kernel selftest covers PSE hardware.

Fixes a2317231df4b ("net: pse-pd: Add Si3474 PSE controller driver")
---
 drivers/net/pse-pd/si3474.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
drivers/net/pse-pd/si3474.c +12 -2
index e4eff88ae6723..97a3b998729d9 100644
@@ -250,9 +250,9 @@ static int si3474_get_of_channels(struct si3474_priv *priv)
 					"Failed to read channel reg property\n");
 				return ret;
 			}
-			if (chan_id > SI3474_MAX_CHANS) {
+			if (chan_id >= SI3474_MAX_CHANS) {
 				dev_err(&priv->client[0]->dev,
-					"Incorrect channel number: %d\n", chan_id);
+					"Incorrect channel number: %u\n", chan_id);
 				return -EINVAL;
 			}
 
@@ -267,6 +267,16 @@ static int si3474_get_of_channels(struct si3474_priv *priv)
 				pi->np);
 			return -EINVAL;
 		}
+
+		/* The 2P/4P mode bit pairs channels 0+1 and 2+3 of a quad */
+		if (pairset_found &&
+		    (priv->pi[pi_no].chan[0] ^ 1) != priv->pi[pi_no].chan[1]) {
+			dev_err(&priv->client[0]->dev,
+				"PI %pOF: channels %u and %u are not a channel pair\n",
+				pi->np, priv->pi[pi_no].chan[0],
+				priv->pi[pi_no].chan[1]);
+			return -EINVAL;
+		}
 	}
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#2398 lore raw

PATCH 2375/2651 net: sparx5/lan969x: do not read past skb->len when injecting a frame

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit 9642ce6cb51ebd596d0a02074ba9b2a387e974b0 ]

sparx5_inject() writes the frame to the injection FIFO one 32-bit word at a time, and pads frames shorter than 60 bytes with zero words.

Before this patch, the last word is loaded whole even when skb->len is not a multiple of four, so 1 to 3 bytes past the end of the frame are read. For a frame shorter than 60 bytes those bytes are also transmitted, as VLD_BYTES marks the whole last word valid and the padding starts at the next word.

Write the trailing bytes from a zeroed word. The number of words written and VLD_BYTES are unchanged.

Found by an AI code review agent, and reproduced on lan969x and sparx5 with register injection: bytes 57 to 59 of a 57 byte frame were not zero. With the fix they are zero, and traffic still passes on both chips.

---
 .../net/ethernet/microchip/sparx5/sparx5_packet.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
drivers/net/ethernet/microchip/sparx5/sparx5_packet.c +12 -3
index f713656f1fae1..14c9ae673e354 100644
@@ -169,8 +169,8 @@ static int sparx5_inject(struct sparx5 *sparx5,
 			 struct sk_buff *skb,
 			 struct net_device *ndev)
 {
+	u32 val, w, count, last;
 	int grp = INJ_QUEUE;
-	u32 val, w, count;
 	u8 *buf;
 
 	val = spx5_rd(sparx5, QS_INJ_STATUS);
@@ -189,14 +189,23 @@ static int sparx5_inject(struct sparx5 *sparx5,
 	for (w = 0; w < IFH_LEN; w++)
 		spx5_wr(ifh[w], sparx5, QS_INJ_WR(grp));
 
-	/* Write words, round up */
-	count = DIV_ROUND_UP(skb->len, 4);
+	/* Write the whole words of the frame */
+	count = skb->len / 4;
 	buf = skb->data;
 	for (w = 0; w < count; w++, buf += 4) {
 		val = get_unaligned((const u32 *)buf);
 		spx5_wr(val, sparx5, QS_INJ_WR(grp));
 	}
 
+	/* Write the last 1 to 3 bytes, zero padded to a whole word */
+	last = skb->len % 4;
+	if (last) {
+		val = 0;
+		memcpy(&val, buf, last);
+		spx5_wr(val, sparx5, QS_INJ_WR(grp));
+		w++;
+	}
+
 	/* Add padding */
 	while (w < (60 / 4)) {
 		spx5_wr(0, sparx5, QS_INJ_WR(grp));
Signature · 1 line
2.53.0
author maintainer
#2399 lore raw

PATCH 2376/2651 net: sparx5: fix tx DCB index drift in fdma xmit

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit 1df26063ab9ba64f5fb11049fa4be686b7fc309e ]

sparx5_fdma_xmit() advances dcb_index before checking that the FDMA is done with the DCB, and does not undo the advance when the check fails. Before commit f4aa7e361ae2 ("net: sparx5: use FDMA library for adding DCB's in the tx path") the next DCB was always the one after last_dcb. Since then dcb_index drifts one DCB further away from last_dcb on every failed transmit.

While the ring is full, this drops frames even though completed DCBs sit behind dcb_index. After a run of failures, dcb_index can also land on last_dcb itself. Re-adding last_dcb loses the frame, because the FDMA has already passed the tail of the chain, and that DCB is never completed again.

Fix this by making dcb_index the next DCB to use, and advancing it only after the DCB has been added, as the rx path does. dcb_index and last_dcb now only move together, so dcb_index always points at the DCB after last_dcb.

The issue was found by an AI code review agent. It was reproduced on a sparx5 PCB135 board with a modified kernel that forces 63 consecutive transmit failures. Afterwards, about 1 in 64 frames is lost for good. With the fix, the same test loses no frames.

Fixes f4aa7e361ae2 ("net: sparx5: use FDMA library for adding DCB's in the tx path")
---
 drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c +2 -1
index dbe86f937b210..15ec9b053824f 100644
@@ -217,7 +217,6 @@ int sparx5_fdma_xmit(struct sparx5 *sparx5, u32 *ifh, struct sk_buff *skb,
 	struct fdma *fdma = &tx->fdma;
 	void *virt_addr;
 
-	fdma_dcb_advance(fdma);
 	if (!fdma_db_is_done(fdma_db_get(fdma, fdma->dcb_index, 0)))
 		return -EINVAL;
 
@@ -235,6 +234,8 @@ int sparx5_fdma_xmit(struct sparx5 *sparx5, u32 *ifh, struct sk_buff *skb,
 		     FDMA_DCB_STATUS_BLOCKO(0) |
 		     FDMA_DCB_STATUS_BLOCKL(skb->len + IFH_LEN * 4 + 4));
 
+	fdma_dcb_advance(fdma);
+
 	sparx5_fdma_reload(sparx5, fdma);
 
 	return NETDEV_TX_OK;
Signature · 1 line
2.53.0
author maintainer
#2400 lore raw

PATCH 2377/2651 selftests: gro: remove unused variable total_data

In reply to Greg Kroah-Hartman

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

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

From: Hangbin Liu <[email protected]>

[ Upstream commit 86537a8fb24750fc25a96a27ff29400054d052b5 ]

I hit a build warning when building the net selftests.

gro.c: In function 'check_capacity_pkts': gro.c:1249:13: warning: variable 'total_data' set but not used [-Wunused-but-set-variable=]

   1249 |         int total_data = 0;
        |             ^~~~~~~~~~

Remove the total_data variable, as it is no longer used.

Fixes d97348474708 ("selftests: drv-net: gro: always wait for FIN in the capacity test")
---
 tools/testing/selftests/net/lib/gro.c | 2 --
 1 file changed, 2 deletions(-)
tools/testing/selftests/net/lib/gro.c +0 -2
index 7a333155de1ab..1bc92e7a625f3 100644
@@ -1246,7 +1246,6 @@ static void check_capacity_pkts(int fd)
 	int coalesced[num_flows];
 	struct tcphdr *tcph;
 	int ip_ext_len = 0;
-	int total_data = 0;
 	int pkt_size = -1;
 	int data_len = 0;
 	int flow_id;
@@ -1309,7 +1308,6 @@ static void check_capacity_pkts(int fd)
 		}
 
 		num_pkt++;
-		total_data += data_len;
 	}
 
 	/* Check flow ordering. We expect to see all non-coalesced first segs
Signature · 1 line
2.53.0
author maintainer
#2401 lore raw

PATCH 2378/2651 tls: fix the open record check in the max payload size setsockopt

In reply to Greg Kroah-Hartman

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

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

From: Jiayuan Chen <[email protected]>

[ Upstream commit ed642349d87dd7067a44c30319f0cffd22780376 ]

do_tls_setsockopt_tx_payload_len() refuses to resize records while one is open, but the check is broken in two ways.

It reaches for the open record through tls_sw_ctx_tx(), an unchecked cast of ctx->priv_ctx_tx. Under device offload that pointer is a tls_offload_context_tx, so the check reads a field of the wrong struct: it returns EBUSY on whatever happens to be there, and never sees the record that really is open. Dispatch on tx_conf.

The socket lock alone is also not enough to tell no sender is in flight. The device tx path drops it in sk_stream_wait_memory() after tls_push_record() cleared open_record, so setsockopt can slip in mid-sendmsg and shrink the limit. tls_push_data() latches the limit once per call, and a record left open by MSG_MORE can then be bigger than the new limit, making the u32 subtraction in the copy clamp wrap around and build an oversized record. Take tx_lock like the sendmsg paths do so setsockopt waits for in-flight senders. Re-reading the limit inside the tls_push_data() loop could close the wrap too, but a parked sender would still finish with the old limit, so serializing on tx_lock is simpler.

Take tx_lock interruptible, as tls_sw_sendmsg() does. Both sendmsg paths keep it across sk_stream_wait_memory(), which sleeps until the peer reads, so a plain mutex_lock() could park setsockopt in D state for as long as the sender waits. The lock_sock() after it is fine uninterruptible: a sender sleeping for memory has released the socket lock, so that wait only covers short critical sections, like every other setsockopt.

Fixes 82cb5be6ad64 ("net/tls: support setting the maximum payload size")
---
 net/tls/tls_main.c | 22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)
net/tls/tls_main.c +20 -2
index fbb274287aa5f..2d1cde3f61886 100644
@@ -833,15 +833,26 @@ static int do_tls_setsockopt_no_pad(struct sock *sk, sockptr_t optval,
 	return rc;
 }
 
+static bool tls_tx_record_is_open(struct tls_context *ctx)
+{
+	switch (ctx->tx_conf) {
+	case TLS_SW:
+		return !!tls_sw_ctx_tx(ctx)->open_rec;
+	case TLS_HW:
+		return !!tls_offload_ctx_tx(ctx)->open_record;
+	default:
+		return false;
+	}
+}
+
 static int do_tls_setsockopt_tx_payload_len(struct sock *sk, sockptr_t optval,
 					    unsigned int optlen)
 {
 	struct tls_context *ctx = tls_get_ctx(sk);
-	struct tls_sw_context_tx *sw_ctx = tls_sw_ctx_tx(ctx);
 	u16 value;
 	bool tls_13 = ctx->prot_info.version == TLS_1_3_VERSION;
 
-	if (sw_ctx && sw_ctx->open_rec)
+	if (tls_tx_record_is_open(ctx))
 		return -EBUSY;
 
 	if (sockptr_is_null(optval) || optlen != sizeof(value))
@@ -862,6 +873,7 @@ static int do_tls_setsockopt_tx_payload_len(struct sock *sk, sockptr_t optval,
 static int do_tls_setsockopt(struct sock *sk, int optname, sockptr_t optval,
 			     unsigned int optlen)
 {
+	struct tls_context *ctx;
 	int rc = 0;
 
 	switch (optname) {
@@ -881,9 +893,15 @@ static int do_tls_setsockopt(struct sock *sk, int optname, sockptr_t optval,
 		rc = do_tls_setsockopt_no_pad(sk, optval, optlen);
 		break;
 	case TLS_TX_MAX_PAYLOAD_LEN:
+		ctx = tls_get_ctx(sk);
+		/* Senders sleep with tx_lock held, so take it interruptible */
+		rc = mutex_lock_interruptible(&ctx->tx_lock);
+		if (rc)
+			break;
 		lock_sock(sk);
 		rc = do_tls_setsockopt_tx_payload_len(sk, optval, optlen);
 		release_sock(sk);
+		mutex_unlock(&ctx->tx_lock);
 		break;
 	default:
 		rc = -ENOPROTOOPT;
Signature · 1 line
2.53.0
author maintainer
#2402 lore raw

PATCH 2379/2651 net: fix frag_list leak in skb_segment_list() error path

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 546daf344420b5dce27eded3ad15be12628dd185 ]

skb_segment_list() detaches the frag_list from the head skb and moves its members one by one to the skb->next chain. On error, err_linearize frees that chain with kfree_skb_list(skb->next), relying on the members not yet processed to still be linked after the current one.

This does not hold when the current member was shared: it is replaced by skb_clone(), and __skb_clone() clears ->next. If __skb_linearize() then fails on that clone, the remaining members are no longer reachable from skb->next nor from skb_shinfo(skb)->frag_list, and they leak.

The skb_shared() error branch already relinks nskb->next to list_skb before jumping to err_linearize. Do it unconditionally right after nskb is added to the chain, so every error exit sees the remaining members. On the last member list_skb is NULL, which still terminates the chain.

Fixes 53475c5dd856 ("net: fix use-after-free when UDP GRO with shared fraglist")
Cc Simon Polack <[email protected]>
---
 net/core/skbuff.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
net/core/skbuff.c +6 -3
index 0c1229c544d24..512eddc0fc3d6 100644
@@ -4747,10 +4747,13 @@ struct sk_buff *skb_segment_list(struct sk_buff *skb,
 		else
 			tail->next = nskb;
 
-		if (unlikely(err)) {
-			nskb->next = list_skb;
+		/* nskb may be a clone with a NULL ->next: keep the remaining
+		 * members linked so that err_linearize frees them.
+		 */
+		nskb->next = list_skb;
+
+		if (unlikely(err))
 			goto err_linearize;
-		}
 
 		tail = nskb;
 
Signature · 1 line
2.53.0
author maintainer
#2403 lore raw

PATCH 2380/2651 net/mlx5e: SHAMPO: Do not merge PSP packets

In reply to Greg Kroah-Hartman

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

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

From: Cosmin Ratiu <[email protected]>

[ Upstream commit 46bd2bf65b93573f3b73ce8c61f862ac901c076d ]

PSP packets are UDP-encapsulated, and enabling HW GRO (SHAMPO in mlx5) makes it possible to merge those packets in a silly way:
IP|UDP|PSP1|payload1|PSP2|payload2|...

That happens because the HW GRO machinery doesn't know about PSP and considers it part of the UDP payload.

Reject merging when the incoming CQE has PSP marker or the pending skb has the PSP extension.

---
 .../ethernet/mellanox/mlx5/core/en_accel/en_accel.h |  6 ++++++
 .../ethernet/mellanox/mlx5/core/en_accel/psp_rxtx.h | 13 +++++++++++++
 drivers/net/ethernet/mellanox/mlx5/core/en_rx.c     |  6 ++++--
 3 files changed, 23 insertions(+), 2 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/en_accel/en_accel.h +6 -0
index 3f212e46fc2f9..5a340f1435e6b 100644
@@ -218,6 +218,12 @@ static inline void mlx5e_accel_tx_finish(struct mlx5e_txqsq *sq,
 #endif
 }
 
+static inline bool
+mlx5e_accel_shampo_can_merge(struct mlx5e_rq *rq, struct mlx5_cqe64 *cqe)
+{
+	return mlx5e_psp_shampo_can_merge(rq->hw_gro_data->skb, cqe);
+}
+
 static inline int mlx5e_accel_init_rx(struct mlx5e_priv *priv)
 {
 	return mlx5e_ktls_init_rx(priv);
drivers/net/ethernet/mellanox/mlx5/core/en_accel/psp_rxtx.h +13 -0
index 2b080c39cc37e..9fd1ee789de02 100644
@@ -85,6 +85,13 @@ static inline bool mlx5e_psp_is_rx_flow(struct mlx5_cqe64 *cqe)
 	return MLX5_PSP_METADATA_MARKER(be32_to_cpu(cqe->ft_metadata));
 }
 
+static inline bool
+mlx5e_psp_shampo_can_merge(struct sk_buff *skb, struct mlx5_cqe64 *cqe)
+{
+	/* PSP packets cannot be merged. */
+	return !skb_ext_exist(skb, SKB_EXT_PSP) && !mlx5e_psp_is_rx_flow(cqe);
+}
+
 bool mlx5e_psp_offload_handle_rx_skb(struct net_device *netdev, struct sk_buff *skb,
 				     struct mlx5_cqe64 *cqe);
 #else
@@ -110,6 +117,12 @@ static inline bool mlx5e_psp_is_rx_flow(struct mlx5_cqe64 *cqe)
 	return false;
 }
 
+static inline bool
+mlx5e_psp_shampo_can_merge(struct sk_buff *skb, struct mlx5_cqe64 *cqe)
+{
+	return true;
+}
+
 static inline bool mlx5e_psp_offload_handle_rx_skb(struct net_device *netdev,
 						   struct sk_buff *skb,
 						   struct mlx5_cqe64 *cqe)
drivers/net/ethernet/mellanox/mlx5/core/en_rx.c +4 -2
index 903af3b3e7794..d49f26323b1e2 100644
@@ -49,6 +49,7 @@
 #include "en_rep.h"
 #include "en/rep/tc.h"
 #include "ipoib/ipoib.h"
+#include "en_accel/en_accel.h"
 #include "en_accel/ipsec.h"
 #include "en_accel/macsec.h"
 #include "en_accel/psp_rxtx.h"
@@ -2268,8 +2269,9 @@ static void mlx5e_handle_rx_cqe_mpwrq_shampo(struct mlx5e_rq *rq, struct mlx5_cq
 	}
 
 	if (*skb &&
-	    !(match && mlx5e_hw_gro_skb_has_enough_space(*skb, data_bcnt,
-							 page_size))) {
+	    !(match &&
+	      mlx5e_hw_gro_skb_has_enough_space(*skb, data_bcnt, page_size) &&
+	      mlx5e_accel_shampo_can_merge(rq, cqe))) {
 		match = false;
 		mlx5e_shampo_flush_skb(rq, cqe, match);
 	}
Signature · 1 line
2.53.0
author maintainer
#2404 lore raw

PATCH 2381/2651 net/mlx5e: IPsec, Fix out-of-bounds comparison of neighbour keys

In reply to Greg Kroah-Hartman

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

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

From: Gal Pressman <[email protected]>

[ Upstream commit 520631554a689d2cd52452578f3140f045730ee0 ]

mlx5e_ipsec_netevent_event() keeps the L2 headers of offloaded tunnel mode SAs up to date: on every neighbour change it looks for SAs whose endpoint matches the neighbour's address. The compare width, 4 bytes for IPv4 or 16 for IPv6, is chosen from the SA's address family, with no check that the neighbour is of the same family.

An ARP entry only stores a 4-byte key, so with an IPv6 tunnel mode SA offloaded, any IPv4 neighbour update in the system is compared as if it were a 16-byte IPv6 address, reading past the end of the object:

  BUG: KASAN: slab-out-of-bounds in mlx5e_ipsec_netevent_event+0x736/0x8d0 [mlx5_core]
  Read of size 4 at addr ff110001260a4ad8 by task swapper/8/0
  Call Trace:
   <IRQ>
   mlx5e_ipsec_netevent_event+0x736/0x8d0 [mlx5_core]
   notifier_call_chain+0x97/0x2b0
   atomic_notifier_call_chain+0x5d/0x130
   neigh_timer_handler+0x35c/0x1140
   call_timer_fn+0x164/0x490
   __run_timers+0x5b9/0x960
   run_timer_softirq+0xf0/0x1d0
   handle_softirqs+0x189/0x8a0
   __irq_exit_rcu+0x10d/0x250
   ...

  Allocated by task 1015:
   __kmalloc_noprof+0x2e6/0x8b0
   ___neigh_create+0xcc9/0x24c0
   ip_finish_output2+0xfc7/0x1e80
   ip_output+0x172/0x3b0
   ip_send_skb+0xa5/0x1b0
   udp_send_skb+0x852/0x10f0
   udp_sendmsg+0x1333/0x2150
   ...

The opposite mix (IPv4 SA with IPv6 neighbour) stays in bounds, but only the first 32 bits of the IPv6 address are compared, so an unrelated neighbour can match.

Skip neighbours whose address family doesn't match the SA.

---
 drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c +3 -0
index db260e3d1412f..e6dd911475e31 100644
@@ -958,6 +958,9 @@ static int mlx5e_ipsec_netevent_event(struct notifier_block *nb,
 	xa_for_each_marked(&ipsec->sadb, idx, sa_entry, MLX5E_IPSEC_TUNNEL_SA) {
 		attrs = &sa_entry->attrs;
 
+		if (attrs->addrs.family != n->tbl->family)
+			continue;
+
 		if (attrs->addrs.family == AF_INET) {
 			if (!neigh_key_eq32(n, &attrs->addrs.saddr.a4) &&
 			    !neigh_key_eq32(n, &attrs->addrs.daddr.a4))
Signature · 1 line
2.53.0
author maintainer
#2405 lore raw

PATCH 2382/2651 net/rds: include the scope id in the sendmsg connection cache check

In reply to Greg Kroah-Hartman

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

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

From: Allison Henderson <[email protected]>

[ Upstream commit b7dfff5e3eb3984d42026a6d653ec2a3d5cec729 ]

rds_sendmsg() reuses the connection cached in rs->rs_conn when its peer address and ToS match the request. The interface index is part of a connection's identity as well: rds_conn_create_outgoing() passes the request's scope_id down as dev_if, and rds_conn_lookup() compares c_dev_if, so sends to the same link-local address through two interfaces are two different connections. The cache-hit test never looked at it.

A socket bound to a non-link-local address has rs_bound_scope_id 0, and the scope check at the top of rds_sendmsg() accepts any non-zero destination scope for such a socket. So after a send to fe80::x%ifA, a send to fe80::x%ifB hits the cached ifA connection and the datagram leaves through ifA, to whichever peer answers to that address there.

Compare c_dev_if with the request's scope_id in the cache test, so that such a send takes the lookup path and finds, or creates, the ifB connection - the same key the lookup uses. A send without a destination takes its scope from the socket, and the connection it created was keyed on that same scope, so the comparison holds for it too; the next patch gives that send the connected peer's own scope.

Found by inspection while reworking this cache for the connection lifetime series on net-next; not observed in the field.

---
 net/rds/send.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/rds/send.c +2 -1
index 1afa981e5c06d..38b9cc9e0d20b 100644
@@ -1342,7 +1342,8 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 	/* rds_conn_create has a spinlock that runs with IRQ off.
 	 * Caching the conn in the socket helps a lot. */
 	if (rs->rs_conn && ipv6_addr_equal(&rs->rs_conn->c_faddr, &daddr) &&
-	    rs->rs_tos == rs->rs_conn->c_tos) {
+	    rs->rs_tos == rs->rs_conn->c_tos &&
+	    rs->rs_conn->c_dev_if == scope_id) {
 		conn = rs->rs_conn;
 	} else {
 		conn = rds_conn_create_outgoing(sock_net(sock->sk),
Signature · 1 line
2.53.0
author maintainer
#2406 lore raw

PATCH 2383/2651 net/rds: keep the connected peers scope id apart from the bound one

In reply to Greg Kroah-Hartman

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

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

From: Allison Henderson <[email protected]>

[ Upstream commit 3fe64a5f670dbd6c7c84c2345b0b9726b3b79b31 ]

rds_connect() has nowhere to keep the scope of a link-local peer, so it stores it in rs_bound_scope_id, the scope of the socket's own bound address, for rds_bind() to check a later link-local bind against. That field is then also what a send without a destination uses as the request's scope, what getpeername() and recvmsg() report as the peer's scope, and what a later bind() overwrites:
rds_add_bound() stores the bound address's scope unconditionally, which for a non-link-local address is 0.

So after connect(fe80::x%ifA) followed by bind(global), a send() with no destination asks for fe80::x with scope 0. rds_conn_lookup() keys on the interface, so that finds or creates a connection with c_dev_if 0, which the TCP transport then tries to connect through sin6_scope_id 0 and tcp_v6_connect() rejects for a link-local peer:
the connected socket's data is queued on a connection that can never come up. In the other order, bind(global) then connect(fe80::x%ifB), the connect leaves a global-bound socket with rs_bound_scope_id ifB, so sends to other link-local peers are refused as off-link and sends to global peers inherit a meaningless interface.

Give the connected peer its own rs_conn_scope_id. rds_connect() records it there and leaves the bound scope alone, rds_bind()'s connected-socket check compares against it, and the destination-less send takes its scope from it - falling back to the bound scope for a non-link-local peer, so that send() and sendto() to the connected peer compute the same scope, and so the same connection. getpeername() reports the connected peer with its own scope. recvmsg() used to report every sender with the socket's bound scope; a connected socket receives from any peer, so neither the bound scope nor the connected peer's scope is right for an arbitrary sender. It now reports a link-local sender with the interface recorded on its connection, c_dev_if: the TCP accept path takes it from the incoming socket, and the IB passive side resolves it from the local address, the closest the CM gets to the arrival interface. Any other sender is reported with scope 0, the inet6 convention. Either way, a reply to the address an application was given reaches the same connection.

Found by inspection while reworking the sendmsg connection cache; not observed in the field.

---
 net/rds/af_rds.c | 15 +++++++++------
 net/rds/bind.c   |  4 ++--
 net/rds/rds.h    |  2 ++
 net/rds/recv.c   | 11 ++++++++++-
 net/rds/send.c   |  6 +++++-
 5 files changed, 28 insertions(+), 10 deletions(-)
net/rds/af_rds.c +9 -6
index d5defe9172e36..e84d00bbe9a15 100644
@@ -136,8 +136,7 @@ static int rds_getname(struct socket *sock, struct sockaddr *uaddr,
 			sin6->sin6_port = rs->rs_conn_port;
 			sin6->sin6_addr = rs->rs_conn_addr;
 			sin6->sin6_flowinfo = 0;
-			/* scope_id is the same as in the bound address. */
-			sin6->sin6_scope_id = rs->rs_bound_scope_id;
+			sin6->sin6_scope_id = rs->rs_conn_scope_id;
 			uaddr_len = sizeof(*sin6);
 		}
 	} else {
@@ -572,6 +571,7 @@ static int rds_connect(struct socket *sock, struct sockaddr_unsized *uaddr,
 		}
 		ipv6_addr_set_v4mapped(sin->sin_addr.s_addr, &rs->rs_conn_addr);
 		rs->rs_conn_port = sin->sin_port;
+		rs->rs_conn_scope_id = 0;
 		break;
 
 #if IS_ENABLED(CONFIG_IPV6)
@@ -616,11 +616,14 @@ static int rds_connect(struct socket *sock, struct sockaddr_unsized *uaddr,
 				ret = -EINVAL;
 				break;
 			}
-			/* Remember the connected address scope ID.  It will
-			 * be checked against the binding local address when
-			 * the socket is bound.
+			/* Remember the connected address scope ID.  It is
+			 * checked against the binding local address when
+			 * the socket is bound, and gives a send without a
+			 * destination its scope.
 			 */
-			rs->rs_bound_scope_id = sin6->sin6_scope_id;
+			rs->rs_conn_scope_id = sin6->sin6_scope_id;
+		} else {
+			rs->rs_conn_scope_id = 0;
 		}
 		rs->rs_conn_addr = sin6->sin6_addr;
 		rs->rs_conn_port = sin6->sin6_port;
net/rds/bind.c +2 -2
index f800d920d9690..3ac59cd512a21 100644
@@ -233,8 +233,8 @@ int rds_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int addr_len)
 	 * non-link local address (scope_id is 0).
 	 */
 	if (!ipv6_addr_any(&rs->rs_conn_addr) && scope_id &&
-	    rs->rs_bound_scope_id &&
-	    scope_id != rs->rs_bound_scope_id) {
+	    rs->rs_conn_scope_id &&
+	    scope_id != rs->rs_conn_scope_id) {
 		ret = -EINVAL;
 		goto out;
 	}
net/rds/rds.h +2 -0
index 2db49573dacd5..9b1ffc49c0a61 100644
@@ -646,6 +646,8 @@ struct rds_sock {
 	struct in6_addr		rs_conn_addr;
 #define rs_conn_addr_v4		rs_conn_addr.s6_addr32[3]
 	__be16			rs_conn_port;
+	/* scope of rs_conn_addr when it is link-local, 0 otherwise */
+	__u32			rs_conn_scope_id;
 	struct rds_transport    *rs_transport;
 
 	/*
net/rds/recv.c +10 -1
index 93ee4546ae362..00ab60f2d9969 100644
@@ -791,7 +791,16 @@ int rds_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
 				sin6->sin6_port = inc->i_hdr.h_sport;
 				sin6->sin6_addr = inc->i_saddr;
 				sin6->sin6_flowinfo = 0;
-				sin6->sin6_scope_id = rs->rs_bound_scope_id;
+				/* A link-local sender is reported with the
+				 * interface recorded on its connection (the
+				 * accepting socket's device for TCP, the one
+				 * resolved for the local address on IB); any
+				 * other sender has no scope.
+				 */
+				sin6->sin6_scope_id =
+					(ipv6_addr_type(&inc->i_saddr) &
+					 IPV6_ADDR_LINKLOCAL) ?
+					inc->i_conn->c_dev_if : 0;
 				msg->msg_namelen = sizeof(*sin6);
 			}
 		}
net/rds/send.c +5 -1
index 38b9cc9e0d20b..f38967f65af18 100644
@@ -1256,7 +1256,11 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
 		lock_sock(sk);
 		daddr = rs->rs_conn_addr;
 		dport = rs->rs_conn_port;
-		scope_id = rs->rs_bound_scope_id;
+		/* The connected peer's scope for a link-local peer, else
+		 * the bound scope, as an explicit send to that peer would
+		 * compute below.
+		 */
+		scope_id = rs->rs_conn_scope_id ?: rs->rs_bound_scope_id;
 		release_sock(sk);
 	}
 
Signature · 1 line
2.53.0
author maintainer
#2407 lore raw

PATCH 2384/2651 selftests/net: tcp_mmap: remove unused -k option and keepflag

In reply to Greg Kroah-Hartman

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

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

From: Greg Thelen <[email protected]>

[ Upstream commit 5536d5553f274c8baa77c44854c9091657213970 ]

Commit aacb0c2e524c ("selftests: net: tcp_mmap must use TCP_ZEROCOPY_RECEIVE") removed the only read of keepflag in child_thread(), leaving the file-scope keepflag variable set by the -k option in main() but never read. This triggers a Clang 23 warning:

tcp_mmap.c:91:12: error: variable 'keepflag' set but not used [-Werror,-Wunused-but-set-global]

Remove the unused keepflag variable and the dead -k getopt option.

Fixes aacb0c2e524c ("selftests: net: tcp_mmap must use TCP_ZEROCOPY_RECEIVE")
---
 tools/testing/selftests/net/tcp_mmap.c | 6 +-----
 1 file changed, 1 insertion(+), 5 deletions(-)
tools/testing/selftests/net/tcp_mmap.c +1 -5
index 487ae659a1f18..86241bed7f086 100644
@@ -85,7 +85,6 @@ static int rcvbuf; /* Default: autotuning.  Can be set with -r <integer> option
 static int sndbuf; /* Default: autotuning.  Can be set with -w <integer> option */
 static int zflg; /* zero copy option. (MSG_ZEROCOPY for sender, mmap() for receiver */
 static int xflg; /* hash received data (simple xor) (-h option) */
-static int keepflag; /* -k option: receiver shall keep all received file in memory (no munmap() calls) */
 static int integrity; /* -i option: sender and receiver compute sha256 over the data.*/
 
 static size_t chunk_size  = 512*1024;
@@ -456,7 +455,7 @@ int main(int argc, char *argv[])
 	int sflg = 0;
 	int mss = 0;
 
-	while ((c = getopt(argc, argv, "46p:svr:w:H:zxkP:M:C:a:i")) != -1) {
+	while ((c = getopt(argc, argv, "46p:svr:w:H:zxP:M:C:a:i")) != -1) {
 		switch (c) {
 		case '4':
 			cfg_family = PF_INET;
@@ -490,9 +489,6 @@ int main(int argc, char *argv[])
 		case 'x':
 			xflg = 1;
 			break;
-		case 'k':
-			keepflag = 1;
-			break;
 		case 'P':
 			max_pacing_rate = atoi(optarg) ;
 			break;
Signature · 1 line
2.53.0
author maintainer
#2408 lore raw

PATCH 2385/2651 tls: avoid field-spanning write when copying crypto info

In reply to Greg Kroah-Hartman

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

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

From: Nandor Kracser <[email protected]>

[ Upstream commit c43c1c24f3cdc0d2d3f59e5686573ac3129637aa ]

do_tls_setsockopt_conf() copies the cipher-specific part of the crypto info to crypto_info + 1, where crypto_info points at the 4-byte info member of union tls_crypto_context. When optval is a kernel sockptr, copy_from_sockptr_offset() is a memcpy(), and FORTIFY_SOURCE bounds the destination by that member:

  [    6.948348] memcpy: detected field-spanning write (size 52) of single field "dst" at include/linux/sockptr.h:49 (size 0)
  [    6.948480] WARNING: include/linux/sockptr.h:49 at tls_setsockopt+0x9b2/0xa30, CPU#1: init/1
  [    7.001355] Call Trace:
  [    7.003146]  do_sock_setsockopt+0xb0/0x190
  [    7.003975]  __sys_setsockopt+0x76/0xc0
  [    7.005368]  do_syscall_64+0xda/0x4b0

tls_setsockopt() gets a kernel sockptr whenever a cgroup setsockopt BPF program is attached, even one that leaves the option alone, because __cgroup_bpf_run_filter_setsockopt() passes optval on in a kernel buffer. With a no-op program on the root cgroup, a plain TLS_TX setsockopt() with AES-GCM-256 triggers the warning above on an x86_64 build with CONFIG_FORTIFY_SOURCE.

Copy into the union at offset sizeof(struct tls_crypto_info) instead. crypto_ctx already points at the right union for both the first set and the TLS 1.3 rekey (tmp) case, and the address is unchanged.

Fixes a7b75c5a8c41 ("net: pass a sockptr_t into ->setsockopt")
---
 net/tls/tls_main.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
net/tls/tls_main.c +2 -2
index 2d1cde3f61886..f13faafe58d20 100644
@@ -701,8 +701,8 @@ static int do_tls_setsockopt_conf(struct sock *sk, sockptr_t optval,
 		goto err_crypto_info;
 	}
 
-	rc = copy_from_sockptr_offset(crypto_info + 1, optval,
-				      sizeof(*crypto_info),
+	rc = copy_from_sockptr_offset((u8 *)crypto_ctx + sizeof(*crypto_info),
+				      optval, sizeof(*crypto_info),
 				      optlen - sizeof(*crypto_info));
 	if (rc) {
 		rc = -EFAULT;
Signature · 1 line
2.53.0
author maintainer
#2409 lore raw

PATCH 2386/2651 net/sched: etf: initialise the sock_exterr_skb before filling it

In reply to Greg Kroah-Hartman

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

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

From: Dudu Lu <[email protected]>

[ Upstream commit 7076f684d5132e6a6145e1da2fa74771ecd052e5 ]

report_sock_error() clones the transmitted skb, overlays a struct sock_exterr_skb on its control block and fills in the seven struct sock_extended_err fields, but never clears addr_offset and port. skb_clone() copies cb[] verbatim, so the errqueue entry carries the TX skb's stale control block to the receive side, and the ipv4 error-queue reader trusts those bytes:

net/ipv4/ip_sockglue.c:556

	sin->sin_addr.s_addr = *(__be32 *)(skb_network_header(skb) +
					   serr->addr_offset);
	sin->sin_port = serr->port;

The gate that is supposed to guard that read only asks whether an address was requested at all:

net/ipv4/ip_sockglue.c:484

	return serr->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
	       serr->ee.ee_origin == SO_EE_ORIGIN_LOCAL || serr->port;

SO_EE_ORIGIN_TXTIME is neither ICMP nor LOCAL, so for sch_etf the gate is decided by serr->port alone -- by the stale byte pair. When it is non-zero the reader dereferences skb_network_header() + addr_offset with an arbitrary offset. On the TCP path cb[40..44) is not zero: the transmit path stored delivered_mstamp there (tcp_rate_skb_sent()), which is exactly where addr_offset/port sit in the arm64 struct layout.

Reached with an unmodified 7.3-rc4 (arm64, KASAN, in-tree modules): a TCP socket enables TX-timestamp error reporting (SO_TXTIME with SOF_TXTIME_REPORT_ERRORS), a sch_etf qdisc drops the packet, and a recvmsg() reaches ip_recv_error():

  BUG: KASAN: slab-out-of-bounds in ip_recv_error+0x970/0xa0c
  Read of size 4 at addr ffff0000158ffdd5 by task A-227-A227-1_S2/113
  ip_recv_error+0x970/0xa0c
  inet_recv_error+0x94/0xdc
  tcp_recvmsg+0x378/0x408
  ...
  The buggy address is located 149 bytes to the right of
  allocated 704-byte region

Zero the whole overlay rather than the two fields individually: the errqueue entry is handed to the receive side as a self-contained record, which is what every other producer in the tree already does (sch_etf was the only error-queue producer that cleared neither field). This does not change what the in-tree selftest observes -- so_txtime.c reads only ee_origin/ee_errno/ee_code/ee_data/ee_info, never msg_name or sin_port.

Fixes 4b15c7075352 ("net/sched: Make etf report drops on error_queue")
---
 net/sched/sch_etf.c | 1 +
 1 file changed, 1 insertion(+)
net/sched/sch_etf.c +1 -0
index ada87a81da6ac..aaafcf640bc7e 100644
@@ -147,6 +147,7 @@ static void report_sock_error(struct sk_buff *skb, u32 err, u8 code)
 		return;
 
 	serr = SKB_EXT_ERR(clone);
+	memset(serr, 0, sizeof(*serr));
 	serr->ee.ee_errno = err;
 	serr->ee.ee_origin = SO_EE_ORIGIN_TXTIME;
 	serr->ee.ee_type = 0;
Signature · 1 line
2.53.0
author maintainer
#2410 lore raw

PATCH 2387/2651 scsi: elx: libefc: Fix resource leak in efcport_init() error path

In reply to Greg Kroah-Hartman

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

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

From: Haotian Zhang <[email protected]>

[ Upstream commit b4bd078b78c248d4263a1da7033cbe7a74ce0e12 ]

efcport_init() creates efc->node_pool and efc->node_dma_pool before allocating efc->els_io_pool. When the latter allocation fails it returns -ENOMEM without releasing the node dma pool or the node pool, leaking both. The caller efct_efclib_config() only logs the error and efct_device_attach() failure path never calls efcport_destroy(), so the resources are never freed.

Destroy node_dma_pool and node_pool before returning from the els_io_pool allocation failure path.

Fixes d7b71fd2195e ("scsi: elx: libefc: Emulex FC discovery library APIs and definitions")
Assisted-by DeepSeek-V4.1-Flash
---
 drivers/scsi/elx/libefc/efclib.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/scsi/elx/libefc/efclib.c +2 -0
index dd3e3d0a47614..ceec0e2a0266a 100644
@@ -50,6 +50,8 @@ int efcport_init(struct efc *efc)
 						sizeof(struct efc_els_io_req));
 	if (!efc->els_io_pool) {
 		efc_log_err(efc, "Can't allocate els io pool\n");
+		dma_pool_destroy(efc->node_dma_pool);
+		mempool_destroy(efc->node_pool);
 		return -ENOMEM;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#2411 lore raw

PATCH 2388/2651 scsi: ufs: qcom: Power down UFS during system suspend on Milos

In reply to Greg Kroah-Hartman

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

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

From: Alexander Koskovich <[email protected]>

[ Upstream commit fb2a238f15f0fc2dacd12f8847b0ec0a1cf7ccac ]

On Milos the UFS PHY GDSC is turned off on every system suspend and the PHY loses its register state, so exiting hibern8 on resume fails:

ufshcd-qcom 1d84000.ufshc: pwr ctrl cmd 0x18 with (MIBattribute 0x0, mode 0x0) failed, host upmcrs:0x5 ufshcd-qcom 1d84000.ufshc: ufshcd_uic_hibern8_exit: hibern8 exit failed. ret = 5 ufshcd-qcom 1d84000.ufshc: __ufshcd_wl_resume: hibern8 exit failed 5

Set no_phy_retention so the controller and device are powered down during system suspend and the link is brought up again on resume.

---
 drivers/ufs/host/ufs-qcom.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/ufs/host/ufs-qcom.c +5 -0
index 954be9343f42a..08f83d789e46e 100644
@@ -3001,6 +3001,10 @@ static void ufs_qcom_remove(struct platform_device *pdev)
 		platform_device_msi_free_irqs_all(hba->dev);
 }
 
+static const struct ufs_qcom_drvdata ufs_qcom_milos_drvdata = {
+	.no_phy_retention = true,
+};
+
 static const struct ufs_qcom_drvdata ufs_qcom_sm8550_drvdata = {
 	.quirks = UFSHCD_QUIRK_BROKEN_LSDBS_CAP,
 	.no_phy_retention = true,
@@ -3012,6 +3016,7 @@ static const struct ufs_qcom_drvdata ufs_qcom_sa8255p_drvdata = {
 
 static const struct of_device_id ufs_qcom_of_match[] __maybe_unused = {
 	{ .compatible = "qcom,ufshc" },
+	{ .compatible = "qcom,milos-ufshc", .data = &ufs_qcom_milos_drvdata },
 	{ .compatible = "qcom,sm8550-ufshc", .data = &ufs_qcom_sm8550_drvdata },
 	{ .compatible = "qcom,sm8650-ufshc", .data = &ufs_qcom_sm8550_drvdata },
 	{ .compatible = "qcom,sa8255p-ufshc", .data = &ufs_qcom_sa8255p_drvdata },
Signature · 1 line
2.53.0
author maintainer
#2412 lore raw

PATCH 2389/2651 selftests/bpf: Test freeing a struct_ops map under a running prog

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit a451867eb5f645a199d0f70cb2b1f541e07f33ec ]

st_ops_assoc_in_timer_no_uref drops every reference to the struct_ops map while a timer callback of its prog calls .test_1 through the association, and checks that the callback ends up with no struct_ops.

The timer first fires 500ms later and .test_1 returns right away, so the callback hardly ever runs .test_1 while the map is freed, and the test can't catch a map that is freed under a running .test_1.

Add st_ops_assoc_in_timer_free, which starts the timer right away, restarts it with no delay until the association is gone, and makes .test_1 spin in bpf_loop() when the timer callback calls it. Share the steps of st_ops_assoc_in_timer_no_uref with it through a helper, which stops when associating or running syscall_prog fails instead of waiting for a timer that never starts.

st_ops_assoc_in_timer_free run in a loop on kernels of the same bpf-next commit with KASAN enabled, x86_64 VM with 32 vCPUs, without and with the previous fix:

without the fix with the fix
outcome Oops (int3) on run 1 100 of 100 passed, median 0.28 s

Stable-dep-of: ac3df711a428 ("selftests/bpf: Wait for the struct_ops map to be freed in assoc_in_timer")

---
 .../bpf/prog_tests/test_struct_ops_assoc.c    | 37 ++++++++++++++++---
 .../bpf/progs/struct_ops_assoc_in_timer.c     | 16 ++++++++
 2 files changed, 47 insertions(+), 6 deletions(-)
tools/testing/selftests/bpf/prog_tests/test_struct_ops_assoc.c +31 -6
index 461ded7223515..6c85d368bf167 100644
@@ -136,7 +136,8 @@ static void test_st_ops_assoc_in_timer(void)
 	struct_ops_assoc_in_timer__destroy(skel);
 }
 
-static void test_st_ops_assoc_in_timer_no_uref(void)
+static void run_st_ops_assoc_in_timer_no_uref(int timer_ns, int wait_map_free,
+					      int spin_loops)
 {
 	struct struct_ops_assoc_in_timer *skel = NULL;
 	struct bpf_link *link;
@@ -148,7 +149,8 @@ static void test_st_ops_assoc_in_timer_no_uref(void)
 
 	err = bpf_program__assoc_struct_ops(skel->progs.syscall_prog,
 					    skel->maps.st_ops_map, NULL);
-	ASSERT_OK(err, "bpf_program__assoc_struct_ops");
+	if (!ASSERT_OK(err, "bpf_program__assoc_struct_ops"))
+		goto out;
 
 	link = bpf_map__attach_struct_ops(skel->maps.st_ops_map);
 	if (!ASSERT_OK_PTR(link, "bpf_map__attach_struct_ops"))
@@ -157,12 +159,18 @@ static void test_st_ops_assoc_in_timer_no_uref(void)
 	/*
 	 * Run .test_1 by calling kfunc bpf_kfunc_multi_st_ops_test_1_prog_arg() and checks
 	 * the return value. .test_1 will also schedule timer_cb that runs .test_1 again.
-	 * timer_cb will run 500ms after syscall_prog runs, when the user space no longer
-	 * holds a reference to st_ops_map.
+	 * timer_cb will run timer_ns after syscall_prog runs and, with wait_map_free, every
+	 * timer_ns after that until the map is freed. With 500ms, it first runs when the
+	 * user space no longer holds a reference to st_ops_map.
 	 */
-	skel->bss->timer_ns = 500000000;
+	skel->bss->timer_ns = timer_ns;
+	skel->bss->wait_map_free = wait_map_free;
+	skel->bss->spin_loops = spin_loops;
 	err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.syscall_prog), NULL);
-	ASSERT_OK(err, "bpf_prog_test_run_opts");
+	if (!ASSERT_OK(err, "bpf_prog_test_run_opts")) {
+		bpf_link__destroy(link);
+		goto out;
+	}
 
 	/* Detach and close struct_ops map to cause it to be freed */
 	bpf_link__destroy(link);
@@ -178,6 +186,21 @@ static void test_st_ops_assoc_in_timer_no_uref(void)
 	struct_ops_assoc_in_timer__destroy(skel);
 }
 
+static void test_st_ops_assoc_in_timer_no_uref(void)
+{
+	run_st_ops_assoc_in_timer_no_uref(500000000, 0, 0);
+}
+
+/*
+ * Keep calling .test_1 through the association from the timer callback, and
+ * stay in it for a while each time, while the map is being freed. The map
+ * must not be freed under a running .test_1.
+ */
+static void test_st_ops_assoc_in_timer_free(void)
+{
+	run_st_ops_assoc_in_timer_no_uref(0, 1, 1 << 20);
+}
+
 void test_struct_ops_assoc(void)
 {
 	if (test__start_subtest("st_ops_assoc"))
@@ -188,4 +211,6 @@ void test_struct_ops_assoc(void)
 		test_st_ops_assoc_in_timer();
 	if (test__start_subtest("st_ops_assoc_in_timer_no_uref"))
 		test_st_ops_assoc_in_timer_no_uref();
+	if (test__start_subtest("st_ops_assoc_in_timer_free"))
+		test_st_ops_assoc_in_timer_free();
 }
tools/testing/selftests/bpf/progs/struct_ops_assoc_in_timer.c +16 -0
index 0bed49e9f2170..47a44c8e8b114 100644
@@ -25,6 +25,13 @@ int test_err;
 int timer_ns;
 int timer_test_1_ret;
 int timer_cb_run;
+int wait_map_free;
+int spin_loops;
+
+static int spin(u32 i, void *ctx)
+{
+	return 0;
+}
 
 __noinline static int timer_cb(void *map, int *key, struct bpf_timer *timer)
 {
@@ -34,6 +41,12 @@ __noinline static int timer_cb(void *map, int *key, struct bpf_timer *timer)
 	timer_test_1_ret = bpf_kfunc_multi_st_ops_test_1_assoc(&args);
 	recur--;
 
+	/* Try again later until the map is freed */
+	if (wait_map_free && timer_test_1_ret != -1) {
+		bpf_timer_start(timer, timer_ns, 0);
+		return 0;
+	}
+
 	timer_cb_run++;
 
 	return 0;
@@ -53,6 +66,9 @@ int BPF_PROG(test_1, struct st_ops_args *args)
 		bpf_timer_init(timer, &array_map, 1);
 		bpf_timer_set_callback(timer, timer_cb);
 		bpf_timer_start(timer, timer_ns, 0);
+	} else if (spin_loops) {
+		/* Stay in the trampoline while the map may be freed */
+		bpf_loop(spin_loops, spin, NULL, 0);
 	}
 
 	return MAP_MAGIC;
Signature · 1 line
2.53.0
author maintainer
#2413 lore raw

PATCH 2390/2651 selftests/bpf: Wait for the struct_ops map to be freed in assoc_in_timer

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit ac3df711a428a9ff4277100ee26c6765e8f80a3b ]

st_ops_assoc_in_timer_no_uref runs .test_1, which starts a timer to call it again 500ms later, drops every reference to the struct_ops map, and expects the timer callback to find no struct_ops associated with its program anymore.

The association goes away only when the last reference to the map is dropped. syscall_prog holds one through its own association and drops it only when it is freed, in a work item after an RCU tasks trace grace period. With other tests running in parallel, that can take longer than 500ms, and the callback still reaches the struct_ops and gets MAP_MAGIC instead of -1.

Have the timer callback restart the timer until the map is gone, as it does for st_ops_assoc_in_timer_free. Calling the struct_ops through the association until then is safe, as the map is freed only after a grace period that follows clearing the association.

st_ops_assoc_in_timer_no_uref run 100 times with test_progs -j32 running in the background, on a KASAN kernel with the fix, x86_64 VM with 32 vCPUs, before and after this patch:

before after
outcome 2 of 100 failed (MAP_MAGIC) 0 of 100 failed (MAP_MAGIC)

---
 tools/testing/selftests/bpf/prog_tests/test_struct_ops_assoc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/bpf/prog_tests/test_struct_ops_assoc.c +1 -1
index 6c85d368bf167..9b646d134a45e 100644
@@ -188,7 +188,7 @@ static void run_st_ops_assoc_in_timer_no_uref(int timer_ns, int wait_map_free,
 
 static void test_st_ops_assoc_in_timer_no_uref(void)
 {
-	run_st_ops_assoc_in_timer_no_uref(500000000, 0, 0);
+	run_st_ops_assoc_in_timer_no_uref(500000000, 1, 0);
 }
 
 /*
Signature · 1 line
2.53.0
author maintainer
#2414 lore raw

PATCH 2391/2651 bpf: Propagate btf_add_type() errors in btf_check_all_metas()

In reply to Greg Kroah-Hartman

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

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

From: Feng Yang <[email protected]>

[ Upstream commit fb2b27d214c3b88d926a303267dd83cfdb428b13 ]

btf_check_all_metas() ignores the return value of btf_add_type(), so a type that could not be registered is silently dropped while the loop keeps walking over the type section.

Both failure modes are reachable:

- -E2BIG. Once the types array reaches its capacity (BTF_MAX_TYPE), every following btf_add_type() fails the same way, so btf_check_all_metas() still returns 0 and the BTF object is created with btf->nr_types capped while hdr->type_len claims more records.

- -ENOMEM. btf->nr_types is not incremented and the array is not grown, so the next type is recorded at the slot of the dropped one and btf->types[] stays off by one with respect to the type ids for all remaining types. btf_type_by_id() then returns the wrong type for those ids for the whole lifetime of the object, and the last type is silently left unresolved.

Propagate the error so that the object is rejected instead.

---
 kernel/bpf/btf.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
kernel/bpf/btf.c +5 -1
index b1adb52e2f310..85b8a667dd547 100644
@@ -5471,6 +5471,7 @@ static int btf_check_all_metas(struct btf_verifier_env *env)
 	struct btf *btf = env->btf;
 	struct btf_header *hdr;
 	void *cur, *end;
+	int err;
 
 	hdr = &btf->hdr;
 	cur = btf->nohdr_data + hdr->type_off;
@@ -5485,7 +5486,10 @@ static int btf_check_all_metas(struct btf_verifier_env *env)
 		if (meta_size < 0)
 			return meta_size;
 
-		btf_add_type(env, t);
+		err = btf_add_type(env, t);
+		if (err)
+			return err;
+
 		cur += meta_size;
 		env->log_type_id++;
 	}
Signature · 1 line
2.53.0
author maintainer
#2415 lore raw

PATCH 2392/2651 bpf: Use memmove() to load bytes from an skb and an xdp_buff

In reply to Greg Kroah-Hartman

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

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

From: Ayushman Rout <[email protected]>

[ Upstream commit b93cf2c8a0552b544e90e25802e4bf989987d29d ]

bpf_dynptr_read() on an skb or xdp dynptr ends in bpf_skb_load_bytes() or bpf_xdp_load_bytes(). The destination can be a slice of the same packet, so it can overlap the source, which memcpy() does not allow. On x86 with FSRM memcpy() copies forward, so a destination above the source gets the first bytes repeated:

  p = bpf_dynptr_slice_rdwr(&ptr, 8, NULL, 64);
  bpf_dynptr_read(p, 64, &ptr, 0, 0);

leaves bytes 8-71 of the packet as bytes 0-7 repeated, not bytes 0-63. Reproduced with BPF_PROG_TEST_RUN on both an xdp and a tc program.

Use memmove(), as the store side does since commit 1db084f42884 ("bpf: Use memmove() to store bytes in an skb") and commit ab08863c58b1 ("bpf: Use memmove() to store bytes in an xdp_buff"). A read that spans xdp frags still goes through bpf_xdp_copy_buf() and is not changed here.

bpf_skb_load_bytes_relative() has the same pattern and is reachable from tc and sk_filter programs, so use memmove() there as well. Reproduced with BPF_PROG_TEST_RUN on a tc program: loading into a slice at offset 8 gave wrong bytes before the change and correct bytes after.

Fixes 2012c867c800 ("bpf: verifier: Accept dynptr mem as mem in helpers")
---
 net/core/filter.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
net/core/filter.c +3 -3
index 9e577495eef19..0ad1507759ded 100644
@@ -1789,7 +1789,7 @@ BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
 	if (unlikely(!ptr))
 		goto err_clear;
 	if (ptr != to)
-		memcpy(to, ptr, len);
+		memmove(to, ptr, len);
 
 	return 0;
 err_clear:
@@ -1871,7 +1871,7 @@ BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
 	ptr = start + offset;
 
 	if (likely(ptr + len <= end)) {
-		memcpy(to, ptr, len);
+		memmove(to, ptr, len);
 		return 0;
 	}
 
@@ -4305,7 +4305,7 @@ BPF_CALL_4(bpf_xdp_load_bytes, struct xdp_buff *, xdp, u32, offset,
 	if (!ptr)
 		bpf_xdp_copy_buf(xdp, offset, buf, len, false);
 	else
-		memcpy(buf, ptr, len);
+		memmove(buf, ptr, len);
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#2416 lore raw

PATCH 2393/2651 bpf: Remove nmi_uaccess_okay() check in bpf_send_signal_common()

In reply to Greg Kroah-Hartman

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

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

From: Aditya Sharma <[email protected]>

[ Upstream commit 93bd472336ac2424f5f3cf05cbb24e02242343b7 ]

nmi_uaccess_okay() takes no task argument and is a statement about current. When commit 6280cf718db0 ("bpf: Implement bpf_send_signal_task() kfunc") made the PF_KTHREAD/PF_EXITING and is_global_init() test the supplied task, nmi_uaccess_okay() was left testing current.

As a result bpf_send_signal_task() returns -EPERM whenever the calling context happens to be a kernel thread, regardless of which task the signal is aimed at. The same call with the same target succeeds or fails depending only on what the CPU was running:

bpf_send_signal_task() from tp_btf/workqueue_execute_start : -EPERM
bpf_send_signal_task() from tp_btf/sys_enter : 0

The check was carried over from bpf_probe_write_user() when bpf_send_signal() was added in commit 8b401f9ed244 ("bpf: implement bpf_send_signal() helper"). There it guards a user memory write, but bpf_send_signal_common() does no user memory access, so the check has nothing to guard here. It is also already a no-op outside x86.

Remove it, and drop the part of the comment above it that described the memory access checks, as none remain.

---
 kernel/trace/bpf_trace.c | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)
kernel/trace/bpf_trace.c +3 -6
index d649aaf13553e..08ddadd80056c 100644
@@ -867,15 +867,12 @@ static int bpf_send_signal_common(u32 sig, enum pid_type type, struct task_struc
 		siginfo = &info;
 	}
 
-	/* Similar to bpf_probe_write_user, task needs to be
-	 * in a sound condition and kernel memory access be
-	 * permitted in order to send signal to the current
-	 * task.
+	/*
+	 * Similar to bpf_probe_write_user, task needs to be
+	 * in a sound condition.
 	 */
 	if (unlikely(task->flags & (PF_KTHREAD | PF_EXITING)))
 		return -EPERM;
-	if (unlikely(!nmi_uaccess_okay()))
-		return -EPERM;
 	/* Task should not be pid=1 to avoid kernel panic. */
 	if (unlikely(is_global_init(task)))
 		return -EPERM;
Signature · 1 line
2.53.0
author maintainer
#2417 lore raw

PATCH 2394/2651 kernel/reboot: avoid potential deadlocks during suspension

In reply to Greg Kroah-Hartman

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

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

From: Edward Adam Davis <[email protected]>

[ Upstream commit 66644b992f25f6a33775788c8b69a8bb3d41ad67 ]

Invoking reboot with LINUX_REBOOT_CMD_SW_SUSPEND causes kernel/reboot.c to acquire system_transition_mutex and invoke hibernate(). hibernate() calls lock_system_sleep(), which sets PF_NOFREEZE on current and attempts to acquire system_transition_mutex again, potentially hitting:

WARNING: possible recursive locking detected
--------------------------------------------
syz.3.5755/5950 is trying to acquire lock:
ffffffff8fc04760 (system_transition_mutex){+.+.}-{4:4}, at: lock_system_sleep+0x49/0x70 kernel/power/main.c:71

but task is already holding lock:
ffffffff8fc04760 (system_transition_mutex){+.+.}-{4:4}, at: __do_sys_reboot kernel/reboot.c:774 [inline] ffffffff8fc04760 (system_transition_mutex){+.+.}-{4:4}, at: __se_sys_reboot+0x223/0x460 kernel/reboot.c:738

other info that might help us debug this:

 Possible unsafe locking scenario:
       CPU0
       ----

lock(system_transition_mutex);
lock(system_transition_mutex);

*** DEADLOCK ***

May be due to missing lock nesting notation

locks held by syz.3.5755/5950: 1, last CPU#0:
#0: ffffffff8fc04760 (system_transition_mutex){+.+.}-{4:4}, at: __do_sys_reboot kernel/reboot.c:774 [inline] #0: ffffffff8fc04760 (system_transition_mutex){+.+.}-{4:4}, at: __se_sys_reboot+0x223/0x460 kernel/reboot.c:738

Call Trace:
 lock_system_sleep+0x49/0x70 kernel/power/main.c:71
 hibernate+0x162/0x680 kernel/power/hibernate.c:784
 __do_sys_reboot kernel/reboot.c:816 [inline]

Move the suspension operation outside the scope protected by lock system_transition_mutex.

---
 kernel/reboot.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/reboot.c +2 -2
index 5b9691f45f5f0..bc2716677a6c5 100644
@@ -813,8 +813,8 @@ SYSCALL_DEFINE4(reboot, int, magic1, int, magic2, unsigned int, cmd,
 
 #ifdef CONFIG_HIBERNATION
 	case LINUX_REBOOT_CMD_SW_SUSPEND:
-		ret = hibernate();
-		break;
+		mutex_unlock(&system_transition_mutex);
+		return hibernate();
 #endif
 
 	default:
Signature · 1 line
2.53.0
author maintainer
#2418 lore raw

PATCH 2395/2651 profiling: fix sampling step on 64-bit big-endian systems

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit b1d68946a08313895f352af5336623d29739c299 ]

read_profile() stores the sampling step in an unsigned long but copies only four bytes to userspace. On 64-bit big-endian systems (not common obviously), this copies the upper 32 bits and discards the rest, causing /proc/profile to report zero for normal shift values.

Cast to unsigned int so we get the correct 4 bytes, while keeping the shift calculation in unsigned long.

A small C reproducer under qemu-s390x reproduced this and proved the fix works for prof_shift=2.

Fixes 2d186afd04d6 ("profiling: fix shift-out-of-bounds bugs")
---
 kernel/profile.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/profile.c +1 -1
index 1fcf1adcf4eb0..e7defa90a34c9 100644
@@ -156,7 +156,7 @@ read_profile(struct file *file, char __user *buf, size_t count, loff_t *ppos)
 	unsigned long p = *ppos;
 	ssize_t read;
 	char *pnt;
-	unsigned long sample_step = 1UL << prof_shift;
+	unsigned int sample_step = (unsigned int)(1UL << prof_shift);
 
 	if (p >= (prof_len+1)*sizeof(unsigned int))
 		return 0;
Signature · 1 line
2.53.0
author maintainer
#2419 lore raw

PATCH 2396/2651 scripts/gdb: fix radix tree lookup pointer handling

In reply to Greg Kroah-Hartman

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

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

From: Ting-Han Hou <[email protected]>

[ Upstream commit 66d190b072b4e261aff35debb53872ace9b80628 ]

Patch series "scripts/gdb: fix radix tree lookup and stack depot diagnostic", v2.

Two scripts/gdb fixes.

Patch 1 fixes $lx_radix_tree_lookup(), which dereferenced slot contents as if they were node pointers. v2 also handles the XArray sibling, retry and zero entries that Sashiko pointed out: they carry the internal tag but are not node pointers, and the v1 patch raised a GDB MemoryError on them. Large folios in the page cache make sibling entries common, so this was worth fixing rather than documenting.

Patch 2 is unchanged from v1 apart from being resent with git send-email, since the earlier copy was word-wrapped by the mail client. Sorry about that.

Both patches are tested against standalone GCC-built fixtures that use the kernel struct layouts (details below the --- line of each patch), not against a running kernel.

This patch (of 2):

lookup() casts each slot to a pointer to a node pointer and then dereferences it. Since the slot already contains an entry pointer, this reads the entry's contents as another pointer instead of returning the entry itself. Internal entries also keep their tag bits when descending, so multi-level trees are read from the wrong address and $lx_radix_tree_lookup() fails with a memory error.

Sibling, retry and zero entries carry the same internal tag but are small integers rather than node pointers, so the tag alone must not decide whether to descend. A page cache populated with large folios has a sibling entry in every slot but the first of each folio.

Walk the tree the way xas_load() does: descend only through entries that xa_is_node() would accept, follow sibling entries to the canonical slot of a multi-index entry, and treat retry and zero entries like empty slots since they hold no data. Remove the explicit shift counter, as traversal now follows the entry type.

Fixes b7235d6bb516 ("scripts/gdb: add a Radix Tree Parser")
Assisted-by LLM
Cc Jan Kiszka <[email protected]>
Cc Kieran Bingham <[email protected]>
Cc Kuan-Ying Lee <[email protected]>
---
 scripts/gdb/linux/radixtree.py | 66 ++++++++++++++++++++--------------
 1 file changed, 40 insertions(+), 26 deletions(-)
scripts/gdb/linux/radixtree.py +40 -26
index bc2954e45c327..8ce9936dfa50f 100644
@@ -27,6 +27,24 @@ def entry_to_node(node):
     indirect_ptr = node.cast(long_type) & ~constants.LX_RADIX_TREE_INTERNAL_NODE
     return indirect_ptr.cast(radix_tree_node_type.get_type().pointer())
 
+def is_node(entry):
+    # Like xa_is_node(): internal entries below 4096 are sibling, retry
+    # or zero entries rather than pointers to a struct xa_node.
+    ulong_type = utils.get_ulong_type()
+    return is_internal_node(entry) and entry.cast(ulong_type) > 4096
+
+def is_sibling(entry):
+    # Like xa_is_sibling(): a multi-index entry occupies several slots,
+    # and all but the first hold a sibling entry that encodes the offset
+    # of the first one.
+    ulong_type = utils.get_ulong_type()
+    return is_internal_node(entry) and entry.cast(ulong_type) < \
+        xa_mk_internal(constants.LX_RADIX_TREE_MAP_SIZE - 1)
+
+def sibling_offset(entry):
+    ulong_type = utils.get_ulong_type()
+    return int(entry.cast(ulong_type)) >> 2
+
 def node_maxindex(node):
     return (constants.LX_RADIX_TREE_MAP_SIZE << node['shift']) - 1
 
@@ -40,39 +58,35 @@ def resolve_root(root):
 
 def lookup(root, index):
     root = resolve_root(root)
-    node = root['xa_head']
-    if node == 0:
-        return None
+    entry = root['xa_head']
 
-    if not (is_internal_node(node)):
-        if (index > 0):
+    if is_node(entry):
+        node = entry_to_node(entry)
+        if index > node_maxindex(node):
             return None
-        return node
 
-    node = entry_to_node(node)
-    maxindex = node_maxindex(node)
-
-    if (index > maxindex):
-        return None
-
-    shift = node['shift'] + constants.LX_RADIX_TREE_MAP_SHIFT
-
-    while True:
-        offset = (index >> node['shift']) & constants.LX_RADIX_TREE_MAP_MASK
-        slot = node['slots'][offset]
+        # Walk down the tree like xas_load() does.
+        while True:
+            offset = (index >> node['shift']) & constants.LX_RADIX_TREE_MAP_MASK
+            entry = node['slots'][offset]
 
-        if slot == 0:
-            return None
+            while is_sibling(entry):
+                entry = node['slots'][sibling_offset(entry)]
+                if node['shift'] and is_node(entry):
+                    # xas_descend() turns this into a retry entry.
+                    return None
 
-        node = slot.cast(node.type.pointer()).dereference()
-        if node == 0:
-            return None
+            if not is_node(entry) or node['shift'] == 0:
+                break
+            node = entry_to_node(entry)
+    elif index > 0:
+        return None
 
-        shift -= constants.LX_RADIX_TREE_MAP_SHIFT
-        if (shift <= 0):
-            break
+    # Empty slots and retry or zero entries hold no data.
+    if entry == 0 or is_internal_node(entry):
+        return None
 
-    return node
+    return entry
 
 def descend(parent, index):
     offset = (index >> int(parent["shift"])) & constants.LX_RADIX_TREE_MAP_MASK
Signature · 1 line
2.53.0
author maintainer
#2420 lore raw

PATCH 2397/2651 scripts/gdb: fix stack depot out-of-bounds diagnostic

In reply to Greg Kroah-Hartman

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

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

From: Ting-Han Hou <[email protected]>

[ Upstream commit b6232ca8d194c60ee603586e42b5ea584d4b7be9 ]

The pool_index field was renamed to pool_index_plus_1, but the out-of-bounds diagnostic in stack_depot_fetch() still accesses the old field. Looking up a handle whose pool index is outside stack_pools therefore raises "There is no member named pool_index" instead of printing the diagnostic and returning an empty result.

Use the already decoded pool_index variable in the diagnostic.

Fixes 9d938f40b228 ("scripts/gdb: rename pool_index to pool_index_plus_1")
Assisted-by LLM
Cc Jan Kiszka <[email protected]>
Cc Kieran Bingham <[email protected]>
Cc Kuan-Ying Lee <[email protected]>
---
 scripts/gdb/linux/stackdepot.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/gdb/linux/stackdepot.py +1 -1
index 37313a5a51a0d..aaa18af25cd12 100644
@@ -39,7 +39,7 @@ def stack_depot_fetch(handle):
 
     pool_index = parts['pool_index_plus_1'] - 1
     if pool_index >= pools_num:
-        gdb.write("pool index %d out of bounds (%d) for stack id 0x%08x\n" % (parts['pool_index'], pools_num, handle))
+        gdb.write("pool index %d out of bounds (%d) for stack id 0x%08x\n" % (pool_index, pools_num, handle))
         return gdb.Value(0), 0
 
     stack_pools = gdb.parse_and_eval('stack_pools')
Signature · 1 line
2.53.0
author maintainer
#2421 lore raw

PATCH 2398/2651 zram: fix short reads from block_state

In reply to Greg Kroah-Hartman

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

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

From: Pooyan Azad <[email protected]>

[ Upstream commit 372012202260db088b489ed00059c4571a602552 ]

read_block_state() formats each entry directly into the buffer supplied by read(). If the remaining buffer is too small for one complete record, snprintf() returns the full record length and the function stops without copying data or advancing the file position. A read from this debugfs file which is smaller than a record therefore returns zero at a non-EOF position and cannot make progress.

Convert block_state to seq_file so formatted records are buffered independently of the userspace read size. Keep dev_lock held across each seq_file iteration and continue to protect individual entries with their slot locks.

---
 drivers/block/zram/zram_drv.c | 102 +++++++++++++++++-----------------
 1 file changed, 52 insertions(+), 50 deletions(-)
drivers/block/zram/zram_drv.c +52 -50
index 4ba0f77b2abd8..30f11e36d19c7 100644
@@ -1547,68 +1547,70 @@ static void zram_debugfs_destroy(void)
 	debugfs_remove_recursive(zram_debugfs_root);
 }
 
-static ssize_t read_block_state(struct file *file, char __user *buf,
-				size_t count, loff_t *ppos)
+static void *zram_block_state_start(struct seq_file *seq, loff_t *pos)
 {
-	char *kbuf;
-	unsigned long index;
-	ssize_t written = 0;
-	struct zram *zram = file->private_data;
+	struct zram *zram = seq->private;
 	unsigned long nr_pages;
 
-	kbuf = kvmalloc(count, GFP_KERNEL);
-	if (!kbuf)
-		return -ENOMEM;
-
-	guard(rwsem_read)(&zram->dev_lock);
-	if (!init_done(zram)) {
-		kvfree(kbuf);
-		return -EINVAL;
-	}
+	down_read(&zram->dev_lock);
+	if (!init_done(zram))
+		return ERR_PTR(-EINVAL);
 
 	nr_pages = zram->disksize >> PAGE_SHIFT;
+	if (*pos >= nr_pages)
+		return NULL;
 
-	for (index = *ppos; index < nr_pages; index++) {
-		int copied;
+	return pos;
+}
 
-		slot_lock(zram, index);
-		if (!slot_allocated(zram, index))
-			goto next;
+static void *zram_block_state_next(struct seq_file *seq, void *v, loff_t *pos)
+{
+	struct zram *zram = seq->private;
+	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
 
-		copied = snprintf(kbuf + written, count,
-			"%12lu %12u.%06d %c%c%c%c%c%c\n",
-			index, zram->table[index].attr.ac_time, 0,
-			test_slot_flag(zram, index, ZRAM_SAME) ? 's' : '.',
-			test_slot_flag(zram, index, ZRAM_WB) ? 'w' : '.',
-			test_slot_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
-			test_slot_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
-			get_slot_comp_priority(zram, index) ? 'r' : '.',
-			test_slot_flag(zram, index,
-				       ZRAM_INCOMPRESSIBLE) ? 'n' : '.');
-
-		if (count <= copied) {
-			slot_unlock(zram, index);
-			break;
-		}
-		written += copied;
-		count -= copied;
-next:
-		slot_unlock(zram, index);
-		*ppos += 1;
-	}
+	++*pos;
+	if (*pos >= nr_pages)
+		return NULL;
+
+	return pos;
+}
+
+static void zram_block_state_stop(struct seq_file *seq, void *v)
+{
+	struct zram *zram = seq->private;
 
-	if (copy_to_user(buf, kbuf, written))
-		written = -EFAULT;
-	kvfree(kbuf);
+	up_read(&zram->dev_lock);
+}
+
+static int zram_block_state_show(struct seq_file *seq, void *v)
+{
+	struct zram *zram = seq->private;
+	unsigned long index = *(loff_t *)v;
+
+	slot_lock(zram, index);
+	if (slot_allocated(zram, index)) {
+		seq_printf(seq, "%12lu %12u.%06d %c%c%c%c%c%c\n",
+			   index, zram->table[index].attr.ac_time, 0,
+			   test_slot_flag(zram, index, ZRAM_SAME) ? 's' : '.',
+			   test_slot_flag(zram, index, ZRAM_WB) ? 'w' : '.',
+			   test_slot_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
+			   test_slot_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
+			   get_slot_comp_priority(zram, index) ? 'r' : '.',
+			   test_slot_flag(zram, index,
+					  ZRAM_INCOMPRESSIBLE) ? 'n' : '.');
+	}
+	slot_unlock(zram, index);
 
-	return written;
+	return 0;
 }
 
-static const struct file_operations proc_zram_block_state_op = {
-	.open = simple_open,
-	.read = read_block_state,
-	.llseek = default_llseek,
+static const struct seq_operations zram_block_state_sops = {
+	.start = zram_block_state_start,
+	.next = zram_block_state_next,
+	.stop = zram_block_state_stop,
+	.show = zram_block_state_show,
 };
+DEFINE_SEQ_ATTRIBUTE(zram_block_state);
 
 static void zram_debugfs_register(struct zram *zram)
 {
@@ -1618,7 +1620,7 @@ static void zram_debugfs_register(struct zram *zram)
 	zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
 						zram_debugfs_root);
 	debugfs_create_file("block_state", 0400, zram->debugfs_dir,
-				zram, &proc_zram_block_state_op);
+				zram, &zram_block_state_fops);
 }
 
 static void zram_debugfs_unregister(struct zram *zram)
Signature · 1 line
2.53.0
author maintainer
#2422 lore raw

PATCH 2399/2651 ALSA: us122l: mark hwdep mappings VM_MIXEDMAP

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

mm has recently moved to a strict model which requires any driver which clears VMA_MAYWRITE_BIT to be mapping non-mm-managed memory (VMA_PFNMAP_BIT or VMA_MIXEDMAP_BIT), failing any such mmap() with an error and a kernel warning - see "mm/vma: only allow mmap to clear VMA_MAYWRITE_BIT if not mm-managed".

However, simultaneous to this, commit 71c610aeb177 ("ALSA: us122l: Prevent write upgrades for read mappings") updated us122l to clear VMA_MAYWRITE_BIT without marking the region with either VMA_PFNMAP_BIT or VMA_MIXEDMAP_BIT.

vm_insert_pages() and friends set this automatically, however this driver maps its pre-allocated pages from a fault handler, so never calls these.

Simply set the flag in usb_stream_hwdep_mmap() to resolve the issue. This correctly marks the mapping as one whose pages core mm does not manage, which has no meaningful impact for this driver beyond preventing the mmap() from failing.

---
 sound/usb/usx2y/us122l.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/usb/usx2y/us122l.c +1 -1
index 9b4ec9bdc1383..6e491736ca5ba 100644
@@ -204,7 +204,7 @@ static int usb_stream_hwdep_mmap(struct snd_hwdep *hw,
 	}
 
 	area->vm_ops = &usb_stream_hwdep_vm_ops;
-	vm_flags_set(area, VM_DONTDUMP);
+	vm_flags_set(area, VM_MIXEDMAP | VM_DONTDUMP);
 	if (!read)
 		vm_flags_set(area, VM_DONTEXPAND);
 	area->vm_private_data = us122l;
Signature · 1 line
2.53.0
author maintainer
#2423 lore raw

PATCH 2400/2651 tools/cgroup: sum shrinker object counts across NUMA nodes

In reply to Greg Kroah-Hartman

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

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

From: Ren Tamura <[email protected]>

[ Upstream commit ae2514c95518b39b36fa463d855c74f29c91d064 ]

Each row of a memcg-aware shrinker's debugfs count file contains the cgroup ID followed by one object count per NUMA node. memcg_shrinker.py uses only the first count when sorting and displaying entries.

This undercounts objects on NUMA systems. An entry with counts of 0 and 23 is treated as zero and omitted from the output, even though its total is 23.

Sum all count fields after the cgroup ID so that the displayed totals and sort order account for every node. Single-node input retains the same result.

Fixes d261ea23533b ("tools: add memcg_shrinker.py")
Assisted-by LLM
Cc Roman Gushchin <[email protected]>
---
 tools/cgroup/memcg_shrinker.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/cgroup/memcg_shrinker.py +1 -1
index e81c3017ada96..714772449c6ba 100644
@@ -31,7 +31,7 @@ def scan_shrinkers(shrinker_debugfs):
                     items = line.split(' ')
                     ino = int(items[0])
                     # (count, shrinker, memcg ino)
-                    shrinkers.append((int(items[1]), shrinker, ino))
+                    shrinkers.append((sum(map(int, items[1:])), shrinker, ino))
     return shrinkers
 
 
Signature · 1 line
2.53.0
author maintainer
#2424 lore raw

PATCH 2401/2651 tools/testing/shared: catch a failed posix_memalign()

In reply to Greg Kroah-Hartman

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

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

From: Liam R. Howlett (Google) <[email protected]>

[ Upstream commit c9ed13789061af00d9239f9fab8e246adbed2076 ]

posix_memalign() returns zero or a positive error number and never sets errno, so the checks for a negative return in kmem_cache_alloc_lru() and kmem_cache_alloc_bulk() is not possible. A failed aligned allocation carries on with the pointer unset, into the constructor or the memset().

Test for any non-zero return.

---
 tools/testing/shared/linux.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
tools/testing/shared/linux.c +2 -2
index e0a0693df08f5..a37d2f86d3254 100644
@@ -83,7 +83,7 @@ void *kmem_cache_alloc_lru(struct kmem_cache *cachep, struct list_lru *lru,
 	} else {
 		pthread_mutex_unlock(&cachep->lock);
 		if (cachep->align) {
-			if (posix_memalign(&p, cachep->align, cachep->size) < 0)
+			if (posix_memalign(&p, cachep->align, cachep->size))
 				return NULL;
 		} else {
 			p = malloc(cachep->size);
@@ -191,7 +191,7 @@ bool kmem_cache_alloc_bulk(struct kmem_cache *cachep, gfp_t gfp, size_t size,
 
 			if (cachep->align) {
 				if (posix_memalign(&p[i], cachep->align,
-					       cachep->size) < 0)
+					       cachep->size))
 					break;
 			} else {
 				p[i] = malloc(cachep->size);
Signature · 1 line
2.53.0
author maintainer
#2425 lore raw

PATCH 2402/2651 maple_tree: fix maple_range_64 crashes in RCU mode

In reply to Greg Kroah-Hartman

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

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

From: Dimitris Charisis <[email protected]>

[ Upstream commit baed735a956f2a7badb5436bef6810303034f920 ]

Patch series "maple_tree: fix maple_range_64 crashes in RCU mode", v3.

The patch series fixes two RCU destroy path issues on maple_range_64 nodes. Both arising from the fact that a maple_range_64 node repurposes the last slot to hold metadata when the node is not full. Patch 1 addresses the issues, and patch 2 adds a test used to catch them.

Currently there is no in-tree user of maple_range_64 nodes in RCU mode. All in-tree users of MT_FLAGS_USE_RCU also set MT_FLAGS_ALLOC_RANGE which makes the internal nodes maple_arange_64.

Below is the minimal reproducer used during debugging:

static DEFINE_MTREE(tree);
static int __init maple_fix_init(void)

{
        unsigned long i, j;

        for (i = 10; i < 4000; i++) {
                mt_init_flags(&tree, MT_FLAGS_USE_RCU);

                for (j = 0; j < i; j++) {
                        mtree_insert_range(&tree, j * 10, j * 10 + 9,
                                        xa_mk_value(j), GFP_KERNEL);
                }

                mtree_destroy(&tree);
                rcu_barrier();
        }
        return 0;
}

The splat for the first issue addressed by the first patch is shown below. mt_clear_meta() runs after the slots have been rewritten with raw pointers by mte_dead_leaves(), so it cannot recognize a valid last pointer because the type information is stripped. On my 64-bit LE machine, it clears bytes 248 and 249 of the maple_range_64 which are the two least significant bytes of the last pointer. The lowest byte is already zero, since nodes are 256-byte aligned, but zeroing byte 249 corrupts the pointer.

KASAN catches it as a double-free, because that corrupted pointer happens to land on a node that was freed previously. The splat appears at 226 insertions in the reproducer. This is when the tree has a full root node on a 64-bit build.

==================================================================

  BUG: KASAN: double-free in mt_free_walk+0x138/0x3a0
  Free of addr ffff0000f3d40000 by task swapper/2/0
  [...]
  Call trace:
   [...]
   kmem_cache_free_bulk+0x5b8/0xc18
   mt_free_walk+0x138/0x3a0
   rcu_core+0x5d0/0x1638
   rcu_core_si+0x18/0x30
   [...]

  Allocated by task 1218:
   [...]
   kmem_cache_alloc_from_sheaf_noprof+0xa8/0x2f0
   dst_setup+0x210/0x630
   mas_wr_split+0x568/0x26e0
   mas_wr_store_entry+0x98c/0x1de0
   mas_insert.isra.0+0x3d0/0x5d8
   mtree_insert_range+0xec/0x1c8
   maple_fix_init+0x94/0xff8 [maple_fix_obj]
   [...]

  Freed by task 0:
   [...]
   __kasan_slab_free+0x88/0xb8
   __rcu_free_sheaf_prepare+0x94/0x360
   rcu_free_sheaf+0x30/0x138
   rcu_core+0x5d0/0x1638
   rcu_core_si+0x18/0x30
   [...]

  The buggy address belongs to the object at ffff0000f3d40000
   which belongs to the cache maple_node of size 256
  The buggy address is located 0 bytes inside of
   256-byte region [ffff0000f3d40000, ffff0000f3d40100)

[...]

  Memory state around the buggy address:
   ffff0000f3d3ff00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
   ffff0000f3d3ff80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
  >ffff0000f3d40000: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
                     ^
   ffff0000f3d40080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
   ffff0000f3d40100: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
  ==================================================================

The second issue fixed in the first patch is in the mt_free_walk(). mt_free_walk() descends by checking if the corresponding slot[offset] entry is non-zero. In a maple_range_64 node that has MAPLE_RANGE64_SLOTS-1 valid pointers to child nodes, all slots will be non-zero, since the last slot holds the metadata. Thus, mte_dead_walk() dereferences the metadata as if it were a node and hits the null-ptr-deref as shown in the splat below.

After fixing the first issue, the reproducer reaches this case at 3166 insertions. The affected node is the root on a tree with height 3 and it has 15 valid child nodes on a 64-bit machine. The first fix does not introduce this bug, but it exposes it for the root node because it no longer clears the root metadata. On an unmodified kernel, the same bug exists and is reachable when such a maple_range_64 node appears below the root, where mt_clear_meta() is not called.

Second KASAN splat:

  Unable to handle kernel paging request at virtual address dfff800000000006
  KASAN: null-ptr-deref in range [0x0000000000000030-0x0000000000000037]
  [...]
  Call trace:
   mte_dead_walk+0x78/0x140 (P)
   mt_free_walk+0x1f8/0x3a0
   rcu_core+0x5d0/0x1638
   rcu_core_si+0x18/0x30
   [..]

Both splats are from an arm64 QEMU guest. The test_maple_tree and the userspace suite pass after each patch in the series.

This patch (of 2):

This commit fixes two issues in maple_range_64 nodes under RCU mode. A maple_range_64 node repurposes its last slot to hold metadata whenever the node is not full. Both issues arise from mishandling that last slot.

More specifically the two fixes are:

1. Remove mt_clear_meta() function. mt_clear_meta() decides whether the last slot of a maple_range_64 node holds a child pointer or a struct maple_metadata with the check

        if (unlikely((mte_to_node(next) &&
                      mte_node_type(next))))
                return; /* no metadata, could be node */

The check expects the pointer to be encoded. But the only callsite of mt_clear_meta() is mt_destroy_walk() on the RCU destroy path, and by the time it runs, mte_dead_leaves() has overwritten every slot on a full node with a raw pointer, stripping the type information. Thus, the check above never returns early for a full node as it should. It falls through and then:

           meta->gap = 0;
           meta->end = 0;

zeroes two bytes of a valid child pointer. Later, mt_free_walk() dereferences the corrupted pointer.

Fix this by removing mt_clear_meta() along with its only callsite. mt_clear_meta() is only called for the root of each sub-tree destroyed under RCU. Descendant nodes retain their metadata until they are freed. RCU readers may use the metadata while traversing a node, but do not use cleared metadata to detect that a node has been removed. They detect a dead node via ma_dead_node().

2. Fix invalid memory access in mt_free_walk(). mt_free_walk() descends to the left-most unvisited "parent-of-a-leaf" node by checking the condition:

        if ((offset < mt_slots[type]) &&
            rcu_dereference_protected(slots[offset],
                                      lock_is_held(&rcu_callback_map)))
                slots = mte_dead_walk(&enode, offset);

On a maple_range_64 node with MAPLE_RANGE64_SLOTS-1 children *all* slots are non-NULL. The first MAPLE_RANGE64_SLOTS-1 hold valid pointers to child nodes, and the last slot contains metadata. The above check therefore passes for all offsets, and mte_dead_walk() dereferences the metadata as if it were a node.

To trigger this, a node at least two levels above the leaves has to have exactly MAPLE_RANGE64_SLOTS-1 valid pointers to other nodes. maple_arange_64 nodes cannot hit this since they store the metadata in a separate field.

Fix this by bounding the descent with slot_len which holds the number of children of a dead node.

---
 lib/maple_tree.c | 43 +------------------------------------------
 1 file changed, 1 insertion(+), 42 deletions(-)
lib/maple_tree.c +1 -42
index 1aba6cced7130..0b0036c9f8489 100644
@@ -763,43 +763,6 @@ static inline void ma_set_meta(struct maple_node *mn, enum maple_type mt,
 	meta->end = end;
 }
 
-/*
- * mt_clear_meta() - clear the metadata information of a node, if it exists
- * @mt: The maple tree
- * @mn: The maple node
- * @type: The maple node type
- */
-static inline void mt_clear_meta(struct maple_tree *mt, struct maple_node *mn,
-				  enum maple_type type)
-{
-	struct maple_metadata *meta;
-	unsigned long *pivots;
-	void __rcu **slots;
-	void *next;
-
-	switch (type) {
-	case maple_range_64:
-		pivots = mn->mr64.pivot;
-		if (unlikely(pivots[MAPLE_RANGE64_SLOTS - 2])) {
-			slots = mn->mr64.slot;
-			next = mt_slot_locked(mt, slots,
-					      MAPLE_RANGE64_SLOTS - 1);
-			if (unlikely((mte_to_node(next) &&
-				      mte_node_type(next))))
-				return; /* no metadata, could be node */
-		}
-		fallthrough;
-	case maple_arange_64:
-		meta = ma_meta(mn, type);
-		break;
-	default:
-		return;
-	}
-
-	meta->gap = 0;
-	meta->end = 0;
-}
-
 /*
  * ma_meta_end() - Get the data end of a node from the metadata
  * @mn: The maple node
@@ -4789,9 +4752,7 @@ static void mt_free_walk(struct rcu_head *head)
 
 		type = mte_node_type(enode);
 		slots = ma_slots(mte_to_node(enode), type);
-		if ((offset < mt_slots[type]) &&
-		    rcu_dereference_protected(slots[offset],
-					      lock_is_held(&rcu_callback_map)))
+		if (offset < mte_to_node(enode)->slot_len)
 			slots = mte_dead_walk(&enode, offset);
 		node = mte_to_node(enode);
 	} while ((node != start) || (node->slot_len < offset));
@@ -4885,8 +4846,6 @@ static void mt_destroy_walk(struct maple_enode *enode, struct maple_tree *mt,
 free_leaf:
 	if (free)
 		kfree(node);
-	else
-		mt_clear_meta(mt, node, node->type);
 }
 
 /*
Signature · 1 line
2.53.0
author maintainer
#2426 lore raw

PATCH 2403/2651 bpf: Track borrowed iterator results by default

In reply to Greg Kroah-Hartman

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

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

From: Xu Yunxiang <[email protected]>

[ Upstream commit d09c2aa3109f5cb1d0be7d382231ab5d58583cad ]

An open-coded iterator can return a struct pointer borrowed from its current element. The verifier has not tied such results to iterator state since the task_vma iterator was introduced, so a saved result can still be used after destroy. Commit bee9ef4a40a27 ("bpf: switch task_vma iterator from mmap_lock to per-VMA locks") also made next release the protection of the prior element. A later snapshot conversion made vm_file explicitly borrowed from that element.

Associate non-RCU, non-acquired struct results with the iterator reference by default. Invalidate dependents before next forks its NULL and non-NULL paths, while retaining the iterator itself. Let destroy propagate child-reference errors. Add KF_ITER_RET_INDEPENDENT for results that outlive the current element, preserving existing RCU and acquired-reference rules.

Trusted pointer field loads also need to preserve the source lifetime. Loading a trusted field does not acquire a reference to the pointed-to object. Set the field pointer's parent_id to the source's reference ID if the source is referenced, or inherit its parent_id if it is borrowed. This is a generic rule, including accesses unrelated to iterators. For example, the following access is now rejected:

  file = bpf_get_task_exe_file(task);
  if (!file)
          return 0;
  inode = file->f_inode;
  bpf_put_file(file);
  ino = inode->i_ino;

The inode pointer borrows the file's lifetime. Releasing the acquired file reference removes that lifetime guarantee, so the verifier must invalidate the derived inode pointer as well. This does not imply that bpf_put_file() immediately frees the file or inode. Reading the inode while the file reference is held remains valid. Fields with independent RCU protection retain their existing lifetime rules.

For an iterator result, the same propagation keeps trusted fields such as vm_file and f_inode tied to the current element. Propagate the backing object's lifetime through dynptr construction too, so its descendants remain in the invalidation graph. Share the invalidation traversal between next and release, so advancing the iterator preserves its own reference.

Fixes 4ac454682158 ("bpf: Introduce task_vma open-coded iterator kfuncs")
---
 Documentation/bpf/bpf_iterators.rst | 10 +++++
 include/linux/btf.h                 |  1 +
 kernel/bpf/btf.c                    | 13 +++++-
 kernel/bpf/verifier.c               | 68 ++++++++++++++++++++++++-----
 4 files changed, 79 insertions(+), 13 deletions(-)
Documentation/bpf/bpf_iterators.rst +10 -0
index 189e3ec1c6c8e..72435e32ffa16 100644
@@ -86,6 +86,16 @@ Constructor/next/destructor implementation contract is as follows:
     resources and marks stack space used by `struct bpf_iter_<type>` as usable
     for something else. Destructor is marked with KF_ITER_DESTROY flag.
 
+The verifier treats a non-RCU, non-acquired struct result as borrowed from
+the iterator's current element. It invalidates the previous result and its
+tracked derived pointers on the next call, including when it returns NULL,
+and on destruction of the iterator. Resources borrowing that lifetime must
+be released first. A next method whose struct result has an independent
+lifetime must use ``KF_ITER_RET_INDEPENDENT``. This flag requires
+``KF_ITER_NEXT`` and a struct pointer return type, and cannot be combined
+with ``KF_ACQUIRE``. RCU-protected and acquired results retain their own
+lifetime rules.
+
 Any open-coded BPF iterator implementation has to implement at least these
 three methods. It is enforced that for any given type of iterator only
 applicable constructor/destructor/next are callable. I.e., verifier ensures
include/linux/btf.h +1 -0
index 7c62ea17b1163..19eff0c17b2af 100644
@@ -81,6 +81,7 @@
 #define KF_IMPLICIT_ARGS (1 << 16) /* kfunc has implicit arguments supplied by the verifier */
 #define KF_SPINLOCK_SAFE (1 << 17) /* kfunc is allowed inside bpf_spin_lock-ed region */
 #define KF_PERFMON      (1 << 18) /* kfunc requires CAP_PERFMON */
+#define KF_ITER_RET_INDEPENDENT (1 << 19) /* next result outlives the current element */
 
 /*
  * Tag marking a kernel function as a kfunc. This is meant to minimize the
kernel/bpf/btf.c +12 -1
index 85b8a667dd547..bf731bf9e0a57 100644
@@ -8859,6 +8859,10 @@ static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
 	if (!flags || (flags & (flags - 1)))
 		return -EINVAL;
 
+	if ((func_flags & KF_ITER_RET_INDEPENDENT) &&
+	    (!(flags & KF_ITER_NEXT) || (func_flags & KF_ACQUIRE)))
+		return -EINVAL;
+
 	/* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
 	nr_args = btf_type_vlen(func);
 	if (nr_args < 1)
@@ -8899,6 +8903,12 @@ static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
 		t = btf_type_skip_modifiers(btf, func->type, NULL);
 		if (!t || !btf_type_is_ptr(t))
 			return -EINVAL;
+		/* The opt-out applies only to non-acquired struct results. */
+		if (func_flags & KF_ITER_RET_INDEPENDENT) {
+			t = btf_type_skip_modifiers(btf, t->type, NULL);
+			if (!t || !__btf_type_is_struct(t))
+				return -EINVAL;
+		}
 	}
 
 	if (flags & KF_ITER_DESTROY) {
@@ -8965,7 +8975,8 @@ static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
 	if (!func || !btf_type_is_func_proto(func))
 		return -EINVAL;
 
-	if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) {
+	if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY |
+			  KF_ITER_RET_INDEPENDENT)) {
 		err = btf_check_iter_kfuncs(btf, func_name, func, func_flags);
 		if (err)
 			return err;
kernel/bpf/verifier.c +56 -12

143 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#2427 lore raw

PATCH 2404/2651 ALSA: ump: Drain sequencer callbacks before freeing their client

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 9b30046de03acb3b3f2135d45af6be7ee0b565b6 ]

seq_ump_client_free() cancels group_notify_work while the endpoint still publishes seq_ops and seq_client. A received Function Block update can enter the sequencer callback after cancellation and queue the work again. Even disabling the work cannot protect a callback that already loaded seq_client and then resumes after the client has been freed.

A USB UMP endpoint can continue receiving while its sequencer binding is removed. The following order uses the same endpoint and client:

Sequencer binding removal UMP input completion
------------------------- --------------------
cancel_work_sync()
load seq_ops and seq_client
delete sequencer client
clear endpoint binding
kfree(client)

                                        schedule group_notify_work
                                        read client->seq_client

Cover all calls through seq_ops with SRCU in the UMP core. Withdraw the operations pointer and wait for those callbacks before canceling work and deleting the client. No producer can then queue work after the final cancellation, and both the client and callback code remain available until the last in-flight callback returns.

Publish seq_ops with release/acquire ordering so the separately stored seq_client is initialized before any callback uses it. Use SRCU because sequencer notification delivery can sleep; no callback needs to change its existing execution context or allocation behavior.

Fixes 4a16a3af0571 ("ALSA: seq: ump: Handle FB info update")
Assisted-by LLM
---
 include/sound/ump.h             |  5 +++
 sound/core/seq/seq_ump_client.c |  5 +--
 sound/core/ump.c                | 59 ++++++++++++++++++++++++++++-----
 3 files changed, 59 insertions(+), 10 deletions(-)
include/sound/ump.h +5 -0
index 73f97f88e2ed7..387143783a9b5 100644
@@ -66,6 +66,7 @@ struct snd_ump_endpoint {
 
 #if IS_ENABLED(CONFIG_SND_SEQUENCER)
 	struct snd_seq_device *seq_dev;
+	/* Published after seq_client; calls are covered by UMP core SRCU. */
 	const struct snd_seq_ump_ops *seq_ops;
 	void *seq_client;
 #endif
@@ -126,6 +127,10 @@ int snd_ump_receive_ump_val(struct snd_ump_endpoint *ump, u32 val);
 int snd_ump_switch_protocol(struct snd_ump_endpoint *ump, unsigned int protocol);
 void snd_ump_update_group_attrs(struct snd_ump_endpoint *ump);
 
+#if IS_ENABLED(CONFIG_SND_SEQUENCER)
+void snd_ump_detach_seq(struct snd_ump_endpoint *ump);
+#endif
+
 /*
  * Some definitions for UMP
  */
sound/core/seq/seq_ump_client.c +3 -2
index 4c1e81db376f8..ca9dcec198832 100644
@@ -353,12 +353,12 @@ static int create_ump_endpoint_port(struct seq_ump_client *client)
 /* release the client resources */
 static void seq_ump_client_free(struct seq_ump_client *client)
 {
+	snd_ump_detach_seq(client->ump);
 	cancel_work_sync(&client->group_notify_work);
 
 	if (client->seq_client >= 0)
 		snd_seq_delete_kernel_client(client->seq_client);
 
-	client->ump->seq_ops = NULL;
 	client->ump->seq_client = NULL;
 
 	kfree(client);
@@ -523,7 +523,8 @@ static int snd_seq_ump_probe(struct snd_seq_device *dev)
 	snd_seq_kernel_client_put(cptr);
 
 	ump->seq_client = client;
-	ump->seq_ops = &seq_ump_ops;
+	/* Publish the initialized client before callbacks can observe seq_ops. */
+	smp_store_release(&ump->seq_ops, &seq_ump_ops);
 	return 0;
 
  error:
sound/core/ump.c +51 -8

95 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#2428 lore raw

PATCH 2405/2651 kthread: Fall back when no preferred housekeeping CPU is online

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit 78ff77ded78f2d3d6040705a3ab5a83cc45275e3 ]

kthread_fetch_affinity() falls back to the housekeeping mask only when the intersection with the preferred mask is empty.

If the intersection contains only offline CPUs, set_cpus_allowed_ptr() returns -EINVAL and the kthread keeps its previous affinity, which may still include an isolated CPU.

Check whether the intersection contains an online CPU instead. Fall back to the full housekeeping mask when none are online.

Fixes e894f6339808 ("kthread: Honour kthreads preferred affinity after cpuset changes")
---
 kernel/kthread.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/kthread.c +1 -1
index a3f95c90456bd..0dbff3b68ffbe 100644
@@ -343,7 +343,7 @@ static void kthread_fetch_affinity(struct kthread *kthread, struct cpumask *cpum
 	}
 
 	cpumask_and(cpumask, pref, housekeeping_cpumask(HK_TYPE_DOMAIN));
-	if (cpumask_empty(cpumask))
+	if (!cpumask_intersects(cpumask, cpu_online_mask))
 		cpumask_copy(cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN));
 }
 
Signature · 1 line
2.53.0
author maintainer
#2429 lore raw

PATCH 2406/2651 hrtimer: Add cleanup class for on-stack timers

In reply to Greg Kroah-Hartman

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

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

From: Hui Su <[email protected]>

[ Upstream commit 064bcd117e8a1a266bb92b840f63862999b7cb87 ]

hrtimer_setup_on_stack() requires callers to destroy the timer before its backing stack storage goes out of scope, but the setup interface does not encode the required teardown pairing.

Add an hrtimer_on_stack cleanup class that pairs on-stack setup with destroy_hrtimer_on_stack(). Document the existing setup API's lifetime requirement.

The cleanup class provides debug-object teardown, not timer cancellation. Callers must ensure that no hrtimer operation can still access the timer before the scope ends; in particular, the timer must no longer be queued and any running callback must have completed.

Stable-dep-of: bd091346971c ("sched/idle: Use hrtimer cleanup class in play_idle_precise()")

---
 include/linux/hrtimer.h | 24 ++++++++++++++++++++++++
 kernel/time/hrtimer.c   |  8 ++++++--
 2 files changed, 30 insertions(+), 2 deletions(-)
include/linux/hrtimer.h +24 -0
index 29072d89e5cb3..1877beb81d5c2 100644
@@ -12,6 +12,7 @@
 #ifndef _LINUX_HRTIMER_H
 #define _LINUX_HRTIMER_H
 
+#include <linux/cleanup.h>
 #include <linux/hrtimer_rearm.h>
 #include <linux/hrtimer_types.h>
 #include <linux/init.h>
@@ -201,6 +202,29 @@ extern void destroy_hrtimer_on_stack(struct hrtimer *timer);
 static inline void destroy_hrtimer_on_stack(struct hrtimer *timer) { }
 #endif
 
+/*
+ * The cleanup class pairs on-stack setup with debug-object teardown. Callers
+ * using it must not call destroy_hrtimer_on_stack() manually.
+ *
+ * This class provides debug-object teardown, not timer cancellation. Callers
+ * must ensure that no hrtimer operation can still access the timer before
+ * leaving the scope. In particular, the timer must no longer be queued and
+ * any running callback must have completed.
+ *
+ * Callers using hrtimer_setup_on_stack() without this class retain
+ * responsibility for destroying the timer before its backing storage leaves
+ * scope.
+ */
+DEFINE_CLASS(hrtimer_on_stack, struct hrtimer *,
+	     destroy_hrtimer_on_stack(_T),
+	     ({
+		hrtimer_setup_on_stack(timer, function, clock_id, mode);
+		timer;
+	     }),
+	     struct hrtimer *timer,
+	     enum hrtimer_restart (*function)(struct hrtimer *),
+	     clockid_t clock_id, enum hrtimer_mode mode)
+
 /* Basic timer operations: */
 extern void hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
 				   u64 range_ns, const enum hrtimer_mode mode);
kernel/time/hrtimer.c +6 -2
index cbf1693c86b38..12e136d5691f4 100644
@@ -1975,8 +1975,12 @@ EXPORT_SYMBOL_GPL(hrtimer_setup);
  * @clock_id:	The clock to be used
  * @mode:       The timer mode
  *
- * Similar to hrtimer_setup(), except that this one must be used if struct hrtimer is in stack
- * memory.
+ * Similar to hrtimer_setup(), except that this one must be used if struct
+ * hrtimer is in stack memory.
+ *
+ * Callers that do not use the hrtimer_on_stack cleanup class must call
+ * destroy_hrtimer_on_stack() before the stack storage goes out of scope. The
+ * cleanup class pairs setup and destruction automatically.
  */
 void hrtimer_setup_on_stack(struct hrtimer *timer,
 			    enum hrtimer_restart (*function)(struct hrtimer *),
Signature · 1 line
2.53.0
author maintainer
#2430 lore raw

PATCH 2407/2651 sched/idle: Use hrtimer cleanup class in play_idle_precise()

In reply to Greg Kroah-Hartman

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

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

From: Hui Su <[email protected]>

[ Upstream commit bd091346971c88fccd44afd2547d28366f824572 ]

Pair on-stack setup with destruction using the hrtimer_on_stack cleanup class in play_idle_precise().

Keep the cleanup object's scope around timer start and the idle wait. Start the timer in pinned hard mode, so its callback runs as a hardirq on the current CPU. The interrupted task observes it.done only after the callback returns. Since the callback returns HRTIMER_NORESTART, the timer is not requeued before the cleanup object tears down its on-stack debug object.

---
 kernel/sched/idle.c | 16 ++++++++++------
 1 file changed, 10 insertions(+), 6 deletions(-)
kernel/sched/idle.c +10 -6
index eb73b65ce6c47..2880e01368b8e 100644
@@ -429,13 +429,17 @@ void play_idle_precise(u64 duration_ns, u64 latency_ns)
 	cpuidle_use_deepest_state(latency_ns);
 
 	it.done = 0;
-	hrtimer_setup_on_stack(&it.timer, idle_inject_timer_fn, CLOCK_MONOTONIC,
-			       HRTIMER_MODE_REL_HARD);
-	hrtimer_start(&it.timer, ns_to_ktime(duration_ns),
-		      HRTIMER_MODE_REL_PINNED_HARD);
+	{
+		CLASS(hrtimer_on_stack, timer)(&it.timer, idle_inject_timer_fn,
+					       CLOCK_MONOTONIC,
+					       HRTIMER_MODE_REL_HARD);
 
-	while (!READ_ONCE(it.done))
-		do_idle();
+		hrtimer_start(timer, ns_to_ktime(duration_ns),
+			      HRTIMER_MODE_REL_PINNED_HARD);
+
+		while (!READ_ONCE(it.done))
+			do_idle();
+	}
 
 	cpuidle_use_deepest_state(0);
 	current->flags &= ~PF_IDLE;
Signature · 1 line
2.53.0
author maintainer
#2431 lore raw

PATCH 2408/2651 vdso/gettimeofday: Correct the read of tz_minuteswest and tz_dsttime

In reply to Greg Kroah-Hartman

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

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

From: Thomas Weißschuh <[email protected]>

[ Upstream commit cbd0f65b48f52d308c457b0fd5201324abadb501 ]

When these fields got moved from 'struct vdso_time_data' to the new 'struct vdso_clock', this access was forgotten.

'vd' is not an array, but a pointer to a single structure. The code works by accident in its current form as CS_HRES_COARSE is 0.

Replace the incorrect array access with a regular pointer dereference.

Fixes 886653e36639 ("vdso: Rework struct vdso_time_data and introduce struct vdso_clock")
---
 lib/vdso/gettimeofday.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
lib/vdso/gettimeofday.c +2 -2
index f7a591aba59f1..6e9b03051beec 100644
@@ -374,8 +374,8 @@ __cvdso_gettimeofday_data(const struct vdso_time_data *vd,
 		if (vdso_is_timens_clock(vc))
 			vd = vdso_timens_data(vd);
 
-		tz->tz_minuteswest = vd[CS_HRES_COARSE].tz_minuteswest;
-		tz->tz_dsttime = vd[CS_HRES_COARSE].tz_dsttime;
+		tz->tz_minuteswest = vd->tz_minuteswest;
+		tz->tz_dsttime = vd->tz_dsttime;
 	}
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#2432 lore raw

PATCH 2409/2651 bpf: Validate stack arg reads against caller state

In reply to Greg Kroah-Hartman

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

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

From: Weiming Shi <[email protected]>

[ Upstream commit 90aedf8854c05713c02b381c41c59081b5cedbcc ]

check_stack_arg_read() bounds a stack argument index with the callee's BTF-derived argument count, then uses the index in the caller's stack_arg_regs[] array. The array's actual logical length is recorded in caller->out_stack_arg_cnt, so the bound and indexed object can diverge.

A crafted BPF_PROG_LOAD can use an argument mismatch to mark a static subprogram's BTF information unreliable. Later calls return from btf_check_subprog_call() before check_outgoing_stack_args(), while check_func_call() continues the static call on -EINVAL. The callee can then read a slot that the caller never allocated or initialized. The earlier commit 4286f5deee14 ("bpf: Validate outgoing stack args when btf_prepare_func_args fails") closed this hole for the first call, but not for later calls after the subprogram has been marked unreliable.

Callbacks have a related problem. The verifier can make incoming stack arguments readable from outgoing slots at the helper call site. However, helpers and kfuncs invoke callbacks through an ABI that passes at most five arguments, so the runtime callback receives no stack arguments. Async callback verification can also reach check_stack_arg_read() without a caller frame.

On x86-64, KASAN reports the direct-call out-of-bounds copy as:

  BUG: KASAN: slab-out-of-bounds in check_load_mem+0xb51/0xc60
  Read of size 80 at addr ffff8881009af550 by task poc/131
  Call Trace:
   check_stack_arg_read at kernel/bpf/verifier.c:4234
   (inlined by) check_load_mem at kernel/bpf/verifier.c:6645
   do_check_common at kernel/bpf/verifier.c:19568
   bpf_check at kernel/bpf/verifier.c:21318
   bpf_prog_load at kernel/bpf/syscall.c:3134

Reject callback subprograms with incoming stack arguments before their state is pushed. For direct calls, retrieve the slot with bpf_get_spilled_stack_arg(), which validates the index against the caller's out_stack_arg_cnt and rejects uninitialized slots before copying the register state.

Fixes 0f6bd5e7a804 ("bpf: Support stack arguments for bpf functions")
---
 kernel/bpf/verifier.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
kernel/bpf/verifier.c +10 -1
index 46c21d90820c8..2ed356a03a57b 100644
@@ -4278,7 +4278,12 @@ static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_st
 	}
 
 	caller = vstate->frame[vstate->curframe - 1];
-	arg = &caller->stack_arg_regs[spi];
+	arg = bpf_get_spilled_stack_arg(spi, caller);
+	if (!arg) {
+		verbose(env, "invalid read from uninitialized stack arg off %d\n", off);
+		return -EACCES;
+	}
+
 	cur = vstate->frame[vstate->curframe];
 	bpf_diag_mod_begin(env, &cur->regs[dst_regno], arg, BPF_DIAG_MOD_WRITE);
 	cur->regs[dst_regno] = *arg;
@@ -10040,6 +10045,10 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 	err = btf_check_subprog_call(env, subprog, caller->regs);
 	if (err == -EFAULT)
 		return err;
+	if (bpf_in_stack_arg_cnt(&env->subprog_info[subprog])) {
+		verbose(env, "callback subprog cannot have stack args\n");
+		return -EINVAL;
+	}
 
 	/* set_callee_state is used for direct subprog calls, but we are
 	 * interested in validating only BPF helpers that can call subprogs as
Signature · 1 line
2.53.0
author maintainer
#2433 lore raw

PATCH 2410/2651 ALSA: pcmtest: Reject invalid fill_mode values

In reply to Greg Kroah-Hartman

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

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

From: HyeongJun An <[email protected]>

[ Upstream commit 5deb9c57ba93d28a52871a96f3d8794d2cbed035 ]

The fill_block() function handles only fill_mode 0 (random) and 1 (pattern). With any other value it writes nothing and does not move the buffer position. A capture stream then gets no data, and a read fails with -EIO after the timeout. Nothing in the kernel log says why.

Check the value in a set callback, so a bad value is rejected both when the module is loaded and when the parameter is written.

Fixes 315a3d57c64c ("ALSA: Implement the new Virtual PCM Test Driver")
Assisted-by Claude:claude-opus-5-5
---
 sound/drivers/pcmtest.c | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
sound/drivers/pcmtest.c +20 -1
index c5b24c05b3562..b3d5218e89db6 100644
@@ -72,13 +72,32 @@ static u8 playback_capture_test;
 static u8 ioctl_reset_test;
 static struct dentry *driver_debug_dir;
 
+static int fill_mode_set(const char *val, const struct kernel_param *kp)
+{
+	short mode;
+	int err;
+
+	err = kstrtos16(val, 0, &mode);
+	if (err)
+		return err;
+	if (mode != FILL_MODE_RAND && mode != FILL_MODE_PAT)
+		return -EINVAL;
+	fill_mode = mode;
+	return 0;
+}
+
+static const struct kernel_param_ops fill_mode_ops = {
+	.set = fill_mode_set,
+	.get = param_get_short,
+};
+
 module_param(index, int, 0444);
 MODULE_PARM_DESC(index, "Index value for pcmtest soundcard");
 module_param(id, charp, 0444);
 MODULE_PARM_DESC(id, "ID string for pcmtest soundcard");
 module_param(enable, bool, 0444);
 MODULE_PARM_DESC(enable, "Enable pcmtest soundcard.");
-module_param(fill_mode, short, 0600);
+module_param_cb(fill_mode, &fill_mode_ops, &fill_mode, 0600);
 MODULE_PARM_DESC(fill_mode, "Buffer fill mode: rand(0) or pattern(1)");
 module_param(inject_delay, int, 0600);
 MODULE_PARM_DESC(inject_delay, "Inject delays during playback/capture (in jiffies)");
Signature · 1 line
2.53.0
author maintainer
#2434 lore raw

PATCH 2411/2651 netlink: fix out-of-bounds bitmap access clearing stale mc groups

In reply to Greg Kroah-Hartman

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

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

From: Henry Martin <[email protected]>

[ Upstream commit 6430fb7f1cc4e329e386521b7b208df443de92f2 ]

netlink_realloc_groups() sizes nlk->groups to the number of groups that exist at bind/ADD_MEMBERSHIP time. When more multicast groups are registered later (e.g. a new genl family), existing sockets keep their smaller bitmap.

When clearing a multicast group of a departing family, __netlink_clear_multicast_users() runs netlink_update_socket_mc() on each socket on mc_list, which does test_bit()/__assign_bit() on group - 1 with no regard to nlk->ngroups. Skip sockets whose bitmap predates the group: such a socket can never have joined it.

The overflow windows differ per architecture, both needing privileged module (un)loading. On 32-bit kernels the ~54 dynamically allocated genl groups already exceed the initial 32-bit bitmap, so the table can grow there directly. On 64-bit kernels the same in-tree set fits the initial 64-bit bitmap only while allocation stays contiguous:
genl_allocate_reserve_groups() takes the first free contiguous range and unregister does not compact, so an unload/reload sequence can fragment the ~59 free IDs until no fitting range remains, forcing the table past 64 bits and reaching the same stale-bitmap overflow on the next family teardown.

This issue was discovered by Tencent CodeBuddy Security.

Fixes 84659eb529b3 ("[NETLIKN]: Allow removing multicast groups.")
---
 net/netlink/af_netlink.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
net/netlink/af_netlink.c +5 -1
index 3029894edad11..aecd0332b90fd 100644
@@ -2160,8 +2160,12 @@ void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
 	struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
 	struct hlist_node *tmp;
 
-	sk_for_each_bound_safe(sk, tmp, &tbl->mc_list)
+	sk_for_each_bound_safe(sk, tmp, &tbl->mc_list) {
+		/* bitmap predates the group, can't be a member */
+		if (group - 1 >= nlk_sk(sk)->ngroups)
+			continue;
 		netlink_update_socket_mc(nlk_sk(sk), group, 0);
+	}
 }
 
 struct nlmsghdr *
Signature · 1 line
2.53.0
author maintainer
#2435 lore raw

PATCH 2412/2651 ceph: remove unused field `i_cap_migration_resv`

In reply to Greg Kroah-Hartman

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

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

From: Max Kellermann <[email protected]>

[ Upstream commit a200e12135c96893f7c29bdf97f46868132f695d ]

This field was added 17 years ago by commit de57606c23afd ("ceph:
client types") but it was never used.

This reduces the size of struct ceph_inode_info by 8 bytes.

---
 fs/ceph/super.h | 1 -
 1 file changed, 1 deletion(-)
fs/ceph/super.h +0 -1
index 72d4e30304dca..1c91e73a63aca 100644
@@ -463,7 +463,6 @@ struct ceph_inode_info {
 	wait_queue_head_t i_cap_wq;      /* threads waiting on a capability */
 	unsigned long i_hold_caps_max; /* jiffies */
 	struct list_head i_cap_delay_list;  /* for delayed cap release to mds */
-	struct ceph_cap_reservation i_cap_migration_resv;
 	struct list_head i_cap_snaps;   /* snapped state pending flush to mds */
 	struct ceph_snap_context *i_head_snapc;  /* set if wr_buffer_head > 0 or
 						    dirty|flushing caps */
Signature · 1 line
2.53.0
author maintainer
#2436 lore raw

PATCH 2413/2651 ceph: mark the superblock active after mounting

In reply to Greg Kroah-Hartman

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

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

From: Xiubo Li <[email protected]>

[ Upstream commit 32eacfae3b16f6a9c0c20f946115abf5a091c922 ]

ceph_get_tree() calls sget_fc() directly and so never goes through vfs_get_super(), which is what sets SB_ACTIVE after fill_super for filesystems that use it. Before commit 82995cc6c5ae ("libceph, rbd,
ceph: convert to use the new mount API") the flag used to be set by get_sb_nodev(), which did this for ceph, but the conversion dropped it.

SB_ACTIVE is required for iput_final() to retain an inode on the inode LRU instead of evicting it once its last reference goes away. This has gone unnoticed because ceph sets inode_just_drop() for ->drop_inode, which always asks for eviction, so the retain branch in iput_final() was never reachable. The next patch makes ->drop_inode() able to retain inodes, and that needs the flag to actually work.

Set it once the mount is up, like nfs_get_tree() does.

Fixes 82995cc6c5ae ("libceph, rbd, ceph: convert to use the new mount API")
---
 fs/ceph/super.c | 9 +++++++++
 1 file changed, 9 insertions(+)
fs/ceph/super.c +9 -0
index 72935f665f11c..4306d6b3b995f 100644
@@ -1368,6 +1368,15 @@ static int ceph_get_tree(struct fs_context *fc)
 	doutc(fsc->client, "root %p inode %p ino %llx.%llx\n", res,
 		    d_inode(res), ceph_vinop(d_inode(res)));
 	fc->root = fsc->sb->s_root;
+
+	/*
+	 * The mount is up.  sget_fc() leaves SB_ACTIVE unset, and, unlike
+	 * filesystems that go through vfs_get_super(), nothing else sets
+	 * it here, so iput_final() would always evict an inode whose
+	 * ->drop_inode() asks to retain it.  Set it like nfs_get_tree()
+	 * does.
+	 */
+	sb->s_flags |= SB_ACTIVE;
 	return 0;
 
 out_splat:
Signature · 1 line
2.53.0
author maintainer
#2437 lore raw

PATCH 2414/2651 ceph: fix page vector leak on encrypted netfs read EIO path

In reply to Greg Kroah-Hartman

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

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

From: Alex Markuze <[email protected]>

[ Upstream commit 00a0d7f377f6af59bc559b2e07dffff63eaa5544 ]

ceph_netfs_issue_read() pins pages with iov_iter_get_pages_alloc2() for encrypted inodes and attaches them with own_pages=false. If ceph_inc_osd_stopping_blocker() then fails, the request is dropped without calling finish_netfs_read(), so the page array and the references taken on those pages leak: ceph_osd_data_release() only frees pages when own_pages is true, and __free_pages() would be the wrong destructor for GUP-pinned pages.

Release the vector with put_page() and kvfree() on that error path, matching finish_netfs_read(). Unencrypted ITER reads are unaffected.

Fixes 1464de9f813e ("ceph: wait for OSD requests' callbacks to finish when unmounting")
---
 fs/ceph/addr.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
fs/ceph/addr.c +11 -0
index f32a533f41009..5f34863d3724c 100644
@@ -450,6 +450,17 @@ static void ceph_netfs_issue_read(struct netfs_io_subrequest *subreq)
 		osd_req_op_extent_osd_iter(req, 0, &subreq->io_iter);
 	}
 	if (!ceph_inc_osd_stopping_blocker(fsc->mdsc)) {
+		struct ceph_osd_data *osd_data =
+			osd_req_op_extent_osd_data(req, 0);
+
+		if (osd_data->type == CEPH_OSD_DATA_TYPE_PAGES) {
+			int num_pages = calc_pages_for(osd_data->alignment,
+						       osd_data->length);
+
+			for (int i = 0; i < num_pages; i++)
+				put_page(osd_data->pages[i]);
+			kvfree(osd_data->pages);
+		}
 		err = -EIO;
 		goto out;
 	}
Signature · 1 line
2.53.0
author maintainer
#2438 lore raw

PATCH 2415/2651 ceph: fix error handling when the OSD client is stopping in ceph_submit_write()

In reply to Greg Kroah-Hartman

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

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

From: Tal Zussman <[email protected]>

[ Upstream commit ad67b498de17b709f050d7ebf84749b1fc6a242d ]

When ceph_inc_osd_stopping_blocker() fails, ceph_submit_write() redirties and unlocks the folios remaining in ceph_wbc->fbatch. However, none of those folios are locked at this point: locked folios were moved to ceph_wbc->pages[] and removed from the fbatch by ceph_process_folio_batch(). Unlocking them triggers VM_BUG_ON_FOLIO(!folio_test_locked(folio)) in folio_unlock(), or unlocks a folio locked by another task.

This error path also returns -EIO without fully cleaning up the folios in ceph_wbc->pages[]: their references are never dropped, fscrypt bounce pages are never freed, the writeback congestion count is never decremented, and the pages array is leaked. ceph_wbc->locked_pages is also left non-zero, so ceph_writepages_start() loops back around and hits BUG_ON(ceph_wbc.locked_pages).

Leave the fbatch folios alone, as ceph_writepages_start() drops their references when releasing the batch, and unwind ceph_wbc->pages[] the same way writepages_finish() would have. Abort writeback in ceph_writepages_start() instead of continuing, matching the handling of ceph_inc_osd_stopping_blocker() failure on entry, as the OSD client is being torn down and further writeback cannot make progress.

An LLM was used to verify that the cleanup was comprehensive, and suggested aborting the writeback instead of continuing.

---
 fs/ceph/addr.c | 39 +++++++++++++++++++++++----------------
 1 file changed, 23 insertions(+), 16 deletions(-)
fs/ceph/addr.c +23 -16
index 5f34863d3724c..5cccba9e010f3 100644
@@ -1502,28 +1502,32 @@ int ceph_submit_write(struct address_space *mapping,
 	BUG_ON(len < ceph_fscrypt_page_offset(page) + thp_size(page) - offset);
 
 	if (!ceph_inc_osd_stopping_blocker(fsc->mdsc)) {
-		for (i = 0; i < folio_batch_count(&ceph_wbc->fbatch); i++) {
-			struct folio *folio = ceph_wbc->fbatch.folios[i];
-
-			if (!folio)
-				continue;
-
-			page = &folio->page;
-			redirty_page_for_writepage(wbc, page);
-			unlock_page(page);
-		}
-
 		for (i = 0; i < ceph_wbc->locked_pages; i++) {
-			page = ceph_fscrypt_pagecache_page(ceph_wbc->pages[i]);
+			page = ceph_wbc->pages[i];
+			if (fscrypt_is_bounce_page(page)) {
+				page = fscrypt_pagecache_page(page);
+				fscrypt_free_bounce_page(ceph_wbc->pages[i]);
+			}
 
-			if (!page)
-				continue;
+			if (atomic_long_dec_return(&fsc->writeback_count) <
+			    CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb))
+				fsc->write_congested = false;
 
 			ceph_undo_wrbuffer_claim(inode, page_folio(page));
 			redirty_page_for_writepage(wbc, page);
 			unlock_page(page);
+			put_page(page);
 		}
 
+		if (ceph_wbc->from_pool) {
+			mempool_free(ceph_wbc->pages, ceph_wb_pagevec_pool);
+			ceph_wbc->from_pool = false;
+		} else {
+			kfree(ceph_wbc->pages);
+		}
+		ceph_wbc->pages = NULL;
+		ceph_wbc->locked_pages = 0;
+
 		ceph_osdc_put_request(req);
 		return -EIO;
 	}
@@ -1756,8 +1760,11 @@ static int ceph_writepages_start(struct address_space *mapping,
 		}
 
 		rc = ceph_submit_write(mapping, wbc, &ceph_wbc);
-		if (rc)
-			goto release_folios;
+		if (rc) {
+			/* the OSD client is being torn down, don't retry */
+			folio_batch_release(&ceph_wbc.fbatch);
+			goto dec_osd_stopping_blocker;
+		}
 
 		ceph_wbc.locked_pages = 0;
 		ceph_wbc.strip_unit_end = 0;
Signature · 1 line
2.53.0
author maintainer
#2439 lore raw

PATCH 2416/2651 ceph: wait for pending fscache write in write_folio_nounlock()

In reply to Greg Kroah-Hartman

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

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

From: Tal Zussman <[email protected]>

[ Upstream commit 3f7655f0d9186656c6f1cbc012a39c866d4aaabf ]

write_folio_nounlock() marks the folio with PG_private_2 via ceph_set_page_fscache() and starts an async write to the cache via ceph_fscache_write_to_cache(). PG_private_2 is only cleared once that write completes.

If the OSD write fails, the error paths return without waiting for the cache write. On retry, ceph_find_incompatible() would wait for writeback, but not for PG_private_2, before calling write_folio_nounlock() again, which would trip the VM_BUG_ON_FOLIO() in folio_start_private_2().

Wait for any pending cache write before starting writeback on the folio. Do so before bumping the writeback congestion count and allocating the possibly mempool-backed OSD request, so that a thread sleeping on the cache I/O does not hold either while it waits. Add ceph_folio_wait_fscache(), a wrapper for folio_wait_private_2(), and use it.

---
 fs/ceph/addr.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
fs/ceph/addr.c +12 -0
index 5cccba9e010f3..6a61508be17e7 100644
@@ -575,6 +575,11 @@ static void ceph_set_page_fscache(struct page *page)
 	folio_start_private_2(page_folio(page)); /* [DEPRECATED] */
 }
 
+static void ceph_folio_wait_fscache(struct folio *folio)
+{
+	folio_wait_private_2(folio); /* [DEPRECATED] */
+}
+
 static void ceph_fscache_write_terminated(void *priv, ssize_t error)
 {
 	struct inode *inode = priv;
@@ -596,6 +601,10 @@ static inline void ceph_set_page_fscache(struct page *page)
 {
 }
 
+static inline void ceph_folio_wait_fscache(struct folio *folio)
+{
+}
+
 static inline void ceph_fscache_write_to_cache(struct inode *inode, u64 off, u64 len, bool caching)
 {
 }
@@ -799,6 +808,9 @@ static int write_folio_nounlock(struct folio *folio,
 	      ceph_vinop(inode), folio, folio->index, page_off, wlen, snapc,
 	      snapc->seq);
 
+	/* wait for a cache write left pending by a previously failed attempt */
+	ceph_folio_wait_fscache(folio);
+
 	if (atomic_long_inc_return(&fsc->writeback_count) >
 	    CONGESTION_ON_THRESH(fsc->mount_options->congestion_kb))
 		fsc->write_congested = true;
Signature · 1 line
2.53.0
author maintainer
#2440 lore raw

PATCH 2417/2651 ceph: fix writeback_count leak when a bounce page allocation fails

In reply to Greg Kroah-Hartman

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

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

From: Tal Zussman <[email protected]>

[ Upstream commit 7807710d88ad03e7ca9b5f79f518f040db2a4e09 ]

ceph_process_folio_batch() calls is_write_congestion_happened(), which increments fsc->writeback_count, before calling move_dirty_folio_in_page_array(). If the fscrypt bounce page allocation there fails, the folio is redirtied and never makes it into the page array, but the count is never dropped.

write_congested is only cleared when a decrement falls below CONGESTION_OFF_THRESH, so the leaked counts set congestion early and eventually leave write_congested set for good. Every WB_SYNC_NONE writeback then returns 0 and background writeback stops entirely.

Bump the count only once the folio is in the page array.

Fixes d55207717ded ("ceph: add encryption support to writepage and writepages")
Assisted-by Claude:fable-5.1
---
 fs/ceph/addr.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/ceph/addr.c +2 -2
index 6a61508be17e7..60cf6a81af35a 100644
@@ -1417,8 +1417,6 @@ void ceph_process_folio_batch(struct address_space *mapping,
 		doutc(cl, "%llx.%llx will write folio %p idx %lu\n",
 		      ceph_vinop(inode), folio, folio->index);
 
-		fsc->write_congested = is_write_congestion_happened(fsc);
-
 		rc = move_dirty_folio_in_page_array(mapping, wbc, ceph_wbc,
 				folio);
 		if (rc) {
@@ -1431,6 +1429,8 @@ void ceph_process_folio_batch(struct address_space *mapping,
 			break;
 		}
 
+		fsc->write_congested = is_write_congestion_happened(fsc);
+
 		ceph_wbc->fbatch.folios[i] = NULL;
 		ceph_wbc->len += folio_size(folio);
 	}
Signature · 1 line
2.53.0
author maintainer
#2441 lore raw

PATCH 2418/2651 ceph: dont clear write_congested when collecting folios

In reply to Greg Kroah-Hartman

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

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

From: Tal Zussman <[email protected]>

[ Upstream commit 77ff2ba4630b9e9e9f73bbaaeb675638b2c20dd0 ]

ceph_process_folio_batch() assigns the result of is_write_congestion_happened() to fsc->write_congested for every folio it collects. The code it replaced only ever set write_congested to true here, leaving the decrement paths to clear it once writeback_count drops below CONGESTION_OFF_THRESH. The unconditional assignment means that a sync writeback that runs while the count sits between the off and on thresholds clears the flag on its first folio, and background writeback resumes early.

Only set the flag here, as before.

Fixes ce80b76dd327 ("ceph: introduce ceph_process_folio_batch() method")
Assisted-by Claude:fable-5.1
---
 fs/ceph/addr.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/ceph/addr.c +2 -1
index 60cf6a81af35a..edf3ad5a0bfc8 100644
@@ -1429,7 +1429,8 @@ void ceph_process_folio_batch(struct address_space *mapping,
 			break;
 		}
 
-		fsc->write_congested = is_write_congestion_happened(fsc);
+		if (is_write_congestion_happened(fsc))
+			fsc->write_congested = true;
 
 		ceph_wbc->fbatch.folios[i] = NULL;
 		ceph_wbc->len += folio_size(folio);
Signature · 1 line
2.53.0
author maintainer
#2442 lore raw

PATCH 2419/2651 ceph: fix off-by-one NUL termination in decode_encrypted_symlink()

In reply to Greg Kroah-Hartman

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

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

From: Xiang Mei <[email protected]>

[ Upstream commit 4da259ea8bf4bd6a91a63f33630a26592d2353f8 ]

decode_encrypted_symlink() allocates enclen + 1 bytes but writes the NUL terminator at sym[declen + 1] instead of sym[declen]. A malicious MDS can report symlink_len == 0 for an encrypted inode, and base64_decode() returns 0 for a zero-length input, so the store lands one byte past a kmalloc(1) allocation.

Terminate at sym[declen], which is always within the allocation.

  BUG: KASAN: slab-out-of-bounds in ceph_fill_inode (fs/ceph/inode.c:996)
  Write of size 1 at addr ffff888020aad361 by task kworker/0:0/9
  Workqueue: ceph-msgr ceph_con_workfn
  Call Trace:
   kasan_report (mm/kasan/report.c:595)
   ceph_fill_inode (fs/ceph/inode.c:996 fs/ceph/inode.c:1277)
   ceph_fill_trace (fs/ceph/inode.c:1716)
   ceph_con_process_message (net/ceph/messenger.c:1424)
   ceph_con_v1_try_read (net/ceph/messenger_v1.c:1430)
   ceph_con_workfn (net/ceph/messenger.c:1576)
   ...
  The buggy address belongs to the object at ffff888020aad360
   which belongs to the cache kmalloc-8 of size 8
  The buggy address is located 0 bytes to the right of
   allocated 1-byte region [ffff888020aad360, ffff888020aad361)
Fixes 79f2f6ad878c ("ceph: create symlinks with encrypted and base64-encoded targets")
Reported-by [email protected]
Assisted-by LLM
---
 fs/ceph/inode.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ceph/inode.c +1 -1
index d52e2b389e0b6..79c4409f183ea 100644
@@ -993,7 +993,7 @@ static int decode_encrypted_symlink(struct ceph_mds_client *mdsc,
 		kfree(sym);
 		return -EIO;
 	}
-	sym[declen + 1] = '\0';
+	sym[declen] = '\0';
 	*decsym = sym;
 	return declen;
 }
Signature · 1 line
2.53.0
author maintainer
#2443 lore raw

PATCH 2420/2651 ceph: dont keep a mon_addr string that failed to parse

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

ceph_parse_mon_addr() stores the string in fsopt->mon_addr before handing it to ceph_parse_mon_ips(), and then returns that function's error. So after a mon_addr= that does not parse, fsconfig() reports the failure but the mount context keeps the rejected string.

That matters because ceph_get_tree() uses fsopt->mon_addr as the "monitor addresses were supplied" test:

	if (fsopt->new_dev_syntax && !fsopt->mon_addr)
		return invalfc(fc, "No monitor address");

Userspace is free to ignore the error from fsconfig(FSCONFIG_SET_STRING) and go straight to FSCONFIG_CMD_CREATE. The check then passes on a value that was rejected, and the mount continues with ceph_options::num_mon still 0 - which is how syzbot reached the BUG_ON() in pick_new_mon() fixed by the previous patch.

Parse first and commit only on success. A failed mon_addr= now leaves any previously accepted value in place instead of replacing it with one that does not parse.

Fixes 7b19b4db5add ("ceph: new device mount syntax")
Reported-by [email protected]
Assisted-by Cursor
---
 fs/ceph/super.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
fs/ceph/super.c +7 -2
index 4306d6b3b995f..416bf86996a03 100644
@@ -394,13 +394,18 @@ static int ceph_parse_mon_addr(struct fs_parameter *param,
 {
 	struct ceph_parse_opts_ctx *pctx = fc->fs_private;
 	struct ceph_mount_options *fsopt = pctx->opts;
+	int ret;
+
+	ret = ceph_parse_mon_ips(param->string, strlen(param->string),
+				 pctx->copts, fc->log.log, '/');
+	if (ret)
+		return ret;
 
 	kfree(fsopt->mon_addr);
 	fsopt->mon_addr = param->string;
 	param->string = NULL;
 
-	return ceph_parse_mon_ips(fsopt->mon_addr, strlen(fsopt->mon_addr),
-				  pctx->copts, fc->log.log, '/');
+	return 0;
 }
 
 static int ceph_parse_mount_param(struct fs_context *fc,
Signature · 1 line
2.53.0
author maintainer
#2444 lore raw

PATCH 2421/2651 libceph: reject bad connect_seq in msgr1 READY reply

In reply to Greg Kroah-Hartman

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

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

From: Nguyen Ngoc Thang <[email protected]>

[ Upstream commit 6dfc1b1a99da4909aee07a906352be5c3fc9baba ]

process_connect() WARN_ON()s when the peer's READY/SEQ reply carries a connect_seq other than ours + 1. That value comes off the wire, so a misbehaving or malicious server can trigger the warning at will (and panic machines running with panic_on_warn).

Check it before touching connection state and fail the connection with a protocol error instead, like the other bad-reply cases here.

---
 net/ceph/messenger_v1.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
net/ceph/messenger_v1.c +6 -2
index c9e002d963190..b3ff3274344e9 100644
@@ -887,6 +887,12 @@ static int process_connect(struct ceph_connection *con)
 			return -1;
 		}
 
+		if (le32_to_cpu(con->v1.in_reply.connect_seq) !=
+		    con->v1.connect_seq + 1) {
+			con->error_msg = "protocol error, bad connect_seq";
+			return -1;
+		}
+
 		WARN_ON(con->state != CEPH_CON_S_V1_CONNECT_MSG);
 		con->state = CEPH_CON_S_OPEN;
 		con->v1.auth_retry = 0;    /* we authenticated; clear flag */
@@ -898,8 +904,6 @@ static int process_connect(struct ceph_connection *con)
 		     con->v1.peer_global_seq,
 		     le32_to_cpu(con->v1.in_reply.connect_seq),
 		     con->v1.connect_seq);
-		WARN_ON(con->v1.connect_seq !=
-			le32_to_cpu(con->v1.in_reply.connect_seq));
 
 		if (con->v1.in_reply.flags & CEPH_MSG_CONNECT_LOSSY)
 			ceph_con_flag_set(con, CEPH_CON_F_LOSSYTX);
Signature · 1 line
2.53.0
author maintainer
#2445 lore raw

PATCH 2422/2651 cgroup/cpuset: Find furthest isolated ancestor for invalidated isolated partition

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 0bce85ff2cc0f7f7d8de16f5fdfc0ae7d29f21f1 ]

Commit 46b885416c27 ("cgroup/cpuset: Fix a missing isolated_cpus update in update_cpumasks_hier()") searches for the closet partition root ancestor to determine if the isolated CPUs in a to be invalidated isolation partition should be removed from isolated_cpus or not.

As reported by sashiko, this method may not work when there is a deeply nested isolated partition hierarchy. For instance, Consider a nested hierarchy A0 -> A1 -> A2 -> A3 where all four are PRS_ISOLATED:

A0: effective_xcpus = 0-4
A1: effective_xcpus = 1-4
A2: effective_xcpus = 2-4
A3: effective_xcpus = 3-4

When A1 shrinks its exclusive_cpus from 1-4 to 1-2, A2 will update it effective_xcpus to 2. A3 will find its closet partition root ancestor A2 and decides that its effective_xcpus 3-4 should be removed from isolated_cpus which is incorrect.

Address this corner case by adding a new isolated_cpus_release() helper to replace the existing ancestor_partition() helper. This new helper will search for the furthest isolated partition root ancestor to decide if some or all of its isolated CPUs should be removed from isolated_cpus and also perform the removal when appropriate.

The is_remote_partition() and is_local_partition() helpers are also moved up so they can be used in earlier functions.

There are other pre-existing problems that will still prevent the above test case to work correctly. These problems will be addressed in subsequent patches.

Fixes 46b885416c27 ("cgroup/cpuset: Fix a missing isolated_cpus update in update_cpumasks_hier()")
---
 kernel/cgroup/cpuset.c | 104 +++++++++++++++++++++--------------------
 1 file changed, 53 insertions(+), 51 deletions(-)
kernel/cgroup/cpuset.c +53 -51
index d39953799ad56..f9ce9383af3f5 100644
@@ -1281,6 +1281,16 @@ static void reset_partition_data(struct cpuset *cs)
 		cpumask_copy(cs->effective_cpus, parent->effective_cpus);
 }
 
+static inline bool is_remote_partition(struct cpuset *cs)
+{
+	return cs->remote_partition;
+}
+
+static inline bool is_local_partition(struct cpuset *cs)
+{
+	return is_partition_valid(cs) && !is_remote_partition(cs);
+}
+
 /* Return true if isolated_cpus changes. */
 static bool isolated_cpu_update(int new_prs, int cpu)
 {
@@ -1323,6 +1333,45 @@ static void isolated_cpus_update(int old_prs, int new_prs, struct cpumask *xcpus
 		update_housekeeping = true;
 }
 
+/*
+ * isolated_cpus_release - Remove the relevant CPUs in @xcpus from isolated_cpus
+ * @cs: the current cpuset
+ * @xcpus: the set of effective xcpus to be considered for removal
+ *
+ * This function is called when an isolated partition is invalidated or when
+ * some of its effective xcpus are to be removed from isolated_cpus due to
+ * changes in parent cpuset. The given @xcpus must be modifiable as the function
+ * will update its value to determine the right set of CPUs to be removed.
+ */
+static void isolated_cpus_release(struct cpuset *cs, struct cpumask *xcpus)
+{
+	struct cpuset *ancestor = parent_cs(cs);
+	struct cpuset *iancestor = NULL;
+
+	/*
+	 * Search the furthest isolated partition root ancestor available
+	 * until top_cpuset or a remote partition root is hit.
+	 */
+	for (; ancestor; ancestor = parent_cs(ancestor)) {
+		if (ancestor->partition_root_state == PRS_ISOLATED)
+			iancestor = ancestor;
+		if (is_remote_partition(ancestor))
+			break;
+	}
+
+	/*
+	 * If a furthest isolated partition acnestor is found, use it to
+	 * determine which of the CPUs in @xcpus should be removed from
+	 * isolated_cpus. Otherwise, all of them will be removed.
+	 */
+	if (iancestor && !cpumask_andnot(xcpus, xcpus, iancestor->effective_xcpus))
+		return; /* No CPU should be removed from isolated_cpus */
+
+	spin_lock_irq(&callback_lock);
+	isolated_cpus_update(PRS_ISOLATED, PRS_ROOT, xcpus);
+	spin_unlock_irq(&callback_lock);
+}
+
 /*
  * partition_xcpus_add - Add new exclusive CPUs to partition
  * @new_prs: new partition_root_state
@@ -1595,16 +1644,6 @@ static int compute_trialcs_excpus(struct cpuset *trialcs, struct cpuset *cs)
 	return rm_siblings_excl_cpus(parent, cs, excpus);
 }
 
-static inline bool is_remote_partition(struct cpuset *cs)
-{
-	return cs->remote_partition;
-}
-
-static inline bool is_local_partition(struct cpuset *cs)
-{
-	return is_partition_valid(cs) && !is_remote_partition(cs);
-}
-
 /*
  * remote_partition_enable - Enable current cpuset as a remote partition root
  * @cs: the cpuset to update
@@ -2184,25 +2223,6 @@ static void compute_partition_effective_cpumask(struct cpuset *cs,
 	rcu_read_unlock();
 }
 
-/*
- * ancestor_partition - Find and return the closest valid partition root ancestor
- * @cs: the current cpuset
- *
- * Return: The closet partition root ancestor cpuset
- */
-static struct cpuset *ancestor_partition(struct cpuset *cs)
-{
-	struct cpuset *ancestor = parent_cs(cs);
-
-	/*
-	 * The top_cpuset is always a valid partition root which will stop
-	 * the loop if it is reached.
-	 */
-	while (!is_partition_valid(ancestor))
-		ancestor = parent_cs(ancestor);
-	return ancestor;
-}
-
 /*
  * update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
  * @cs:  the cpuset to consider
@@ -2296,7 +2316,6 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 		 */
 		if ((cp != cs) && old_prs) {
 			int parent_prs = parent->partition_root_state;
-			struct cpumask *del_cpus = NULL;
 
 			switch (parent_prs) {
 			case PRS_ROOT:
@@ -2310,32 +2329,15 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 				 * child partition roots become invalid too.
 				 *
 				 * For a to be invalidated isolated partition,
-				 * its isolated CPUs may or may not need to be
-				 * removed from isolated_cpus depending on if
-				 * its closest partition root ancestor is a root
-				 * or isolated partition. With a PRS_ISOLATED
-				 * ancestor, the CPUs are checked against its
-				 * effective xcpus to see if any of them needed
-				 * to be removed.
+				 * call return_isolated_cpus() to remove the
+				 * relevant CPUs from isolated_cpus.
 				 */
 				if (is_partition_valid(cp))
 					new_prs = -old_prs;
 
 				if (old_prs == PRS_ISOLATED) {
-					struct cpuset *ancestor = ancestor_partition(cp);
-
-					if (ancestor->partition_root_state == PRS_ROOT)
-						del_cpus = cp->effective_xcpus;
-					else if (cpumask_andnot(tmp->delmask,
-								cp->effective_xcpus,
-								ancestor->effective_xcpus))
-						del_cpus = tmp->delmask;
-
-					if (del_cpus) {
-						spin_lock_irq(&callback_lock);
-						isolated_cpus_update(old_prs, new_prs, del_cpus);
-						spin_unlock_irq(&callback_lock);
-					}
+					cpumask_copy(tmp->delmask, cp->effective_xcpus);
+					isolated_cpus_release(cp, tmp->delmask);
 				}
 				WRITE_ONCE(cp->prs_err,
 					   is_partition_invalid(parent)
Signature · 1 line
2.53.0
author maintainer
#2446 lore raw

PATCH 2423/2651 cgroup/cpuset: Dont allow a child root partition under an isolated parent

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit c0189e75d3b8355ed29fea33c184c3eb00dc273d ]

Although it is not typical for real users to create a complicated nested partition hierarchy, it is currently allowed to create nested root and isolated partitions. In addition, disabling or invalidating a partition should always be allowed especially when the cpuset is being deleted.

With a nested root and isolated partition hierarchy, it is possible that all active housekeeping CPUs can be exhausted when disabling or invalidating a root partition and returning its CPUs to the isolated parent.

One way to avoid this problem is to disallow the creation of a root partition under an isolated parent. It is indeed a new limitation imposed on the existing cpuset partition functionality. However an isolated partition is usually a left node where scheduling and some other kernel noises are disabled. It doesn't make much sense to create a child root partition under an isolated parent and remove some CPUs from the set of isolated CPUs again. Creation of a child isolated partition under a root or isolated parent is still allowed.

If a partition with child root partitions is converted to isolated, the child root partitions will be invalidated.

The cgroup-v2 documentation is also updated to reflect this new limitation. New test cases are added to test_cpuset_prs.sh to verify this new behavior. Some existing test cases are also updated accordingly.

Stable-dep-of: 69a75e4f3776 ("cgroup/cpuset: Properly compute effective xcpus in update_parent_effective_cpumask()")

---
 Documentation/admin-guide/cgroup-v2.rst       |  4 ++-
 kernel/cgroup/cpuset-internal.h               |  1 +
 kernel/cgroup/cpuset.c                        | 32 ++++++++++++++++---
 .../selftests/cgroup/test_cpuset_prs.sh       | 23 +++++++------
 4 files changed, 46 insertions(+), 14 deletions(-)
Documentation/admin-guide/cgroup-v2.rst +3 -1
index 86a2a0099178e..f8bc721ec408f 100644
@@ -2727,7 +2727,9 @@ Cpuset Interface Files
 	be retained, but behaves more like a "member".
 
 	All possible state transitions among "member", "root" and
-	"isolated" are allowed.
+	"isolated" are allowed with the exception that a local child
+	"root" partition is not allowed to be created under an "isolated"
+	parent partition.
 
 	On read, the "cpuset.cpus.partition" file can show the following
 	values.
kernel/cgroup/cpuset-internal.h +1 -0
index e7d010661fd32..701c3854ec7ad 100644
@@ -35,6 +35,7 @@ enum prs_errcode {
 	PERR_HKEEPING,
 	PERR_ACCESS,
 	PERR_REMOTE,
+	PERR_ISOPARENT,
 };
 
 /* bits in struct cpuset flags field */
kernel/cgroup/cpuset.c +28 -4
index f9ce9383af3f5..53f6e3c470f11 100644
@@ -60,6 +60,7 @@ static const char * const perr_strings[] = {
 	[PERR_HKEEPING]  = "partition config conflicts with housekeeping setup",
 	[PERR_ACCESS]    = "Enable partition not permitted",
 	[PERR_REMOTE]    = "Have remote partition underneath",
+	[PERR_ISOPARENT] = "Root partition is not allowed with isolated parent",
 };
 
 /*
@@ -1963,6 +1964,10 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 			part_error = PERR_CPUSEMPTY;
 			goto write_error;
 		}
+		if ((parent_prs == PRS_ISOLATED) && (old_prs == -PRS_ROOT)) {
+			part_error = PERR_ISOPARENT;
+			goto write_error;
+		}
 
 		/* Check newmask again, whether cpus are available for parent/cs */
 		nocpu |= tasks_nocpu_error(parent, cs, newmask);
@@ -2038,6 +2043,13 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 				adding = cpumask_and(tmp->addmask,
 						     cs->effective_xcpus,
 						     parent->effective_xcpus);
+		} else if ((parent_prs == PRS_ISOLATED) &&
+			   ((old_prs == PRS_ROOT) || (old_prs == -PRS_ROOT))) {
+			part_error = PERR_ISOPARENT;
+			if (old_prs == PRS_ROOT) {
+				cpumask_copy(tmp->addmask, cs->effective_xcpus);
+				adding = true;
+			}
 		} else if (is_partition_invalid(cs) && !cpumask_empty(xcpus) &&
 			   cpumask_subset(xcpus, parent->effective_xcpus)) {
 			struct cgroup_subsys_state *css;
@@ -3025,6 +3037,7 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 	int err = PERR_NONE, old_prs = cs->partition_root_state;
 	struct cpuset *parent = parent_cs(cs);
 	struct tmpmasks tmpmask;
+	int parent_prs = parent->partition_root_state;
 	bool isolcpus_updated = false;
 	bool disable_partition = false;
 
@@ -3074,6 +3087,14 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 			enum partition_cmd cmd = (new_prs == PRS_ROOT)
 					       ? partcmd_enable : partcmd_enablei;
 
+			/*
+			 * It is not allowed to create a root partition under
+			 * an isolated parent partition.
+			 */
+			if ((new_prs == PRS_ROOT) && (parent_prs == PRS_ISOLATED)) {
+				err = PERR_ISOPARENT;
+				goto out;
+			}
 			err = update_parent_effective_cpumask(cs, cmd, NULL, &tmpmask);
 		} else {
 			err = remote_partition_enable(cs, new_prs, &tmpmask);
@@ -3087,12 +3108,15 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 		 * Need to update isolated_cpus.
 		 */
 		if (prstate_housekeeping_conflict(new_prs, parent_prs,
-						  cs->effective_xcpus, NULL)) {
-			disable_partition = true;
+						  cs->effective_xcpus, NULL))
 			err = PERR_HKEEPING;
-		} else {
+		else if (parent_prs == PRS_ISOLATED)
+			err = PERR_ISOPARENT;
+
+		if (!err)
 			isolcpus_updated = true;
-		}
+		else
+			disable_partition = true;
 	} else {
 		/*
 		 * Switching back to member is always allowed even if it
tools/testing/selftests/cgroup/test_cpuset_prs.sh +14 -9
index 6859cde73af1a..bb26a7da0ee73 100755
@@ -288,16 +288,14 @@ TEST_MATRIX=(
 								       A1:P0|A2:P1|A3:P0|B1:P1"
 	"   C0-3    C1-3   C3     C4    X2-3  X2-3:P1   P2     P1    0 A1:0-1|A2:2|A3:3|B1:4 \
 								       A1:P0|A2:P1|A3:P2|B1:P1 2-4|3"
-	"   C0-4    C1-4  C2-4     .    X2-4  X2-4:P2  X4:P1    .    0 A1:0-1|A2:2-3|A3:4 \
-								       A1:P0|A2:P2|A3:P1 2-4|2-3"
-	"   C0-4    C1-4  C2-4     .    X2-4  X2-4:P2 X3-4:P1   .    0 A1:0-1|A2:2|A3:3-4 \
-								       A1:P0|A2:P2|A3:P1 2"
+	"  C1-6:P1 C3-6:P1 C5-6:P1 .      .      P2      .      .    0 A1:1-2|A2:3-6|A3:5-6 \
+								       A1:P1|A2:P2|A3:P-1 3-6"
 	" C1-4:X2-4 C2-4:X3-4:P1 C3-4:X4:P2 \
 				   .      .      X5      .      .    0 A1:1-4|A2:2-4|A3:3-4 \
 								       A1:P0|A2:P-1|A3:P-2 ."
-	" C0-4:X2-4 C1-4:X2-4:P2 C2-4:X4:P1 \
-				   .      .      .      X1      .    0 A1:0-1|A2:2-4|A3:2-4 \
-								       A1:P0|A2:P2|A3:P-1 2-4"
+	" C1-4:X2-4 C1-4:X3-4:P1 C3-4:X4:P2 \
+				   .      .      .      X1      .    0 A1:1-2|A2:3-4|A3:3-4 \
+								       A1:P0|A2:P1|A3:P-2 ."
 	" CX1-3:P1 CX1-3  CX1-3    .      .      .      P1      .    0 A1:1-3|A2:1-3|A3:1-3 \
 								       A1:P1|A2:P0|A3:P-1"
 
@@ -331,8 +329,8 @@ TEST_MATRIX=(
 	" C0-3:X1-3:P2 C1-3:X2-3:P2 C2-3:X3:P2 \
 				   .      .    C4:X     .      .     0 A1:1-3|A2:1-3|A3:2-3|XA2:|XA3: A1:P2|A2:P-2|A3:P-2 1-3"
 	# Local partition CPU change tests
-	" C0-5:P2  C4-5:P1  .      .      .    C3-5     .      .     0 A1:0-2|A2:3-5 A1:P2|A2:P1 0-2"
-	" C0-5:P2  C4-5:P1  .      .    C1-5     .      .      .     0 A1:1-3|A2:4-5 A1:P2|A2:P1 1-3"
+	" C0-5:P1  C4-5:P2  .      .      .    C3-5     .      .     0 A1:0-2|A2:3-5 A1:P1|A2:P2 3-5"
+	" C0-5:P1  C4-5:P2  .      .    C1-5     .      .      .     0 A1:1-3|A2:4-5 A1:P1|A2:P2 4-5"
 
 	# cpus_allowed/exclusive_cpus update tests
 	" C0-3:X2-3 C1-3:X2-3 C2-3:X2-3 \
@@ -433,6 +431,13 @@ TEST_MATRIX=(
 	# cpuset.cpus can become empty with task in it as it inherits parent's effective CPUs
 	"   C1-3    C2      .      .       .    T:C     .      .     0 A1:1-3|A2:1-3"
 
+	# Creation of root partition under an isolated partition is not allowed
+	"  C1-3:P2  C2      .      .       .     P1     .      .     0 A1:1-3|A2:2 A1:P2|A2:P-1 1-3"
+	"  C1-3:P2  C2      .      .       .     P2     .      .     0 A1:1,3|A2:2 A1:P2|A2:P2  1-3"
+	"  C1-3:P2 C2:P2    .      .       .     P1     .      .     0 A1:1-3|A2:2 A1:P2|A2:P-1 1-3"
+	"  C1-3:P2 C2:P1    .      .       .    C2-3    .      .     0 A1:1-3|A2:2-3 A1:P2|A2:P-1 1-3"
+
+	#
 	#  old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS
 	#  ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ --------
 	# Failure cases:
Signature · 1 line
2.53.0
author maintainer
#2447 lore raw

PATCH 2424/2651 cgroup/cpuset: Properly compute effective xcpus in update_parent_effective_cpumask()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 69a75e4f377629928bd173747b864694c2af4e1c ]

Since the introduction of cpuset.cpus.exclusive in commit e2ffe502ba45 ("cgroup/cpuset: Add cpuset.cpus.exclusive for v2"), a compute_effective_exclusive_cpumask() helper which is later renamed to compute_excpus() is added to compute the effective xcpus of a partition root. However update_parent_effective_cpumask() is not updated in all proper places to use the new helper to check if a given cpuset should remain a valid partition root. This can cause a cpuset to incorrectly remain a valid partition root even if no effective xcpus is left.

Fix that problem by using compute_excpus() to compute the effective xcpus into delmask in all cases except partcmd_disable, partcmd_invalidate or partcmd_update with newmask set and use it for tasks_nocpu_error() check as well as checking its emptiness. This enables us to catch invalid partition root more accurately in update_parent_effective_cpumask().

In the case of partcmd_update with newmask set, the passed in new effective xcpus value will directly be used in the tasks_nocpu_error() check without relying on old data in the cpuset.

For the partcmd_update with NULL newmask case, the cpu exclusivity test there is also relaxed to be performed only if exclusive_cpus is empty.

Some test case are added to test_cpuset_prs.sh for invalidating a partition root due to its effective xcpus becoming empty as well as making sure that an invalid partition can only be revived when exclusive CPUs are available agin.

Fixes e2ffe502ba45 ("cgroup/cpuset: Add cpuset.cpus.exclusive for v2")
---
 kernel/cgroup/cpuset.c                        | 87 ++++++++++---------
 .../selftests/cgroup/test_cpuset_prs.sh       | 11 +++
 2 files changed, 56 insertions(+), 42 deletions(-)
kernel/cgroup/cpuset.c +45 -42
index 53f6e3c470f11..770956ec1393a 100644
@@ -1820,7 +1820,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
  * update_parent_effective_cpumask - update effective_cpus mask of parent cpuset
  * @cs:      The cpuset that requests change in partition root state
  * @cmd:     Partition root state change command
- * @newmask: Optional new cpumask for partcmd_update
+ * @newmask: Optional new effective xcpus for partcmd_update
  * @tmp:     Temporary addmask and delmask
  * Return:   0 or a partition root state error code
  *
@@ -1835,11 +1835,11 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
  * given back to parent's effective_cpus. 0 will always be returned.
  *
  * For partcmd_update, if the optional newmask is specified, the cpu list is
- * to be changed from effective_xcpus to newmask. Otherwise, effective_xcpus is
- * assumed to remain the same. The cpuset should either be a valid or invalid
- * partition root. The partition root state may change from valid to invalid
- * or vice versa. An error code will be returned if transitioning from
- * invalid to valid violates the exclusivity rule.
+ * to be changed from effective_xcpus to newmask. Otherwise, effective_xcpus
+ * will be computed and a valid partition will be invalidated if it is the new
+ * cpumask is empty. The cpuset should either be a valid or invalid partition
+ * root. The partition root state may change from valid to invalid or vice
+ * versa.
  *
  * For partcmd_invalidate, the current partition will be made invalid.
  *
@@ -1862,7 +1862,6 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 	int deleting;	/* Deleting cpus from parent's effective_cpus	*/
 	int old_prs, new_prs;
 	int part_error = PERR_NONE;	/* Partition error? */
-	struct cpumask *xcpus = user_xcpus(cs);
 	int parent_prs = parent->partition_root_state;
 	bool nocpu;
 
@@ -1905,30 +1904,30 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 	if (!newmask && xcpus_empty(cs))
 		return PERR_CPUSEMPTY;
 
-	nocpu = tasks_nocpu_error(parent, cs, xcpus);
+	/*
+	 * Except for partcmd_disable and non-NULL newmask, use delmask
+	 * to compute the current effective xcpus value and use it for
+	 * tasks_nocpu_error check.
+	 */
+	if ((cmd != partcmd_disable) && !newmask) {
+		compute_excpus(cs, tmp->delmask);
+		nocpu = tasks_nocpu_error(parent, cs, tmp->delmask);
+	}
 
 	if ((cmd == partcmd_enable) || (cmd == partcmd_enablei)) {
-		/*
-		 * Need to call compute_excpus() in case
-		 * exclusive_cpus not set. Sibling conflict should only happen
-		 * if exclusive_cpus isn't set.
-		 */
-		xcpus = tmp->delmask;
-		if (compute_excpus(cs, xcpus))
-			WARN_ON_ONCE(!cpumask_empty(cs->exclusive_cpus));
 		new_prs = (cmd == partcmd_enable) ? PRS_ROOT : PRS_ISOLATED;
 
 		/*
 		 * Enabling partition root is not allowed if its
 		 * effective_xcpus is empty.
 		 */
-		if (cpumask_empty(xcpus))
+		if (cpumask_empty(tmp->delmask))
 			return PERR_INVCPUS;
 
-		if (prstate_housekeeping_conflict(new_prs, parent_prs, xcpus, NULL))
+		if (prstate_housekeeping_conflict(new_prs, parent_prs, tmp->delmask, NULL))
 			return PERR_HKEEPING;
 
-		if (tasks_nocpu_error(parent, cs, xcpus))
+		if (nocpu)
 			return PERR_NOCPUS;
 
 		/*
@@ -1940,16 +1939,14 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		 *
 		 * Warn if it is not the case.
 		 */
-		cpumask_and(tmp->new_cpus, xcpus, cpu_active_mask);
+		cpumask_and(tmp->new_cpus, tmp->delmask, cpu_active_mask);
 		WARN_ON_ONCE(!cpumask_subset(tmp->new_cpus, parent->effective_cpus));
-
 		deleting = true;
 	} else if (cmd == partcmd_disable) {
 		/*
 		 * May need to add cpus back to parent's effective_cpus
 		 * (and maybe removed from subpartitions_cpus/isolated_cpus)
-		 * for valid partition root. xcpus may contain CPUs that
-		 * shouldn't be removed from the two global cpumasks.
+		 * for valid partition root.
 		 */
 		if (is_partition_valid(cs)) {
 			cpumask_copy(tmp->addmask, cs->effective_xcpus);
@@ -1969,8 +1966,8 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 			goto write_error;
 		}
 
-		/* Check newmask again, whether cpus are available for parent/cs */
-		nocpu |= tasks_nocpu_error(parent, cs, newmask);
+		/* Check newmask whether cpus are available for parent/cs */
+		nocpu = tasks_nocpu_error(parent, cs, newmask);
 
 		/*
 		 * partcmd_update with newmask:
@@ -2025,7 +2022,7 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		/*
 		 * partcmd_update w/o newmask
 		 *
-		 * delmask = effective_xcpus & parent->effective_cpus
+		 * delmask = newly computed effective xcpus value
 		 *
 		 * This can be called from:
 		 * 1) update_cpumasks_hier()
@@ -2037,7 +2034,7 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		 * A partition error happens when parent has tasks and all
 		 * its effective CPUs will have to be distributed out.
 		 */
-		if (nocpu) {
+		if (nocpu || cpumask_empty(tmp->delmask)) {
 			part_error = PERR_NOCPUS;
 			if (is_partition_valid(cs))
 				adding = cpumask_and(tmp->addmask,
@@ -2050,38 +2047,44 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 				cpumask_copy(tmp->addmask, cs->effective_xcpus);
 				adding = true;
 			}
-		} else if (is_partition_invalid(cs) && !cpumask_empty(xcpus) &&
-			   cpumask_subset(xcpus, parent->effective_xcpus)) {
+		} else if (is_partition_invalid(cs)) {
 			struct cgroup_subsys_state *css;
 			struct cpuset *child;
 			bool exclusive = true;
 
 			/*
 			 * Convert invalid partition to valid has to pass the
-			 * cpu exclusivity test as well as the housekeeping
-			 * check.
+			 * cpu exclusivity test when cpuset.cpus.exclusive is
+			 * empty as well as the housekeeping check.
 			 */
 			if (prstate_housekeeping_conflict(cs->partition_root_state,
-							  parent_prs, xcpus, NULL)) {
+							  parent_prs, tmp->delmask, NULL)) {
 				part_error = PERR_HKEEPING;
 				goto write_error;
 			}
-			rcu_read_lock();
-			cpuset_for_each_child(child, css, parent) {
-				if (child == cs)
-					continue;
-				if (!cpusets_are_exclusive(cs, child)) {
-					exclusive = false;
-					break;
+			if (cpumask_empty(cs->exclusive_cpus)) {
+				rcu_read_lock();
+				cpuset_for_each_child(child, css, parent) {
+					if (child == cs)
+						continue;
+					if (!cpusets_are_exclusive(cs, child)) {
+						exclusive = false;
+						break;
+					}
 				}
+				rcu_read_unlock();
 			}
-			rcu_read_unlock();
 			if (exclusive)
-				deleting = cpumask_and(tmp->delmask,
-						xcpus, parent->effective_cpus);
+				deleting = !cpumask_empty(tmp->delmask);
 			else
 				part_error = PERR_NOTEXCL;
 		}
+		/*
+		 * When both cs and parent remain valid, parent's
+		 * compute_partition_effective_cpumask() call would have removed
+		 * cs's effective_xcpus from the parent's effective_cpus. So
+		 * there is no need to adjust parent's effective_cpus here.
+		 */
 	}
 
 write_error:
tools/testing/selftests/cgroup/test_cpuset_prs.sh +11 -0
index bb26a7da0ee73..3b59433ae8be8 100755
@@ -290,6 +290,8 @@ TEST_MATRIX=(
 								       A1:P0|A2:P1|A3:P2|B1:P1 2-4|3"
 	"  C1-6:P1 C3-6:P1 C5-6:P1 .      .      P2      .      .    0 A1:1-2|A2:3-6|A3:5-6 \
 								       A1:P1|A2:P2|A3:P-1 3-6"
+	"  C1-6:P2 C3-6:P2 C3-4:P2 .      .     C5-6     .      .    0 A1:1-4|A2:5-6|A3:5-6 \
+								       A1:P2|A2:P2|A3:P-2 1-6"
 	" C1-4:X2-4 C2-4:X3-4:P1 C3-4:X4:P2 \
 				   .      .      X5      .      .    0 A1:1-4|A2:2-4|A3:3-4 \
 								       A1:P0|A2:P-1|A3:P-2 ."
@@ -358,6 +360,10 @@ TEST_MATRIX=(
 	# cpuset.cpus is allowed, but those extra CPUs are ignored.
 	"  C2-3:P1   C3:P1  .      .      .     C2-4    .      .     0 A1:|A2:2-3 A1:P1|A2:P1"
 
+	# A child cannot recover until its exclusive CPUs are available again.
+	" CX1-4:P1 CX3-4:P1 .     .     X1-2     .      .      .     0 A1:1-2|A2:1-2|XA2: A1:P1|A2:P-1"
+	" CX1-4:P1 CX3-4:P1 .     .  X1-2:X1-4   .      .      .     0 A1:1-2|A2:3-4|XA2:3-4 A1:P1|A2:P1"
+
 	# Taking away all CPUs from parent or itself if there are tasks
 	# will make the partition invalid.
 	"  C2-3:P1   C3:P1  .      .      T     C2-3    .      .     0 A1:2-3|A2:2-3 A1:P1|A2:P-1"
@@ -437,6 +443,11 @@ TEST_MATRIX=(
 	"  C1-3:P2 C2:P2    .      .       .     P1     .      .     0 A1:1-3|A2:2 A1:P2|A2:P-1 1-3"
 	"  C1-3:P2 C2:P1    .      .       .    C2-3    .      .     0 A1:1-3|A2:2-3 A1:P2|A2:P-1 1-3"
 
+	# A middle isolated parent shrunk below coverage: the released CPUs of
+	# an invalidated child stay isolated as a higher ancestor still covers them.
+	" CX0-4:P2 CX2-4:P2 CX3-4:P2 .     .     X2     .      .     0 A1:0-1,3-4|A2:2|A3:2 \
+								       A1:P2|A2:P2|A3:P-2 0-4"
+
 	#
 	#  old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS
 	#  ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ --------
Signature · 1 line
2.53.0
author maintainer
#2448 lore raw

PATCH 2425/2651 cgroup/cpuset: Fix incorrect effective_cpus bug in update_cpumasks_hier()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit d3873b45bea4cc99d135922cdc89841164f33855 ]

With the introduction of cpuset.cpus.exclusive, the computation of effective_cpus differs depending on if a cpuset is a valid partition root or not.

In update_cpumasks_hier(), effective_cpus is computed early to check if the current subtree can be skipped. Later on update_parent_effective_cpumask() may be called which can change the partition state from valid to invalid or vice versa. If the partition state changes, the previously computed effective_cpus may no longer be valid. Fix that by recomputing effective_cpus again when that happens.

Also add a new test case into test_cpuset_prs.sh to verify this change.

Fixes e2ffe502ba45 ("cgroup/cpuset: Add cpuset.cpus.exclusive for v2")
---
 kernel/cgroup/cpuset.c                            | 10 ++++++++--
 tools/testing/selftests/cgroup/test_cpuset_prs.sh |  3 +++
 2 files changed, 11 insertions(+), 2 deletions(-)
kernel/cgroup/cpuset.c +8 -2
index 770956ec1393a..731f96f42574f 100644
@@ -2368,10 +2368,16 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 		if (update_parent) {
 			update_parent_effective_cpumask(cp, partcmd_update, NULL, tmp);
 			/*
-			 * The cpuset partition_root_state may become
-			 * invalid. Capture it.
+			 * Capture current partition_root_state as it may have
+			 * changed. Recompute effective cpumask if changed.
 			 */
 			new_prs = cp->partition_root_state;
+			if (new_prs != old_prs) {
+				if (new_prs > 0)
+					compute_partition_effective_cpumask(cp, tmp->new_cpus);
+				else
+					compute_effective_cpumask(tmp->new_cpus, cp, parent);
+			}
 		}
 
 		spin_lock_irq(&callback_lock);
tools/testing/selftests/cgroup/test_cpuset_prs.sh +3 -0
index 3b59433ae8be8..644cf0d2a7c48 100755
@@ -295,6 +295,9 @@ TEST_MATRIX=(
 	" C1-4:X2-4 C2-4:X3-4:P1 C3-4:X4:P2 \
 				   .      .      X5      .      .    0 A1:1-4|A2:2-4|A3:3-4 \
 								       A1:P0|A2:P-1|A3:P-2 ."
+	" C1-5:X3-5:P2 C3-5:X4-5:P2 C4-5:X5:P2 \
+				   .    X1-4     .       .      .    0 A1:1-3|A2:4|A3:4 \
+								       A1:P2|A2:P2|A3:P-2 1-4"
 	" C1-4:X2-4 C1-4:X3-4:P1 C3-4:X4:P2 \
 				   .      .      .      X1      .    0 A1:1-2|A2:3-4|A3:3-4 \
 								       A1:P0|A2:P1|A3:P-2 ."
Signature · 1 line
2.53.0
author maintainer
#2449 lore raw

PATCH 2426/2651 cgroup/cpuset: Minor fixes to prstate_housekeeping_conflict()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 40702b2ca8fa08fb64b926d8c72a4909d0330580 ]

Commit 9527ff78a413 ("cgroup/cpuset: Consider all the exclusive CPUs when doing housekeeping check") changes the way prstate_housekeeping_conflict() is being used by considering all the exclusive xcpus to be owned by the partition when doing housekeeping check. However there are two minor issues reported by sashiko with that patch:

1) In partition_cpus_change(), prstate_housekeeping_conflict() can be called with an invalid partition root. In that case, there are no isolated CPUs that are going to be returned back to the system to become housekeeping CPUs, so the calculation of the del_cpus cpumask is meaningless.

2) The checking of del_cpus in prstate_housekeeping_conflict() to see if it can contain an active housekeeping CPU that can be returned to the system ignores the fact that an active CPU not in HK_TYPE_DOMAIN_BOOT HK cpumask will not become an active housekeeping CPU when it is released by an isolated partition.

Update the existing code to handle these two issues properly to make prstate_housekeeping_conflict() produce more accurate result.

Fixes 9527ff78a413 ("cgroup/cpuset: Consider all the exclusive CPUs when doing housekeeping check")
---
 kernel/cgroup/cpuset.c | 45 +++++++++++++++++++++++++++++-------------
 1 file changed, 31 insertions(+), 14 deletions(-)
kernel/cgroup/cpuset.c +31 -14
index 731f96f42574f..7e0ca4fae49eb 100644
@@ -1471,6 +1471,9 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 	    !cpumask_subset(new_cpus, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT)))
 		return true;
 
+	if (del_cpus && cpumask_empty(del_cpus))
+		del_cpus = NULL;
+
 	/*
 	 * Exit 2nd check early and return false if
 	 * 1) there is no boot time isolated nohz_full CPU
@@ -1479,8 +1482,7 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 	 *    be returned back to the parent.
 	 */
 	if (!housekeeping_enabled(HK_TYPE_KERNEL_NOISE) ||
-	    (new_prs == parent_prs) ||
-	    ((new_prs == PRS_ROOT) && (!del_cpus || cpumask_empty(del_cpus))))
+	    (new_prs == parent_prs) || (!del_cpus && (new_prs == PRS_ROOT)))
 		return false;
 
 	/*
@@ -1491,20 +1493,29 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 	if (parent_prs == PRS_ISOLATED)
 		swap(new_cpus, del_cpus);
 
-	if (del_cpus &&
-	   (cpumask_first_and_and(del_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
-				   cpu_active_mask) < nr_cpu_ids))
-		return false;
-
 	if (!alloc_cpumask_var(&full_hk_cpus, GFP_KERNEL))
 		return true;
 
+	/*
+	 * Check if del_cpus may contain a CPU that can become an active
+	 * housekeeping CPU again.
+	 */
+	if (del_cpus) {
+		cpumask_and(full_hk_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
+			    housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT));
+		if (cpumask_first_and_and(del_cpus, full_hk_cpus,
+					  cpu_active_mask) < nr_cpu_ids) {
+			res = false;
+			goto out;
+		}
+	}
+
 	cpumask_and(full_hk_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
 		    housekeeping_cpumask(HK_TYPE_DOMAIN));
 	cpumask_andnot(full_hk_cpus, full_hk_cpus, isolated_cpus);
 	cpumask_and(full_hk_cpus, full_hk_cpus, cpu_active_mask);
 	res = !cpumask_weight_andnot(full_hk_cpus, new_cpus);
-
+out:
 	free_cpumask_var(full_hk_cpus);
 	return res;
 }
@@ -2529,23 +2540,29 @@ static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs,
 				  struct tmpmasks *tmp)
 {
 	enum prs_errcode prs_err;
+	int parent_prs = is_remote_partition(cs)
+		       ? PRS_ROOT : parent_cs(cs)->partition_root_state;
 
 	if (cs_is_member(cs))
 		return;
 
 	prs_err = validate_partition(cs, trialcs);
-	if (!prs_err && !cpumask_empty(trialcs->effective_xcpus)) {
+	if (!prs_err && (parent_prs > 0) &&
+	    !cpumask_empty(trialcs->effective_xcpus)) {
 		int prs = cs->partition_root_state;
-		int parent_prs = is_remote_partition(cs)
-			       ? PRS_ROOT : parent_cs(cs)->partition_root_state;
+
 		/*
 		 * Check for housekeeping conflict by passing the whole
 		 * effective_xcpus as well as those CPUs that are to be
 		 * removed from cs as delmask.
 		 */
-		cpumask_andnot(tmp->delmask, cs->effective_xcpus, trialcs->effective_xcpus);
-		if (parent_prs > 0 &&
-		    prstate_housekeeping_conflict(prs, parent_prs,
+		if (prs > 0)
+			cpumask_andnot(tmp->delmask, cs->effective_xcpus,
+				       trialcs->effective_xcpus);
+		else
+			cpumask_clear(tmp->delmask);
+
+		if (prstate_housekeeping_conflict(prs, parent_prs,
 						  trialcs->effective_xcpus, tmp->delmask))
 			prs_err = PERR_HKEEPING;
 	}
Signature · 1 line
2.53.0
author maintainer
#2450 lore raw

PATCH 2427/2651 cgroup/cpuset: Prevent recursive call of remote_cpus_update() via update_cpumasks_hier()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 10a6f00d82544a1baa901de8d28f41f28c364995 ]

Guopeng reports that changing the cpumask of a remote partition root may set the effective_cpus of the top_cpuset incorrectly. It is due to the following call sequence:

update_cpumask()
-> partition_cpus_change()

    -> remote_cpus_update()
     -> update_sibling_cpumasks()
      -> update_cpumasks_hier()
       -> remote_cpus_update()

The second remote_cpus_update() call passes in the cs->effective_xcpus instead of the trialcs->effective_xcpus of the first remote_cpus_update() call. As a result, the second call can revert what has been done in the first call leading to incorrect effective_cpus of the top_cpuset as well as subpartitions_cpus.

Fix that by adding a new remote_partition_updating flag into the cpuset structure to indicate that a remote partition is being updated and update_cpumasks_hier() should skip the whole subtree as update_cpumask() or update_exclusive_cpumask() which calls partition_cpus_change() will eventually calls update_cpumasks_hier() for that subtree anyway.

This new flag is currently set only in remote_cpus_update() to prevent recursive call of remote_cpus_update() on the same cpuset.

A test case is added to test_cpuset_prs.sh to verify this change.

Fixes f62a5d39368e ("cgroup/cpuset: Remove remote_partition_check() & make update_cpumasks_hier() handle remote partition")
---
 kernel/cgroup/cpuset-internal.h                   |  5 +++++
 kernel/cgroup/cpuset.c                            | 13 +++++++++----
 tools/testing/selftests/cgroup/test_cpuset_prs.sh |  1 +
 3 files changed, 15 insertions(+), 4 deletions(-)
kernel/cgroup/cpuset-internal.h +5 -0
index 701c3854ec7ad..33990902cdc81 100644
@@ -161,6 +161,11 @@ struct cpuset {
 	 */
 	bool remote_partition;
 
+	/*
+	 * Set to true when a remote partition is undergoing update.
+	 */
+	bool remote_partition_updating;
+
 	/*
 	 * number of SCHED_DEADLINE tasks attached to this cpuset, so that we
 	 * know when to rebuild associated root domain bandwidth information.
kernel/cgroup/cpuset.c +9 -4
index 7e0ca4fae49eb..3abfd6c2387d8 100644
@@ -1800,6 +1800,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 			goto invalidate;
 	}
 
+	cs->remote_partition_updating = true;
 	spin_lock_irq(&callback_lock);
 	if (adding)
 		partition_xcpus_add(prs, NULL, tmp->addmask);
@@ -1821,6 +1822,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 	 */
 	cpuset_update_tasks_cpumask(&top_cpuset, tmp->new_cpus);
 	update_sibling_cpumasks(&top_cpuset, NULL, tmp);
+	cs->remote_partition_updating = false;
 	return;
 
 invalidate:
@@ -2278,16 +2280,19 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 		old_prs = new_prs = cp->partition_root_state;
 
 		/*
-		 * For child remote partition root (!= cs), we need to call
-		 * remote_cpus_update() if effective_xcpus will be changed.
-		 * Otherwise, we can skip the whole subtree.
+		 * For a child remote partition with remote_partition_updating
+		 * set, we can skip the whole subtree as the this function will
+		 * be called eventually. We can also skip the subtree if the
+		 * effective_xcpus isn't going to be changed. Otherwise, we
+		 * will have to call remote_cpus_update().
 		 *
 		 * remote_cpus_update() will reuse tmp->new_cpus only after
 		 * its value is being processed.
 		 */
 		if (remote && (cp != cs)) {
 			compute_excpus(cp, tmp->new_cpus);
-			if (cpumask_equal(cp->effective_xcpus, tmp->new_cpus)) {
+			if (cp->remote_partition_updating ||
+			    cpumask_equal(cp->effective_xcpus, tmp->new_cpus)) {
 				pos_css = css_rightmost_descendant(pos_css);
 				continue;
 			}
tools/testing/selftests/cgroup/test_cpuset_prs.sh +1 -0
index 644cf0d2a7c48..b7ddebb6eebec 100755
@@ -278,6 +278,7 @@ TEST_MATRIX=(
 	"   C0-3    C1-3  C2-3    C4    X2-3   X2-3  X2-3:P2 P2:C4-5 0 A3:2-3|B1:4-5 A3:P2|B1:P2 2-5"
 	"  C4:X0-3  X1-3  X2-3     .      .      P2     .      .     0 A1:4|A2:1-3|A3:1-3 A2:P2 1-3"
 	"  C4:X0-3  X1-3  X2-3     .      .      .      P2     .     0 A1:4|A2:4|A3:2-3 A3:P2 2-3"
+	"   CX1-6  C1-4:P1  .    C4-5     .    C1-3     .      .     0 A1:4-6|A2:1-3|B1:4-5 A2:P1"
 
 	# Nested remote/local partition tests
 	"   C0-3    C1-3  C2-3   C4-5   X2-3  X2-3:P1   P2     P1    0 A1:0-1|A2:|A3:2-3|B1:4-5 \
Signature · 1 line
2.53.0
author maintainer
#2451 lore raw

PATCH 2428/2651 cgroup/cpuset: Make sure compute_partition_effective_cpumask() is only called for valid partition

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 356a3aa7404e420e6f19c5ed42db7b8bd0c7ee9f ]

With visual inspection to make sure that compute_partition_effective_cpumask() is only called for valid partition root, it was found that the function can be called for an invalidated partition near the end of cpuset_hotplug_update_tasks(). When partcmd is set, update_parent_effective_cpumask() is called to either invalidate a valid partition or with partcmd_update to check if an invalid partition can be switched back to valid. In both cases, cpuset_force_rebuild() should be invoked. However, compute_partition_effective_cpumask() should only be called when an invalid partition is switched back to valid. When a partition is invalidated, compute_effective_cpumask() should be called instead.

Also add a WARN_ON_ONCE() in compute_partition_effective_cpumask() to ensure that a valid partition root is passed in.

Fixes 72c6303acfa1 ("cgroup/cpuset: Take isolated CPUs out of workqueue unbound cpumask")
---
 kernel/cgroup/cpuset.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
kernel/cgroup/cpuset.c +6 -1
index 3abfd6c2387d8..96c018c77838f 100644
@@ -2204,6 +2204,8 @@ static void compute_partition_effective_cpumask(struct cpuset *cs,
 	struct cpuset *child;
 	bool populated = partition_is_populated(cs, NULL);
 
+	WARN_ON_ONCE(!is_partition_valid(cs));
+
 	/*
 	 * Check child partition roots to see if they should be
 	 * invalidated when
@@ -4149,9 +4151,12 @@ static void cpuset_hotplug_update_tasks(struct cpuset *cs, struct tmpmasks *tmp)
 
 	if (partcmd >= 0) {
 		update_parent_effective_cpumask(cs, partcmd, NULL, tmp);
-		if ((partcmd == partcmd_invalidate) || is_partition_valid(cs)) {
+		if (is_partition_valid(cs)) {
 			compute_partition_effective_cpumask(cs, &new_cpus);
 			cpuset_force_rebuild();
+		} else if (partcmd == partcmd_invalidate) {
+			compute_effective_cpumask(&new_cpus, cs, parent);
+			cpuset_force_rebuild();
 		}
 	}
 
Signature · 1 line
2.53.0
author maintainer
#2452 lore raw

PATCH 2429/2651 cgroup/cpuset: Release invalid isolated CPUs in compute_partition_effective_cpumask()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit a7d89d92fdfbceb678d82710135d4eee2623d727 ]

It is found by sashiko that when a child isolated partition with parent root partition is invalidated in compute_partition_effective_cpumask(), the switching of the isolated exclusive CPUs from child to parent will not be reflected in isolated_cpus leading to CPU leakage. Fix that by calling isolated_cpus_update() when that happens.

Also simplify compute_partition_effective_cpumask() by doing child partition invalidation only for the special case of no more effective_cpus left in a populated parent. The other case doesn't actually warrant invalidation at this stage and subsequent iteration in update_cpumasks_hier() and update_parent_effective_cpumask() for that child should handle that.

Also drop the make_partition_invalid() helper by inlining it into compute_partition_effective_cpumask() as it is the only caller.

A new test case is add to test_cpuset_prs.sh to verify this.

Fixes 11e5f407b64a ("cgroup/cpuset: Keep track of CPUs in isolated partitions")
---
 kernel/cgroup/cpuset.c                        | 46 +++++++------------
 .../selftests/cgroup/test_cpuset_prs.sh       |  4 ++
 2 files changed, 21 insertions(+), 29 deletions(-)
kernel/cgroup/cpuset.c +17 -29
index 96c018c77838f..e7a2f812db9ed 100644
@@ -255,15 +255,6 @@ static inline bool cs_is_member(const struct cpuset *cs)
 	return cs->partition_root_state == PRS_MEMBER;
 }
 
-/*
- * Callers should hold callback_lock to modify partition_root_state.
- */
-static inline void make_partition_invalid(struct cpuset *cs)
-{
-	if (cs->partition_root_state > 0)
-		cs->partition_root_state = -cs->partition_root_state;
-}
-
 /*
  * Send notification event of whenever partition_root_state changes.
  */
@@ -2194,8 +2185,6 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
  * or update_cpumasks_hier() where parent and children are modified
  * successively, we don't need to call update_parent_effective_cpumask()
  * and the child's effective_cpus will be updated in later iterations.
- *
- * Note that rcu_read_lock() is assumed to be held.
  */
 static void compute_partition_effective_cpumask(struct cpuset *cs,
 						struct cpumask *new_ecpus)
@@ -2207,15 +2196,16 @@ static void compute_partition_effective_cpumask(struct cpuset *cs,
 	WARN_ON_ONCE(!is_partition_valid(cs));
 
 	/*
-	 * Check child partition roots to see if they should be
-	 * invalidated when
-	 *  1) child effective_xcpus not a subset of new
-	 *     excluisve_cpus
-	 *  2) All the effective_cpus will be used up and cp
-	 *     has tasks
+	 * Check child partition roots to see if they should be invalidated
+	 * when all the effective_cpus will be used up and cs is populated.
+	 * It is better to sacrifice a child partition root than invalidating
+	 * the whole subtree.
+	 *
+	 * Return early if the effective_cpus is already empty.
 	 */
 	compute_excpus(cs, new_ecpus);
-	cpumask_and(new_ecpus, new_ecpus, cpu_active_mask);
+	if (!cpumask_and(new_ecpus, new_ecpus, cpu_active_mask))
+		return;
 
 	rcu_read_lock();
 	cpuset_for_each_child(child, css, cs) {
@@ -2227,22 +2217,20 @@ static void compute_partition_effective_cpumask(struct cpuset *cs,
 		 * partition root.
 		 */
 		WARN_ON_ONCE(is_remote_partition(child));
-		WRITE_ONCE(child->prs_err, 0);
-		if (!cpumask_subset(child->effective_xcpus,
-				    cs->effective_xcpus))
-			WRITE_ONCE(child->prs_err, PERR_INVCPUS);
-		else if (populated &&
-			 cpumask_subset(new_ecpus, child->effective_xcpus))
-			WRITE_ONCE(child->prs_err, PERR_NOCPUS);
-
-		if (child->prs_err) {
+		if (populated && cpumask_subset(new_ecpus, child->effective_xcpus)) {
 			int old_prs = child->partition_root_state;
+			int parent_prs = cs->partition_root_state;
 
 			/*
-			 * Invalidate child partition
+			 * Invalidate child partition and update isolated_cpus
+			 * if necessary.
 			 */
 			spin_lock_irq(&callback_lock);
-			make_partition_invalid(child);
+			WRITE_ONCE(child->prs_err, PERR_NOCPUS);
+			if ((old_prs == PRS_ISOLATED) && (parent_prs == PRS_ROOT))
+				isolated_cpus_update(PRS_ISOLATED, PRS_ROOT,
+						     child->effective_xcpus);
+			child->partition_root_state = -old_prs;
 			spin_unlock_irq(&callback_lock);
 			notify_partition_change(child, old_prs);
 			continue;
tools/testing/selftests/cgroup/test_cpuset_prs.sh +4 -0
index b7ddebb6eebec..5f1229c06645e 100755
@@ -452,6 +452,10 @@ TEST_MATRIX=(
 	" CX0-4:P2 CX2-4:P2 CX3-4:P2 .     .     X2     .      .     0 A1:0-1,3-4|A2:2|A3:2 \
 								       A1:P2|A2:P2|A3:P-2 0-4"
 
+	# When an isolated partition child with root partition parent is invalidated,
+	# its effective xcpus will be removed from isolated_cpus.
+	" C1-4:P1 C3-4:P2   .      .    T:C3-4   .      .      .     0 A1:3-4|A2:3-4 A1:P1|A2:P-2 ."
+
 	#
 	#  old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS
 	#  ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ --------
Signature · 1 line
2.53.0
author maintainer
#2453 lore raw

PATCH 2430/2651 cgroup/cpuset: Release invalid isolated CPUs with a shrunk root partition parent

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit ec0254b9eb49ebc9383dc3ae5cb69c8606f88499 ]

It is also reported by sashiko that there may be leakages of isolated CPUs when a root partition parent shrinks its effective_xcpus with isolated partition children. Leakage here means that isolated_cpus may contain extra CPUs that are not in any isolated partitions and not boot time isolated. Those CPUs cannot be used in any isolated partitions anymore.

There are 2 different cases here. The effective_xcpus becomes empty and the isolated partition should be invalidated in this case. Alternatively some of its effective_xcpus are not in parent's effective xcpus but still have some valid effective_xcpus left. The isolated partition can remain valid. In both cases, the invalid isolated CPUs will have to be released from isolated_cpus if appropriate.

Fix that by calling isolated_cpus_release() to release those isolated CPUs from isolated_cpus.

New test cases are added to test_cpuset_prs.sh to test this.

Fixes 11e5f407b64a ("cgroup/cpuset: Keep track of CPUs in isolated partitions")
---
 kernel/cgroup/cpuset.c                           | 16 +++++++++++++++-
 .../testing/selftests/cgroup/test_cpuset_prs.sh  |  6 ++++++
 2 files changed, 21 insertions(+), 1 deletion(-)
kernel/cgroup/cpuset.c +15 -1
index e7a2f812db9ed..6f336ace3033a 100644
@@ -2037,8 +2037,22 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		 *
 		 * A partition error happens when parent has tasks and all
 		 * its effective CPUs will have to be distributed out.
+		 *
+		 * For an isolated partition with a shrunk root partition parent
+		 * we may need to return some or all of its isolated CPUs.
 		 */
-		if (nocpu || cpumask_empty(tmp->delmask)) {
+		nocpu |= cpumask_empty(tmp->delmask);
+		if ((parent_prs == PRS_ROOT) && (old_prs == PRS_ISOLATED)) {
+			cpumask_clear(tmp->addmask);
+			if (nocpu)
+				cpumask_copy(tmp->addmask, cs->effective_xcpus);
+			else if (!cpumask_subset(cs->effective_xcpus, parent->effective_xcpus))
+				cpumask_andnot(tmp->addmask, cs->effective_xcpus,
+							     parent->effective_xcpus);
+			if (!cpumask_empty(tmp->addmask))
+				isolated_cpus_release(cs, tmp->addmask);
+		}
+		if (nocpu) {
 			part_error = PERR_NOCPUS;
 			if (is_partition_valid(cs))
 				adding = cpumask_and(tmp->addmask,
tools/testing/selftests/cgroup/test_cpuset_prs.sh +6 -0
index 5f1229c06645e..78ed0500e11db 100755
@@ -456,6 +456,12 @@ TEST_MATRIX=(
 	# its effective xcpus will be removed from isolated_cpus.
 	" C1-4:P1 C3-4:P2   .      .    T:C3-4   .      .      .     0 A1:3-4|A2:3-4 A1:P1|A2:P-2 ."
 
+	# When a root partition parent with an isolated partition child is shrunk
+	# so that its effective xcpus is no longer a superset of its child effective
+	# xcpus, the invalid isolated CPUs should be removed from cpuset.cpus.isolated.
+	" C1-4:P1 C3-4:P2   .      .    T:C4-6   .      .      .     0 A1:5-6|A2:4 A1:P1|A2:P2 4"
+	" C1-4:P1 C1-2:P2   .      .    T:C4-6   .      .      .     0 A1:4-6|A2:4-6 A1:P1|A2:P-2 ."
+
 	#
 	#  old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS
 	#  ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ --------
Signature · 1 line
2.53.0
author maintainer
#2454 lore raw

PATCH 2431/2651 block: advance iterator after copy-in for SG_DXFER_TO_FROM_DEV

In reply to Greg Kroah-Hartman

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

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

From: TJ Adams <[email protected]>

[ Upstream commit 82e72ea18d0af724914c31a1f274c1aef452aad0 ]

When a passthrough request uses transfer direction SG_DXFER_TO_FROM_DEV, bio_copy_user_iov() sets up a temporary iterator iter2 with data_source = ITER_SOURCE to copy user data into the bio pages before execution.

bio_copy_from_iter(bio, &iter2) copies the data and advances iter2, but the original iter is never advanced. Consequently, iov_iter_count(&i) remains non-zero in the caller loop in blk_rq_map_user_iov():

	i = *iter;
	do {
		if (copy)
			ret = bio_copy_user_iov(rq, map_data, &i, gfp_mask);
...
	} while (iov_iter_count(&i));

Because i is never advanced, blk_rq_map_user_iov() loops indefinitely, continually allocating bios and consuming map_data pages until it exhausts pages and fails with -EINVAL.

Fix this by calling iov_iter_advance(iter, bio->bi_iter.bi_size) in the map_data && map_data->from_user branch after bio_copy_from_iter().

Fixes 13f3956eb568 ("block: Fix WARNING in _copy_from_iter")
Assisted-by LLM
---
 block/blk-map.c | 1 +
 1 file changed, 1 insertion(+)
block/blk-map.c +1 -0
index 9cb9605d1f62d..2685f6177ceb6 100644
@@ -236,6 +236,7 @@ static int bio_copy_user_iov(struct request *rq, struct rq_map_data *map_data,
 		ret = bio_copy_from_iter(bio, &iter2);
 		if (ret)
 			goto cleanup;
+		iov_iter_advance(iter, bio->bi_iter.bi_size);
 	} else {
 		if (bmd->is_our_pages)
 			zero_fill_bio(bio);
Signature · 1 line
2.53.0
author maintainer
#2455 lore raw

PATCH 2432/2651 spi: cs42l43: Add speaker ID quirk for Dell XPS 13 DX13260 SKU 0E54

In reply to Greg Kroah-Hartman

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

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

From: Jérémie Rodon <[email protected]>

[ Upstream commit 7da2aca123754c0e06092bbe179d58078b58d8d4 ]

The Dell XPS 13 DX13260 is also sold with SKU 0E54, which has the same ACPI speaker ID layout as SKU 0E53: two pins in one GpioIo() while the spk-id-gpios _DSD property references only the first. Without the quirk the speaker ID is wrong (0), so there is no speaker audio and no amp firmware is loaded.

Add a DMI entry for SKU 0E54 using the same handler.

Fixes cad16d850e37 ("spi: cs42l43: Workaround for wrong speaker ID on Dell XPS 13 DX13260")
---
 drivers/spi/spi-cs42l43.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/spi/spi-cs42l43.c +8 -0
index 6772abb483dd3..46eeb44130dd5 100644
@@ -301,6 +301,14 @@ static const struct dmi_system_id cs42l43_spk_id_quirks[] = {
 		},
 		.driver_data = cs42l43_get_2bit_speaker_id_from_one_gpioio,
 	},
+	{
+		.ident = "Dell XPS 13 DX13260",
+		.matches = {
+			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc"),
+			DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "0E54"),
+		},
+		.driver_data = cs42l43_get_2bit_speaker_id_from_one_gpioio,
+	},
 	{ }
 };
 
Signature · 1 line
2.53.0
author maintainer
#2456 lore raw

PATCH 2433/2651 selftests/thermal: allow cross builds of the Intel tests

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit ff4194e54f840b4df4eb2489c63ee88283895efc ]

The power_floor and workload_hint Makefiles build nothing when CROSS_COMPILE is set, even for an x86 target, and they include lib.mk only on x86. Other architectures therefore have no install or emit_tests rules for these suites, and their installation fails with a missing target.

Select the x86 tests from the target ARCH when it is given and from the host's SUBARCH otherwise, and include lib.mk unconditionally so that the suites install and emit an empty runlist on other architectures. Use a private ARCH_PROCESSED instead of the ARCH override added by commit 5a1292137e89 ("selftests: fix ARCH normalization to handle command-line argument"): the override changed the value lib.mk uses to pick the clang target, whereas leaving ARCH unset lets lib.mk use the compiler's native triple. A command-line ARCH such as x86_64 is still normalized for the selection, while an ARCH spelling that lib.mk does not know, such as i686 with LLVM=1, is rejected as in other selftests.

Fixes 27801542b2b8 ("selftests/thermel/intel: Add test to read workload hint")
Fixes d4d27e5a1a88 ("selftests/thermel/intel: Add test to read power floor status")
---
 .../selftests/thermal/intel/power_floor/Makefile     | 12 +++++-------
 .../selftests/thermal/intel/workload_hint/Makefile   | 12 +++++-------
 2 files changed, 10 insertions(+), 14 deletions(-)
tools/testing/selftests/thermal/intel/power_floor/Makefile +5 -7
index 07463c2160e09..16d26eab55652 100644
@@ -1,12 +1,10 @@
 # SPDX-License-Identifier: GPL-2.0
-ifndef CROSS_COMPILE
-ARCH ?= $(shell uname -m 2>/dev/null || echo not)
-override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
+top_srcdir = ../../../../../..
+include $(top_srcdir)/scripts/subarch.include
+ARCH_PROCESSED := $(shell echo $(or $(ARCH),$(SUBARCH)) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
 
-ifeq ($(ARCH),x86)
+ifeq ($(ARCH_PROCESSED),x86)
 TEST_GEN_PROGS := power_floor_test
+endif
 
 include ../../../lib.mk
-
-endif
-endif
tools/testing/selftests/thermal/intel/workload_hint/Makefile +5 -7
index 49e3bc2b20f9d..e53d6ecd9f8de 100644
@@ -1,12 +1,10 @@
 # SPDX-License-Identifier: GPL-2.0
-ifndef CROSS_COMPILE
-ARCH ?= $(shell uname -m 2>/dev/null || echo not)
-override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
+top_srcdir = ../../../../../..
+include $(top_srcdir)/scripts/subarch.include
+ARCH_PROCESSED := $(shell echo $(or $(ARCH),$(SUBARCH)) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
 
-ifeq ($(ARCH),x86)
+ifeq ($(ARCH_PROCESSED),x86)
 TEST_GEN_PROGS := workload_hint_test
+endif
 
 include ../../../lib.mk
-
-endif
-endif
Signature · 1 line
2.53.0
author maintainer
#2457 lore raw

PATCH 2434/2651 PM: suspend: Do not call suspend_ops->begin()/end() for s2idle

In reply to Greg Kroah-Hartman

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

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

From: Ovidiu Panait <[email protected]>

[ Upstream commit 4785d5faa935a828a04743c5a7d279baf454c723 ]

Commit 7602c0ec0bbf ("firmware: psci: Set pm_set_resume/suspend_via_firmware() for SYSTEM_SUSPEND") made psci_system_suspend_begin() call pm_set_suspend_via_firmware(), so that device drivers can prepare for the possible removal of the power before PSCI SYSTEM_SUSPEND.

Since then, on platforms where PSCI firmware supports SYSTEM_SUSPEND, pm_suspend_via_firmware() returns true during both s2ram and s2idle. This is inconsistent, since SYSTEM_SUSPEND is only invoked for s2ram.

This was observed while investigating PCI-related suspend/resume issues on Renesas platforms (RZ/G3S, RZ/V2H), and was traced to platform_suspend_begin() falling back to suspend_ops->begin() (PSCI in this case) when there is no s2idle_ops->begin() callback:

platform_suspend_begin(PM_SUSPEND_TO_IDLE)

    suspend_ops->begin()
      psci_system_suspend_begin()
        pm_set_suspend_via_firmware()

platform_resume_end() falls back to suspend_ops->end() in the same way.

Since s2idle has its own set of callbacks in s2idle_ops, make platform_suspend_begin() and platform_resume_end() only invoke those for s2idle, like the other platform_*() helpers do.

Fixes 7602c0ec0bbf ("firmware: psci: Set pm_set_resume/suspend_via_firmware() for SYSTEM_SUSPEND")
[ rjw: Added Fixes: tag ]
---
 kernel/power/suspend.c | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)
kernel/power/suspend.c +12 -8
index 57c44268698f7..32c055df02da7 100644
@@ -306,20 +306,24 @@ static void platform_resume_finish(suspend_state_t state)
 
 static int platform_suspend_begin(suspend_state_t state)
 {
-	if (state == PM_SUSPEND_TO_IDLE && s2idle_ops && s2idle_ops->begin)
-		return s2idle_ops->begin();
-	else if (suspend_ops && suspend_ops->begin)
+	if (state == PM_SUSPEND_TO_IDLE) {
+		if (s2idle_ops && s2idle_ops->begin)
+			return s2idle_ops->begin();
+	} else if (suspend_ops && suspend_ops->begin) {
 		return suspend_ops->begin(state);
-	else
-		return 0;
+	}
+
+	return 0;
 }
 
 static void platform_resume_end(suspend_state_t state)
 {
-	if (state == PM_SUSPEND_TO_IDLE && s2idle_ops && s2idle_ops->end)
-		s2idle_ops->end();
-	else if (suspend_ops && suspend_ops->end)
+	if (state == PM_SUSPEND_TO_IDLE) {
+		if (s2idle_ops && s2idle_ops->end)
+			s2idle_ops->end();
+	} else if (suspend_ops && suspend_ops->end) {
 		suspend_ops->end();
+	}
 }
 
 static void platform_recover(suspend_state_t state)
Signature · 1 line
2.53.0
author maintainer
#2458 lore raw

PATCH 2435/2651 thermal: Fix CPU mask truncation in power limit trace event

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

[ Upstream commit 82c9c94f54a444a686e926c872dae4b198d1036f ]

num_possible_cpus() counts CPUs, but CPU IDs need not be contiguous. Using it to size the thermal_power_cpu_limit bitmap can omit CPUs with higher IDs. For example, possible CPUs 0 and 64 produce an eight-byte bitmap on a 64-bit system, dropping CPU 64.

Use nr_cpumask_bits for both sizing and copying the bitmap.

Fixes 6828a4711f99 ("thermal: add trace events to the power allocator governor")
---
 drivers/thermal/thermal_trace.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/thermal/thermal_trace.h +2 -2
index df8f4edd6068a..2f953fd8289dd 100644
@@ -119,7 +119,7 @@ TRACE_EVENT(thermal_power_cpu_limit,
 	TP_ARGS(cpus, freq, cdev_state, power),
 
 	TP_STRUCT__entry(
-		__bitmask(cpumask, num_possible_cpus())
+		__bitmask(cpumask, nr_cpumask_bits)
 		__field(unsigned int,  freq      )
 		__field(unsigned long, cdev_state)
 		__field(u32,           power     )
@@ -127,7 +127,7 @@ TRACE_EVENT(thermal_power_cpu_limit,
 
 	TP_fast_assign(
 		__assign_bitmask(cpumask, cpumask_bits(cpus),
-				num_possible_cpus());
+				nr_cpumask_bits);
 		__entry->freq = freq;
 		__entry->cdev_state = cdev_state;
 		__entry->power = power;
Signature · 1 line
2.53.0
author maintainer
#2459 lore raw

PATCH 2436/2651 ASoC: codecs: wsa884x: disable runtime PM on unbind

In reply to Greg Kroah-Hartman

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

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

From: Srinivas Kandagatla <[email protected]>

[ Upstream commit 54c121eaeed8ee7751935db8100b6b5c57124db9 ]

Probe enables runtime PM but nothing disables it on unbind. The pending autosuspend then runs wsa884x_runtime_suspend() after the devm-managed regmap is freed, and dereferences NULL:

  Unable to handle kernel NULL pointer dereference at virtual address 0000000000000020
  pc : regcache_cache_only+0x18/0x80
  lr : wsa884x_runtime_suspend+0x24/0x40 [snd_soc_wsa884x]

Use devm_pm_runtime_enable() so runtime PM is disabled before the regmap is freed.

Fixes aa21a7d4f68a ("ASoC: codecs: wsa884x: Add WSA884x family of speakers")
---
 sound/soc/codecs/wsa884x.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
sound/soc/codecs/wsa884x.c +3 -1
index f0857c0588d51..3c008224d32e8 100644
@@ -2125,7 +2125,9 @@ static int wsa884x_probe(struct sdw_slave *pdev,
 	pm_runtime_use_autosuspend(dev);
 	pm_runtime_mark_last_busy(dev);
 	pm_runtime_set_active(dev);
-	pm_runtime_enable(dev);
+	ret = devm_pm_runtime_enable(dev);
+	if (ret)
+		return ret;
 
 	return devm_snd_soc_register_component(dev,
 					       &wsa884x_component_drv,
Signature · 1 line
2.53.0
author maintainer
#2460 lore raw

PATCH 2437/2651 ASoC: codecs: wsa883x: disable runtime PM on unbind

In reply to Greg Kroah-Hartman

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

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

From: Srinivas Kandagatla <[email protected]>

[ Upstream commit ea63182d71956dc33c6f08dc4171f1052f8409a9 ]

Probe enables runtime PM but nothing disables it on unbind, or when registering the component fails. A pending autosuspend can then run wsa883x_runtime_suspend() after the devm-managed regmap is freed, and dereference NULL, as seen on wsa884x.

Use devm_pm_runtime_enable() so runtime PM is disabled before the regmap is freed.

Fixes 43b8c7dc85a1 ("ASoC: codecs: add wsa883x amplifier support")
---
 sound/soc/codecs/wsa883x.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
sound/soc/codecs/wsa883x.c +3 -1
index ccd4404c1644e..b09ee3db7ed58 100644
@@ -1669,7 +1669,9 @@ static int wsa883x_probe(struct sdw_slave *pdev,
 	pm_runtime_use_autosuspend(dev);
 	pm_runtime_mark_last_busy(dev);
 	pm_runtime_set_active(dev);
-	pm_runtime_enable(dev);
+	ret = devm_pm_runtime_enable(dev);
+	if (ret)
+		goto err;
 
 	ret = devm_snd_soc_register_component(dev,
 					      &wsa883x_component_drv,
Signature · 1 line
2.53.0
author maintainer
#2461 lore raw

PATCH 2438/2651 ASoC: codecs: wsa884x: Fix VI sense port channel count

In reply to Greg Kroah-Hartman

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

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

From: Ravi Hothi <[email protected]>

[ Upstream commit a6093f98cbfc4a717ef3d1048b0e38fb2035be98 ]

The VI sense port carries both the voltage and the current sense data of the speaker, but it is described with max_ch = 1 and, since commit 060fac202eb8 ("ASoC: codecs: wsa884x: Correct VI sense channel mask"), a channel mask of 0x1, so only half of the V/I pair is transferred.

Describe the port as two channels and set the channel mask back to 0x3.

Fixes 060fac202eb8 ("ASoC: codecs: wsa884x: Correct VI sense channel mask")
Cc Krzysztof Kozlowski <[email protected]>
---
 sound/soc/codecs/wsa884x.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
sound/soc/codecs/wsa884x.c +2 -2
index 3c008224d32e8..acf32af5aae3e 100644
@@ -859,7 +859,7 @@ static struct sdw_dpn_prop wsa884x_sink_dpn_prop[WSA884X_MAX_SWR_PORTS] = {
 		.num = WSA884X_PORT_VISENSE + 1,
 		.type = SDW_DPN_SIMPLE,
 		.min_ch = 1,
-		.max_ch = 1,
+		.max_ch = 2,
 		.simple_ch_prep_sm = true,
 		.read_only_wordlength = true,
 	},
@@ -892,7 +892,7 @@ static const struct sdw_port_config wsa884x_pconfig[WSA884X_MAX_SWR_PORTS] = {
 	},
 	[WSA884X_PORT_VISENSE] = {
 		.num = WSA884X_PORT_VISENSE + 1,
-		.ch_mask = 0x1,
+		.ch_mask = 0x3,
 	},
 	[WSA884X_PORT_CPS] = {
 		.num = WSA884X_PORT_CPS + 1,
Signature · 1 line
2.53.0
author maintainer
#2462 lore raw

PATCH 2439/2651 ASoC: codecs: wsa883x: Fix VI sense port channel count

In reply to Greg Kroah-Hartman

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

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

From: Ravi Hothi <[email protected]>

[ Upstream commit 9728b328d7adf228d5f691d0ec43bb7a6d07e44b ]

The VI sense port carries both the voltage and the current sense data of the speaker, but it is described with max_ch = 1 and, since commit ed3b274abc40 ("ASoC: codecs: wsa883x: Correct VI sense channel mask"), a channel mask of 0x1, so only half of the V/I pair is transferred.

Describe the port as two channels and set the channel mask back to 0x3.

Fixes ed3b274abc40 ("ASoC: codecs: wsa883x: Correct VI sense channel mask")
Cc Krzysztof Kozlowski <[email protected]>
---
 sound/soc/codecs/wsa883x.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
sound/soc/codecs/wsa883x.c +2 -2
index b09ee3db7ed58..17d8babc6123b 100644
@@ -552,7 +552,7 @@ static struct sdw_dpn_prop wsa_sink_dpn_prop[WSA883X_MAX_SWR_PORTS] = {
 		.num = WSA883X_PORT_VISENSE + 1,
 		.type = SDW_DPN_SIMPLE,
 		.min_ch = 1,
-		.max_ch = 1,
+		.max_ch = 2,
 		.simple_ch_prep_sm = true,
 		.read_only_wordlength = true,
 	}
@@ -573,7 +573,7 @@ static const struct sdw_port_config wsa883x_pconfig[WSA883X_MAX_SWR_PORTS] = {
 	},
 	[WSA883X_PORT_VISENSE] = {
 		.num = WSA883X_PORT_VISENSE + 1,
-		.ch_mask = 0x1,
+		.ch_mask = 0x3,
 	},
 };
 
Signature · 1 line
2.53.0