Skip to contentSkip to conversation

7.2.6-rc1 review

PATCH Applied Greg Kroah-Hartman 19 participants 1,845 messages Sep 12 – Sep 16 Page 12 of 14

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

PATCH 1460/1815 ACPI: bus: Introduce acpi_bus_get_primary_device()

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 72530e1f72b0515a73fd88292254d04fecf03649 ]

The function used for obtaining the first "physical" device for which the given ACPI one is the ACPI companion, acpi_get_first_physical_node(), may return a stale device pointer (mostly in theory) because acpi_unbind_one() may run as a whole after dropping the ACPI device's physical_node_lock in acpi_get_first_physical_node() and before it returns. The last reference to the "physical" device may be dropped then before the pointer to it is returned to the caller.

If that happens and the acpi_get_first_physical_node() caller invokes get_device() on the pointer obtained from it, which is done by the majority of its callers, a use-after-free will occur.

To prepare for addressing this problem, introduce a new function for getting the first "physical" device associated with the given ACPI one (the "primary physical device") that will also reference count the device in question before returning a pointer to it.

Make that new function and acpi_get_first_physical_node() share the physical node list lookup code.

No intentional functional impact.

Stable-dep-of: a9ba4dd2f18b ("ACPI: platform: Use acpi_bus_get_primary_device()")

---
 drivers/acpi/bus.c      | 54 +++++++++++++++++++++++++++++------------
 include/acpi/acpi_bus.h |  6 +++++
 2 files changed, 44 insertions(+), 16 deletions(-)
drivers/acpi/bus.c +38 -16
index 8614b8140ef71..7a2458b00a661 100644
@@ -809,30 +809,52 @@ static int __init acpi_setup_sb_notify_handler(void)
                              Device Matching
    -------------------------------------------------------------------------- */
 
+
+static struct device *primary_physical_device(struct acpi_device *adev)
+{
+	struct acpi_device_physical_node *pn;
+
+	pn = list_first_entry_or_null(&adev->physical_node_list,
+				      struct acpi_device_physical_node, node);
+	if (pn)
+		return pn->dev;
+
+	return NULL;
+}
+
+/**
+ * acpi_bus_get_primary_device - Get first physical device for a given ACPI one
+ * @adev: ACPI device to get the first physical device for.
+ *
+ * Find the first physical device for which @adev is the ACPI companion and
+ * reference count it if present.
+ *
+ * Return: Pointer to the first physical counterpart of @adev or NULL if there
+ * are none.  Callers are responsible for invoking put_device() on the returned
+ * device.
+ */
+struct device *acpi_bus_get_primary_device(struct acpi_device *adev)
+{
+	if (!adev)
+		return NULL;
+
+	guard(mutex)(&adev->physical_node_lock);
+
+	return get_device(primary_physical_device(adev));
+}
+EXPORT_SYMBOL_GPL(acpi_bus_get_primary_device);
+
 /**
- * acpi_get_first_physical_node - Get first physical node of an ACPI device
+ * acpi_get_first_physical_node - Find first physical node of an ACPI device
  * @adev:	ACPI device in question
  *
  * Return: First physical node of ACPI device @adev
  */
 struct device *acpi_get_first_physical_node(struct acpi_device *adev)
 {
-	struct mutex *physical_node_lock = &adev->physical_node_lock;
-	struct device *phys_dev;
-
-	mutex_lock(physical_node_lock);
-	if (list_empty(&adev->physical_node_list)) {
-		phys_dev = NULL;
-	} else {
-		const struct acpi_device_physical_node *node;
+	guard(mutex)(&adev->physical_node_lock);
 
-		node = list_first_entry(&adev->physical_node_list,
-					struct acpi_device_physical_node, node);
-
-		phys_dev = node->dev;
-	}
-	mutex_unlock(physical_node_lock);
-	return phys_dev;
+	return primary_physical_device(adev);
 }
 EXPORT_SYMBOL_GPL(acpi_get_first_physical_node);
 
include/acpi/acpi_bus.h +6 -0
index 714d111d80530..61782dfdfe5a5 100644
@@ -686,6 +686,7 @@ void acpi_bus_unregister_driver(struct acpi_driver *driver);
 int acpi_bus_scan(acpi_handle handle);
 void acpi_bus_trim(struct acpi_device *start);
 acpi_status acpi_bus_get_ejd(acpi_handle handle, acpi_handle * ejd);
+struct device *acpi_bus_get_primary_device(struct acpi_device *adev);
 int acpi_match_device_ids(struct acpi_device *device,
 			  const struct acpi_device_id *ids);
 void acpi_set_modalias(struct acpi_device *adev, const char *default_id,
@@ -1000,6 +1001,11 @@ int acpi_scan_add_dep(acpi_handle handle, struct acpi_handle_list *dep_devices);
 u32 arch_acpi_add_auto_dep(acpi_handle handle);
 #else	/* CONFIG_ACPI */
 
+static inline struct device *acpi_bus_get_primary_device(struct acpi_device *adev)
+{
+	return NULL;
+}
+
 static inline bool acpi_of_match_device(const struct acpi_device *adev,
 					const struct of_device_id *of_match_table,
 					const struct of_device_id **of_id)
Signature · 1 line
2.53.0
author maintainer
#1477 lore raw

PATCH 1461/1815 ACPI: platform: Use acpi_bus_get_primary_device()

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit a9ba4dd2f18bf3f439d9ef0d8f375f90360ba1bd ]

The acpi_get_first_physical_node() usage in acpi_platform_fill_resource() and acpi_create_platform_device() is generally unsafe because in theory the device returned by it may be freed at any time [1].

It is also inefficient because acpi_get_first_physical_node() is called multiple times for the same argument which can be avoided.

Address these issues by using acpi_bus_get_primary_device() instead of acpi_get_first_physical_node() and adjusting the code to call it just once at the beginning of and acpi_create_platform_device() and drop the device reference acquired by it upon the return from that function.

Fixes 3b95bd160547 ("ACPI: introduce a function to find the first physical device")
Fixes a252d881c558 ("ACPI / platform: Pay attention to parent device's resources")
---
 drivers/acpi/acpi_platform.c | 16 +++++++---------
 1 file changed, 7 insertions(+), 9 deletions(-)
drivers/acpi/acpi_platform.c +7 -9
index e3c77a65f61c8..80ea7121744d0 100644
@@ -108,18 +108,15 @@ static unsigned int acpi_platform_adjust_resources(struct acpi_device *adev,
 	return count;
 }
 
-static void acpi_platform_fill_resource(struct acpi_device *adev,
-	const struct resource *src, struct resource *dest)
+static void acpi_platform_fill_resource(struct device *parent,
+					const struct resource *src,
+					struct resource *dest)
 {
-	struct device *parent;
-
 	*dest = *src;
-
 	/*
 	 * If the device has parent we need to take its resources into
 	 * account as well because this device might consume part of those.
 	 */
-	parent = acpi_get_first_physical_node(acpi_dev_parent(adev));
 	if (parent && dev_is_pci(parent))
 		dest->parent = pci_find_resource(to_pci_dev(parent), dest);
 }
@@ -147,7 +144,8 @@ static unsigned int acpi_platform_resource_count(struct acpi_resource *ares, voi
 struct platform_device *acpi_create_platform_device(struct acpi_device *adev,
 						    const struct property_entry *properties)
 {
-	struct acpi_device *parent = acpi_dev_parent(adev);
+	struct acpi_device *p = acpi_dev_parent(adev);
+	struct device *parent __free(put_device) = acpi_bus_get_primary_device(p);
 	struct platform_device *pdev = NULL;
 	struct platform_device_info pdevinfo;
 	const struct acpi_device_id *match;
@@ -193,7 +191,7 @@ struct platform_device *acpi_create_platform_device(struct acpi_device *adev,
 								       rentry->res,
 								       resources,
 								       count);
-				acpi_platform_fill_resource(adev, rentry->res,
+				acpi_platform_fill_resource(parent, rentry->res,
 							    &resources[count++]);
 			}
 			acpi_dev_free_resource_list(&resource_list);
@@ -206,7 +204,7 @@ struct platform_device *acpi_create_platform_device(struct acpi_device *adev,
 	 * attached to it, that physical device should be the parent of the
 	 * platform device we are about to create.
 	 */
-	pdevinfo.parent = parent ? acpi_get_first_physical_node(parent) : NULL;
+	pdevinfo.parent = parent;
 	pdevinfo.name = dev_name(&adev->dev);
 	pdevinfo.id = PLATFORM_DEVID_NONE;
 	pdevinfo.res = resources;
Signature · 1 line
2.53.0
author maintainer
#1478 lore raw

PATCH 1462/1815 ACPI: scan: Use acpi_bus_get_primary_device()

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 87ee7d704f69f303c86b2dcf617e33764371fe7b ]

The acpi_get_first_physical_node() usage in acpi_create_video_bus_device() is generally unsafe because in theory the device returned by it may be freed at any time.

Address this issues by using acpi_bus_get_primary_device() instead of acpi_get_first_physical_node() and dropping the device reference acquired by it after registering the child.

Fixes 6ab3532b4c98 ("ACPI: video: Switch over to auxiliary bus type")
---
 drivers/acpi/scan.c | 20 +++++++++-----------
 1 file changed, 9 insertions(+), 11 deletions(-)
drivers/acpi/scan.c +9 -11
index f8450f7ea097c..99af95f338652 100644
@@ -2213,29 +2213,27 @@ static void acpi_create_video_bus_device(struct acpi_device *adev,
 	struct auxiliary_device *aux_dev;
 	static unsigned int aux_dev_id;
 
+	struct device *phys_parent __free(put_device) = acpi_bus_get_primary_device(parent);
+	if (!phys_parent)
+		return;
+
 	aux_dev = kzalloc_obj(*aux_dev);
 	if (!aux_dev)
 		return;
 
 	aux_dev->id = aux_dev_id++;
 	aux_dev->name = "video_bus";
-	aux_dev->dev.parent = acpi_get_first_physical_node(parent);
-	if (!aux_dev->dev.parent)
-		goto err;
-
+	aux_dev->dev.parent = phys_parent;
 	aux_dev->dev.release = acpi_video_bus_device_release;
 
-	if (auxiliary_device_init(aux_dev))
-		goto err;
+	if (auxiliary_device_init(aux_dev)) {
+		kfree(aux_dev);
+		return;
+	}
 
 	ACPI_COMPANION_SET(&aux_dev->dev, adev);
 	if (__auxiliary_device_add(aux_dev, "acpi"))
 		auxiliary_device_uninit(aux_dev);
-
-	return;
-
-err:
-	kfree(aux_dev);
 }
 
 struct acpi_scan_system_dev {
Signature · 1 line
2.53.0
author maintainer
#1479 lore raw

PATCH 1463/1815 selftests/bpf: Fix selftest build after filter.h update

In reply to Greg Kroah-Hartman

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

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

From: Ihor Solodrai <[email protected]>

[ Upstream commit a2b83a8c8430b5a4cb43a1671c62535afcfce78d ]

Upstream commit 7a1f400ff5e5 ("tools: Ensure tools copy of linux/filter.h exports the UAPI") caused selftests/bpf build to fail [1] with:

In file included from progs/arena_atomics.c:9:
/codebuild/output/src2365462129/src/actions-runner/_work/bpf/bpf/tools/testing/selftests/bpf/../../../include/linux/filter.h:9:10: fatal error: 'uapi/linux/filter.h' file not found
9 | #include <uapi/linux/filter.h>
| ^~~~~~~~~~~~~~~~~~~~~
1 error generated.
CLNG-BPF [test_progs] bind_perm.bpf.o
make: *** [Makefile:888: /codebuild/output/src2365462129/src/actions-runner/_work/bpf/bpf/tools/testing/selftests/bpf/arena_atomics.bpf.o] Error 1
make: *** Waiting for unfinished jobs....
GEN-OBJ [libarena] libarena.bpf.o
GEN-SKEL [libarena] libarena.skel.h
make: Leaving directory '/codebuild/output/src2365462129/src/actions-runner/_work/bpf/bpf/tools/testing/selftests/bpf'
Process completed with exit code 2.

BPF selftest programs include the tools header directly, but BPF_CFLAGS only exposes tools/include/uapi. Compiler therefore cannot resolve the nested UAPI include.

Add tools/include after tools/include/uapi in BPF_CFLAGS. This preserves the existing UAPI header precedence while allowing tools headers to include uapi headers.

[1] https://github.com/kernel-patches/bpf/actions/runs/31806678733/job/94787271162

Fixes 7a1f400ff5e5 ("tools: Ensure tools copy of linux/filter.h exports the UAPI")
---
 tools/testing/selftests/bpf/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/bpf/Makefile +1 -1
index 55d394438705a..5ae24ee101007 100644
@@ -464,7 +464,7 @@ endif
 CLANG_SYS_INCLUDES = $(call get_sys_includes,$(CLANG),$(CLANG_TARGET_ARCH))
 BPF_CFLAGS = -g -Wall -Werror -D__TARGET_ARCH_$(SRCARCH) $(MENDIAN)	\
 	     -I$(INCLUDE_DIR) -I$(CURDIR) -I$(APIDIR)			\
-	     -I$(CURDIR)/libarena/include				\
+	     -I$(TOOLSINCDIR) -I$(CURDIR)/libarena/include		\
 	     -I$(abspath $(OUTPUT)/../usr/include)			\
 	     -std=gnu11		 					\
 	     -fno-strict-aliasing 					\
Signature · 1 line
2.53.0
author maintainer
#1480 lore raw

PATCH 1464/1815 bpf: Fix pending_pos walk on 32-bit ring position wrap

In reply to Greg Kroah-Hartman

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

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

From: Israel Téllez García <[email protected]>

[ Upstream commit 6ff5b56a50c5351aeeb180e34327736576c038fa ]

The reservation path caches the position of the oldest not-yet-committed record in rb->pending_pos and advances it past already committed records on every reservation:

	while (pend_pos < prod_pos) {

consumer_pos, producer_pos and pending_pos are unsigned long, i.e. 32-bit on 32-bit architectures, and Documentation/bpf/ringbuf.rst states that these counters may wrap around there. Every other comparison in the file is written as a difference, so modular arithmetic keeps them correct across the wrap. This one is an ordering comparison, and it is not wrap-safe.

Once producer_pos wraps past 2^32, prod_pos is small while pend_pos still holds its pre-wrap value, so the loop condition is false and pending_pos is never advanced again. Reservations keep succeeding for a while, because bpf_ringbuf_has_space() uses differences, but new_prod_pos - pend_pos grows as the producer advances, and once it exceeds rb->mask every subsequent __bpf_ringbuf_reserve() call fails:
the kernel believes a pending record spans the whole buffer. The ring never recovers, bpf_ringbuf_output() drops every event from then on, and nothing is logged.

Observed on four armv7 devices (i.MX7 Dual, 6.6.52) running a tracepoint-based collector with a 512 KiB ring and 160-byte records. Every one of them stopped delivering after exactly 26846821 records and 4295491360 bytes had passed through the ring, at event rates between 441 and 862 records/s, that is after 8 h to 17 h of uptime: the trigger is the byte count, not time or load. That figure is 2^32 plus 524064 bytes, and the excess is one ring's worth of grace period, as expected while new_prod_pos - pend_pos is still below rb->mask. The last reservation that fits is the largest record boundary X with X + 160 <= 524287, and since 2^32 mod 160 = 96 the boundaries after the wrap sit at X = 64 (mod 160), giving X = 524064. Userspace kept consuming normally until the producer stopped, then read zero records for good. With this patch applied, one of the four devices took 10 GiB through the same ring with no stall, while the three unpatched ones kept wedging at the same byte count.

64-bit hosts are unaffected in practice: their counters would need 16 EiB to wrap.

Compare the two positions as a difference instead. pending_pos never runs ahead of producer_pos, so the unsigned difference is the real distance between them and stays correct across the wrap.

Fixes cfa1a2329a69 ("bpf: Fix overrunning reservations in ringbuf")
---
 kernel/bpf/ringbuf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/bpf/ringbuf.c +1 -1
index 35ae64ade36b8..06d3cc192601f 100644
@@ -482,7 +482,7 @@ static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)
 	prod_pos = rb->producer_pos;
 	new_prod_pos = prod_pos + len;
 
-	while (pend_pos < prod_pos) {
+	while (prod_pos - pend_pos > 0) {
 		hdr = (void *)rb->data + (pend_pos & rb->mask);
 		hdr_len = READ_ONCE(hdr->len);
 		if (hdr_len & BPF_RINGBUF_BUSY_BIT)
Signature · 1 line
2.53.0
author maintainer
#1481 lore raw

PATCH 1465/1815 selftests/sched_ext: Fix flaky ddsp failure tests on busy systems

In reply to Greg Kroah-Hartman

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

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

From: Michal Blaszczyk <[email protected]>

[ Upstream commit e72979d3264a87a6a2dfb44fe0f5723a17d2ef84 ]

The ddsp_vtimelocal_fail and ddsp_bogus_dsq_fail tests skip calling scx_bpf_dsq_insert_vtime() if scx_bpf_pick_idle_cpu() fails to find an idle CPU (returns a negative error code). On loaded systems, this results in the tests skipping the very assertions they are meant to verify.

Eliminate this flakiness by falling back to prev_cpu if no idle CPU is found, ensuring the illegal dispatch operations are unconditionally attempted and tested.

Fixes a5db7817af78 ("sched_ext: Add selftests")
---
 .../sched_ext/ddsp_bogus_dsq_fail.bpf.c       | 20 +++++++++----------
 .../sched_ext/ddsp_vtimelocal_fail.bpf.c      | 13 ++++++------
 2 files changed, 15 insertions(+), 18 deletions(-)
tools/testing/selftests/sched_ext/ddsp_bogus_dsq_fail.bpf.c +9 -11
index 6f4c3f5a1c5d9..7ef9de7b27ebf 100644
@@ -14,18 +14,16 @@ s32 BPF_STRUCT_OPS(ddsp_bogus_dsq_fail_select_cpu, struct task_struct *p,
 		   s32 prev_cpu, u64 wake_flags)
 {
 	s32 cpu = scx_bpf_pick_idle_cpu(p->cpus_ptr, 0);
+	if (cpu < 0)
+		cpu = prev_cpu;
 
-	if (cpu >= 0) {
-		/*
-		 * If we dispatch to a bogus DSQ that will fall back to the
-		 * builtin global DSQ, we fail gracefully.
-		 */
-		scx_bpf_dsq_insert_vtime(p, 0xcafef00d, SCX_SLICE_DFL,
-				       p->scx.dsq_vtime, 0);
-		return cpu;
-	}
-
-	return prev_cpu;
+	/*
+	 * If we dispatch to a bogus DSQ that will fall back to the
+	 * builtin global DSQ, we fail gracefully.
+	 */
+	scx_bpf_dsq_insert_vtime(p, 0xcafef00d, SCX_SLICE_DFL,
+				 p->scx.dsq_vtime, 0);
+	return cpu;
 }
 
 void BPF_STRUCT_OPS(ddsp_bogus_dsq_fail_exit, struct scx_exit_info *ei)
tools/testing/selftests/sched_ext/ddsp_vtimelocal_fail.bpf.c +6 -7
index e4a55027778fd..82dca4cdc0a6c 100644
@@ -14,15 +14,14 @@ s32 BPF_STRUCT_OPS(ddsp_vtimelocal_fail_select_cpu, struct task_struct *p,
 		   s32 prev_cpu, u64 wake_flags)
 {
 	s32 cpu = scx_bpf_pick_idle_cpu(p->cpus_ptr, 0);
+	if (cpu < 0)
+		cpu = prev_cpu;
 
-	if (cpu >= 0) {
-		/* Shouldn't be allowed to vtime dispatch to a builtin DSQ. */
-		scx_bpf_dsq_insert_vtime(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL,
-					 p->scx.dsq_vtime, 0);
-		return cpu;
-	}
+	/* Shouldn't be allowed to vtime dispatch to a builtin DSQ. */
+	scx_bpf_dsq_insert_vtime(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL,
+				 p->scx.dsq_vtime, 0);
 
-	return prev_cpu;
+	return cpu;
 }
 
 void BPF_STRUCT_OPS(ddsp_vtimelocal_fail_exit, struct scx_exit_info *ei)
Signature · 1 line
2.53.0
author maintainer
#1482 lore raw

PATCH 1466/1815 crypto: hisilicon/sec2 - fix CCM algorithm long packet failure

In reply to Greg Kroah-Hartman

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

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

From: Zhushuai Yin <[email protected]>

[ Upstream commit b82f60be50c87b3d75e207852c5ca74fa18f66cf ]

In the CCM B0 block the message-length field Q spans L bytes, where L (cl in the driver) is derived from the cipher IV flags byte as c_ivin[0] + 1. set_aead_auth_iv() hardcoded writing only the last 2 bytes of a_ivin with cryptlen, implicitly assuming cl = 2.

When cl = 3 (a shorter nonce yielding a 3-byte length field) and the packet is longer than 65535 bytes, cryptlen no longer fits in 2 bytes. The dropped high byte made the auth IV built by the driver differ from the one consumed by the hardware, so the software/hardware comparison failed and the CCM request errored out.

Write the last cl bytes of a_ivin in a loop driven by the IV's CL value, so the length-field width always matches the algorithm configuration instead of assuming a fixed 2-byte field.

Fixes c16a70c1f253 ("crypto: hisilicon/sec - add new algorithm mode for AEAD")
---
 drivers/crypto/hisilicon/sec2/sec_crypto.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
drivers/crypto/hisilicon/sec2/sec_crypto.c +6 -6
index 77e0e03cbcab9..a7354fd10dc0f 100644
@@ -96,7 +96,6 @@
 #define IV_FLAGS_OFFSET	0x6
 #define IV_CM_OFFSET		0x3
 #define IV_LAST_BYTE1		1
-#define IV_LAST_BYTE2		2
 #define IV_LAST_BYTE_MASK	0xFF
 #define IV_CTR_INIT		0x1
 #define IV_BYTE_OFFSET		0x8
@@ -1696,7 +1695,7 @@ static void set_aead_auth_iv(struct sec_ctx *ctx, struct sec_req *req)
 	struct sec_cipher_req *c_req = &req->c_req;
 	u32 data_size = aead_req->cryptlen;
 	u8 flage = 0;
-	u8 cm, cl;
+	u8 cm, cl, i;
 
 	/* the specification has been checked in aead_iv_demension_check() */
 	cl = c_req->c_ivin[0] + 1;
@@ -1720,15 +1719,16 @@ static void set_aead_auth_iv(struct sec_ctx *ctx, struct sec_req *req)
 	 * the last 32bit is counter's initial number,
 	 * but the nonce uses the first 16bit
 	 * the tail 16bit fill with the cipher length
+	 * When CL is 3, the tail 24bit fill with the cipher length.
 	 */
 	if (!c_req->encrypt)
 		data_size = aead_req->cryptlen - authsize;
 
-	a_req->a_ivin[ctx->c_ctx.ivsize - IV_LAST_BYTE1] =
-			data_size & IV_LAST_BYTE_MASK;
-	data_size >>= IV_BYTE_OFFSET;
-	a_req->a_ivin[ctx->c_ctx.ivsize - IV_LAST_BYTE2] =
+	for (i = 1; i <= cl; i++) {
+		a_req->a_ivin[ctx->c_ctx.ivsize - i] =
 			data_size & IV_LAST_BYTE_MASK;
+		data_size >>= IV_BYTE_OFFSET;
+	}
 }
 
 static void sec_aead_set_iv(struct sec_ctx *ctx, struct sec_req *req)
Signature · 1 line
2.53.0
author maintainer
#1483 lore raw

PATCH 1467/1815 crypto: lskcipher - propagate errors from unaligned crypt

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

[ Upstream commit 7537036a2e6fe96f8ed82034f755c54714a0e417 ]

The while loop declares a second err variable that shadows the outer one. When the crypt callback fails, the goto out path returns the outer err, which still holds the -ENOMEM value assigned before the successful allocation check. The real error from the cipher is discarded and the caller sees -ENOMEM instead.

Drop the inner declaration so the callback error reaches the caller.

Verified with a test module that registers an lskcipher whose encrypt callback fails with -EIO and calls it through a misaligned buffer. An unpatched kernel returns -ENOMEM, a patched kernel returns -EIO.

Found with Clang's -Wshadow.

Fixes 31865c4c4db2b ("crypto: skcipher - Add lskcipher")
Assisted-by Claude:claude-fable-5
---
 crypto/lskcipher.c | 1 -
 1 file changed, 1 deletion(-)
crypto/lskcipher.c +0 -1
index e4328df6e26c0..a79c9a246e5d7 100644
@@ -95,7 +95,6 @@ static int crypto_lskcipher_crypt_unaligned(
 
 	while (len >= bs) {
 		unsigned chunk = min((unsigned)PAGE_SIZE, len);
-		int err;
 
 		if (chunk > cs)
 			chunk &= ~(cs - 1);
Signature · 1 line
2.53.0
author maintainer
#1484 lore raw

PATCH 1468/1815 sched_ext: Drop unlocked scx_rq_clock_invalidate() from scx_root_disable()

In reply to Greg Kroah-Hartman

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

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

From: Tejun Heo <[email protected]>

[ Upstream commit d44093323131a42a85184315bb9b6da4813cc39b ]

scx_root_disable() invalidates each rq's clock before taking the rq lock. scx_rq_clock_invalidate() is a plain read-modify-write of rq->scx.flags and every other writer of the word runs under the rq lock, so the unlocked update can race a concurrent flags update and lose one side's bits.

The invalidation doesn't matter in the first place. The cached clock is read only by scx_bpf_now() from a loaded scheduler's BPF programs, nothing can re-validate the clock while sched_ext is disabled as scx_rq_clock_update() is gated on scx_enabled() too, and the usual rq lock cycles under the next scheduler refresh or invalidate it before it's practically observable. Drop the invalidation instead of fixing the locking.

v2: Description and comment updated - the invalidation is unnecessary rather
than subsumed by the rq lock cycle below.

Fixes 3a9910b5904d ("sched_ext: Implement scx_bpf_now()")
Cc Changwoo Min <[email protected]>
---
 kernel/sched/ext/ext.c | 11 +++--------
 1 file changed, 3 insertions(+), 8 deletions(-)
kernel/sched/ext/ext.c +3 -8
index c6cfb162abbdc..558be0cdebef8 100644
@@ -6294,12 +6294,9 @@ static void scx_root_disable(struct scx_sched *sch)
 	percpu_up_write(&scx_fork_rwsem);
 
 	/*
-	 * Invalidate all the rq clocks to prevent getting outdated
-	 * rq clocks from a previous scx scheduler.
-	 *
-	 * Also re-balance the dl_server bandwidth reservations: detach
-	 * ext_server (no more sched_ext tasks) and reinstate fair_server if it
-	 * was previously detached because we were running in full mode.
+	 * Re-balance the dl_server bandwidth reservations: detach ext_server
+	 * (no more sched_ext tasks) and reinstate fair_server if it was
+	 * previously detached because we were running in full mode.
 	 *
 	 * Unlike the enable path, this runs on a recovery path that cannot
 	 * fail, so we use dl_server_swap_bw() to atomically free ext_server's
@@ -6312,8 +6309,6 @@ static void scx_root_disable(struct scx_sched *sch)
 	for_each_possible_cpu(cpu) {
 		struct rq *rq = cpu_rq(cpu);
 
-		scx_rq_clock_invalidate(rq);
-
 		scoped_guard(rq_lock_irqsave, rq) {
 			update_rq_clock(rq);
 			if (was_switched_all) {
Signature · 1 line
2.53.0
author maintainer
#1485 lore raw

PATCH 1469/1815 sched_ext/scx_flatcg: Fix cvtime true-up on slice expiry

In reply to Greg Kroah-Hartman

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

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

From: Tao Cui <[email protected]>

[ Upstream commit 9b4243d30469e7733730e786792d1560442e229e ]

fcg_dispatch() true-ups the current cgroup's cvtime when its slice expires or its DSQ runs empty while the slice is still active:

	__sync_fetch_and_add(&cgc->cvtime_delta,
			     (cpuc->cur_at + cgrp_slice_ns - now) *
			     FCG_HWEIGHT_ONE / (cgc->hweight ?: 1));

The true-up should be actual minus charged: on CNS_EXPIRE, the overrun (now - cur_at - cgrp_slice_ns) should be added; on CNS_EMPTY, the unused portion of the slice should be subtracted. The expression above has the sign inverted, and in the CNS_EXPIRE case now is already past cur_at + cgrp_slice_ns, so the u64 subtraction wraps. The multiplication preserves the two's complement encoding but the unsigned division by hweight destroys it, adding roughly 2^64/hweight per expiry instead of a small correction.

Under saturation the hweight budget clamp in cgrp_cap_budget() masks most of the garbage, so the weight distribution barely moves, but the accounting is broken all the same. Compute the delta as a signed value and use fetch_and_add()/fetch_and_sub() so that the dividends stay positive, as BPF division is unsigned.

Instrumented the true-up and ran a saturated three-leaf cgroup tree on a 4-CPU VM: without the fix, each expiry added ~5e15 (2^64/hweight territory) to cvtime_delta; with it, the corrections are back to slice scale, with the overrun added and the unused portion subtracted.

Fixes a4103eacc2ab ("sched_ext: Add a cgroup scheduler which uses flattened hierarchy")
---
 tools/sched_ext/scx_flatcg.bpf.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)
tools/sched_ext/scx_flatcg.bpf.c +11 -3
index 0fd214cc61dae..ddcf6bc03b11c 100644
@@ -769,10 +769,18 @@ void BPF_STRUCT_OPS(fcg_dispatch, s32 cpu, struct task_struct *prev)
 		 * cgroup to execute but the latter needs to be done in a loop
 		 * and we can't keep the lock held. Oh well...
 		 */
+		s64 delta = now - cpuc->cur_at - cgrp_slice_ns;
+
 		bpf_spin_lock(&cgv_tree_lock);
-		__sync_fetch_and_add(&cgc->cvtime_delta,
-				     (cpuc->cur_at + cgrp_slice_ns - now) *
-				     FCG_HWEIGHT_ONE / (cgc->hweight ?: 1));
+		/* keep the dividends positive, BPF division is unsigned */
+		if (delta >= 0)
+			__sync_fetch_and_add(&cgc->cvtime_delta,
+					     (u64)delta * FCG_HWEIGHT_ONE /
+					     (cgc->hweight ?: 1));
+		else
+			__sync_fetch_and_sub(&cgc->cvtime_delta,
+					     (u64)-delta * FCG_HWEIGHT_ONE /
+					     (cgc->hweight ?: 1));
 		bpf_spin_unlock(&cgv_tree_lock);
 	} else {
 		stat_inc(FCG_STAT_CNS_GONE);
Signature · 1 line
2.53.0
author maintainer
#1486 lore raw

PATCH 1470/1815 sched_ext: Make SCHED_CLASS_EXT select GENERIC_ALLOCATOR

In reply to Greg Kroah-Hartman

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

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

From: Tejun Heo <[email protected]>

[ Upstream commit 524ab50763af33d65e6e042cf7034cd8f82d437b ]

kernel/sched/ext/arena.c uses the gen_pool allocator, which is built only when GENERIC_ALLOCATOR is set. SCHED_CLASS_EXT doesn't select it, so on configs where nothing else does, the build fails to link:

build_policy.o: undefined reference to gen_pool_create' build_policy.o: undefined reference to gen_pool_for_each_chunk' build_policy.o: undefined reference to `gen_pool_destroy'

---
 kernel/Kconfig.preempt | 1 +
 1 file changed, 1 insertion(+)
kernel/Kconfig.preempt +1 -0
index 88c594c6d7fcd..f95859e4e3f09 100644
@@ -169,6 +169,7 @@ config SCHED_CORE
 config SCHED_CLASS_EXT
 	bool "Extensible Scheduling Class"
 	depends on BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+	select GENERIC_ALLOCATOR
 	select STACKTRACE if STACKTRACE_SUPPORT
 	help
 	  This option enables a new scheduler class sched_ext (SCX), which
Signature · 1 line
2.53.0
author maintainer
#1487 lore raw

PATCH 1471/1815 perf dso: Guard against errno==0 when dso__get_filename() returns NULL

In reply to Greg Kroah-Hartman

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

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

From: Arnaldo Carvalho de Melo <[email protected]>

[ Upstream commit 51a7a9ddcb3ebc86615886b1f44e85bdea9df326 ]

__open_dso() computes fd = -errno when dso__get_filename() returns NULL. Some failure paths in dso__get_filename() (e.g. binary type mismatch) return NULL without making a syscall, leaving errno at 0 from a prior successful call. fd = -0 = 0, which is stdin — subsequent code treats it as a valid file descriptor.

Fall back to ENOENT when errno is 0, ensuring fd is always negative on failure.

The forced ENOENT stays in errno for the callers that check it after a negative fd. It must not misdirect the try_to_open_dso() fallback loop, though: dso__get_filename()'s chroot fallback used to accept a stale ENOENT even when stat() succeeded on a non-regular file (e.g. a directory). Re-stat() there and only take the chroot path when stat() actually failed with ENOENT [sashiko-bot review of PATCH 1/5].

Fixes eba5102d2f0b ("perf tools: Add global list of opened dso objects")
Assisted-by Claude:claude-opus-4.6
---
 tools/perf/util/dso.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
tools/perf/util/dso.c +15 -3
index 2309196d8df31..b86969dc6e81e 100644
@@ -582,9 +582,18 @@ static char *dso__get_filename(struct dso *dso, const char *root_dir,
 		goto out;
 
 	if (!is_regular_file(name)) {
+		struct stat st;
 		char *new_name;
 
-		if (errno != ENOENT || dso__nsinfo(dso) == NULL)
+		/*
+		 * errno only reflects the failure reason when stat() itself
+		 * failed: a successful stat() on a non-regular file (e.g. a
+		 * directory) leaves a stale errno, which a previous failed
+		 * iteration of the try_to_open_dso() fallback loop may have
+		 * set to ENOENT.
+		 */
+		if (stat(name, &st) == 0 || errno != ENOENT ||
+		    dso__nsinfo(dso) == NULL)
 			goto out;
 
 		new_name = dso__filename_with_chroot(dso, name);
@@ -640,10 +649,13 @@ static int __open_dso(struct dso *dso, struct machine *machine)
 	mutex_lock(dso__lock(dso));
 
 	name = dso__get_filename(dso, machine ? machine->root_dir : "", &decomp);
-	if (name)
+	if (name) {
 		fd = do_open(name);
-	else
+	} else {
+		if (errno == 0)
+			errno = ENOENT;
 		fd = -errno;
+	}
 
 	if (decomp)
 		unlink(name);
Signature · 1 line
2.53.0
author maintainer
#1488 lore raw

PATCH 1472/1815 perf dso: Guard close() against invalid fd in dso__decompress_kmodule_path()

In reply to Greg Kroah-Hartman

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

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

From: Arnaldo Carvalho de Melo <[email protected]>

[ Upstream commit 10f452dc2de401be76ae8e7395c9663313df8b53 ]

dso__decompress_kmodule_path() unconditionally calls close(fd) on the return value of decompress_kmodule(). When decompression fails or the DSO is not compressed, decompress_kmodule() returns -1. close(-1) fails with EBADF and clobbers errno, which callers up the chain (dso__get_filename → __open_dso) depend on for error propagation.

Guard the close() call with fd >= 0 so only valid file descriptors are closed.

Fixes 42b3fa670825 ("perf tools: Introduce dso__decompress_kmodule_{fd,path}")
Assisted-by Claude:claude-opus-4.6
---
 tools/perf/util/dso.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
tools/perf/util/dso.c +3 -1
index b86969dc6e81e..41bbc8f994e41 100644
@@ -395,7 +395,9 @@ int dso__decompress_kmodule_path(struct dso *dso, const char *name,
 {
 	int fd = decompress_kmodule(dso, name, pathname, len);
 
-	close(fd);
+	/* decompress_kmodule() returns -1 on failure, don't close(-1) */
+	if (fd >= 0)
+		close(fd);
 	return fd >= 0 ? 0 : -1;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1489 lore raw

PATCH 1473/1815 perf dso: Use stored fd error instead of stale errno in file_read() and file_size()

In reply to Greg Kroah-Hartman

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

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

From: Arnaldo Carvalho de Melo <[email protected]>

[ Upstream commit 075d2c32353ded0fe5f3b62f4aa4e98dccb3fb29 ]

file_read() and file_size() use ret = -errno when dso__data(dso)->fd is negative after try_to_open_dso() fails. By this point errno has been through mutex_lock(), nsinfo__mountns_enter(), and multiple open() attempts inside try_to_open_dso() — it no longer reflects the actual open failure. If errno happens to be 0, ret = 0 looks like EOF rather than an error, and file_size() callers like dso__data_size() would then report a zero-sized file instead of failing.

dso__data(dso)->fd is always negative on failure — -errno from __open_dso() when no filename could be built (e.g. -EINVAL, -ENOENT), or -1 when do_open() itself failed — and never 0, so use it directly instead of reading the stale global errno.

No assert() or comment is needed after the assignment: the enclosing if (dso__data(dso)->fd < 0) already guarantees ret < 0 [Namhyung Kim review].

Fixes 33bdedcea2d7 ("perf tools: Protect dso cache fd with a mutex")
Assisted-by Claude:claude-opus-4.6
---
 tools/perf/util/dso.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
tools/perf/util/dso.c +2 -2
index 41bbc8f994e41..60aa77f797851 100644
@@ -1038,7 +1038,7 @@ static ssize_t file_read(struct dso *dso, struct machine *machine,
 
 	if (dso__data(dso)->fd < 0) {
 		dso__data(dso)->status = DSO_DATA_STATUS_ERROR;
-		ret = -errno;
+		ret = dso__data(dso)->fd;
 		goto out;
 	}
 
@@ -1160,8 +1160,8 @@ static int file_size(struct dso *dso, struct machine *machine)
 	try_to_open_dso(dso, machine);
 
 	if (dso__data(dso)->fd < 0) {
-		ret = -errno;
 		dso__data(dso)->status = DSO_DATA_STATUS_ERROR;
+		ret = dso__data(dso)->fd;
 		goto out;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#1490 lore raw

PATCH 1474/1815 perf dso: Guard against cache underflow on short reads in dso_cache__memcpy()

In reply to Greg Kroah-Hartman

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

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

From: Arnaldo Carvalho de Melo <[email protected]>

[ Upstream commit 390a9461cd73bdd13acc0f6d763618ae1ff8fa17 ]

dso_cache__memcpy() computes cache_offset = offset - cache->offset, then cache_size = min(cache->size - cache_offset, size). The RB tree lookup in __dso_cache__find() matches using the full DSO__DATA_CACHE_SIZE window, but cache->size reflects the actual pread return value from dso_cache__populate().

A short pread (e.g. near end-of-file) makes cache->size smaller than DSO__DATA_CACHE_SIZE. If a subsequent access targets an offset past cache->offset + cache->size but within the DSO__DATA_CACHE_SIZE window, the cache entry is found but cache_offset exceeds cache->size. Since both are u64, the subtraction cache->size - cache_offset wraps to a large value, min() selects the caller's size, and memcpy reads out of bounds.

Return 0 for an offset past the valid cached data. For a regular file a short pread only happens at end-of-file, so 0 is what a direct pread() at that offset would return: cached_io() stops its read loop as on EOF. Re-reading from the backing file would not help — a second pread at the same offset returns the same short count.

Fixes 366df72657e0 ("perf dso: Refactor dso_cache__read()")
Assisted-by Claude:claude-opus-4.6
---
 tools/perf/util/dso.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
tools/perf/util/dso.c +14 -1
index 60aa77f797851..4dd64069c4348 100644
@@ -1014,7 +1014,20 @@ static ssize_t dso_cache__memcpy(struct dso_cache *cache, u64 offset, u8 *data,
 				 u64 size, bool out)
 {
 	u64 cache_offset = offset - cache->offset;
-	u64 cache_size   = min(cache->size - cache_offset, size);
+	u64 cache_size;
+
+	/*
+	 * The RB tree matches using DSO__DATA_CACHE_SIZE, but a short
+	 * pread may leave cache->size smaller.  For a regular file a
+	 * short pread only happens at end-of-file, so an offset past
+	 * the valid data is EOF: return 0, matching what a direct
+	 * pread() at that offset would return, and cached_io() then
+	 * stops its read loop.
+	 */
+	if (cache_offset >= cache->size)
+		return 0;
+
+	cache_size = min(cache->size - cache_offset, size);
 
 	if (out)
 		memcpy(data, cache->data + cache_offset, cache_size);
Signature · 1 line
2.53.0
author maintainer
#1491 lore raw

PATCH 1475/1815 perf dso: Replace assert with runtime check in dso__read_symbol()

In reply to Greg Kroah-Hartman

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

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

From: Arnaldo Carvalho de Melo <[email protected]>

[ Upstream commit 62972e5644e48255dcc715e6ec4401882f8b37d1 ]

dso__read_symbol() asserts that len <= jited_prog_len, where len comes from sym->end - sym->start (parsed from PERF_RECORD_KSYMBOL in perf.data). Both values originate from untrusted file input.

With NDEBUG (production builds), the assert is compiled out, allowing an out-of-bounds heap read when the BPF program buffer is accessed. Without NDEBUG, a crafted perf.data crashes perf with an assertion failure.

Replace the assert with a runtime bounds check that returns NULL with an appropriate error code, matching the existing error handling pattern in this function.

Fixes aa04707f507e ("perf dso: Support BPF programs in dso__read_symbol()")
Cc Song Liu <[email protected]>
Assisted-by Claude:claude-opus-4.6
---
 tools/perf/util/dso.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
tools/perf/util/dso.c +6 -1
index 4dd64069c4348..42bfe30a3b518 100644
@@ -2038,7 +2038,12 @@ const u8 *dso__read_symbol(struct dso *dso, const char *symfs_filename,
 			errno = SYMBOL_ANNOTATE_ERRNO__BPF_MISSING_BTF;
 			return NULL;
 		}
-		assert(len <= info_linear->info.jited_prog_len);
+		if (len > info_linear->info.jited_prog_len) {
+			pr_debug("BPF symbol length %zu exceeds jited_prog_len %u\n",
+				 len, info_linear->info.jited_prog_len);
+			errno = SYMBOL_ANNOTATE_ERRNO__BPF_MISSING_BTF;
+			return NULL;
+		}
 		*out_buf_len = len;
 		return (const u8 *)(uintptr_t)(info_linear->info.jited_prog_insns);
 #else
Signature · 1 line
2.53.0
author maintainer
#1492 lore raw

PATCH 1476/1815 mailbox: qcom-cpucp: fix PREEMPT_RT self-deadlock in IRQ handler

In reply to Greg Kroah-Hartman

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

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

From: Jia Yang <[email protected]>

[ Upstream commit 3690aaa6d18f6775c3e7932fb8af8c5bf6a6b69c ]

qcom_cpucp_mbox_irq_fn() calls mbox_chan_received_data() while holding chan->lock. Under PREEMPT_RT, spin_lock_irqsave() is converted to an rt_spinlock (rtmutex-based), which tracks ownership and can sleep.

The callback chain triggered by mbox_chan_received_data() eventually reaches mailbox_clear_channel() -> mbox_send_message() -> add_to_rbuf(), which attempts to re-acquire the same chan->lock. Since rtmutex detects the re-entrant lock attempt by the same owner, the thread blocks waiting for a lock it already holds, causing a permanent deadlock.

This deadlock manifests as 'irq/N-apss_cpucp_mbox' stuck in D state with the following call trace:
rt_spin_lock -> mbox_send_message -> mailbox_clear_channel -> scmi_rx_callback -> mbox_chan_received_data [<- held chan->lock here]

Fix by saving chan->cl locally and clearing the HW interrupt register inside the lock, then invoking mbox_chan_received_data() after releasing the lock. This preserves the mutual exclusion for chan->cl access while avoiding the lock re-entrancy that causes the PREEMPT_RT deadlock.

Fixes 0e2a9a03106c ("mailbox: Add support for QTI CPUCP mailbox controller")
---
 drivers/mailbox/qcom-cpucp-mbox.c | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)
drivers/mailbox/qcom-cpucp-mbox.c +14 -3
index 862e45e8fbd58..0f7fe189e8b1f 100644
@@ -63,14 +63,25 @@ static irqreturn_t qcom_cpucp_mbox_irq_fn(int irq, void *data)
 	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);
 		struct mbox_chan *chan = &cpucp->chans[i];
+		struct mbox_client *cl;
 		unsigned long flags;
 
-		/* Provide mutual exclusion with changes to chan->cl */
+		/*
+		 * Provide mutual exclusion with changes to chan->cl.
+		 * Save cl locally and clear the HW interrupt inside the lock,
+		 * then invoke mbox_chan_received_data() outside the lock to
+		 * avoid a PREEMPT_RT self-deadlock: mbox_chan_received_data()
+		 * can call back into mbox_send_message() via scmi_rx_callback()
+		 * -> mailbox_clear_channel(), which re-acquires chan->lock
+		 * (converted to an rt_spinlock under PREEMPT_RT).
+		 */
 		spin_lock_irqsave(&chan->lock, flags);
-		if (chan->cl)
-			mbox_chan_received_data(chan, &val);
+		cl = chan->cl;
 		writeq(BIT(i), cpucp->rx_base + APSS_CPUCP_RX_MBOX_CLEAR);
 		spin_unlock_irqrestore(&chan->lock, flags);
+
+		if (cl)
+			mbox_chan_received_data(chan, &val);
 	}
 
 	return IRQ_HANDLED;
Signature · 1 line
2.53.0
author maintainer
#1493 lore raw

PATCH 1477/1815 mailbox: qcom-cpucp: handle NULL data in send_data callback

In reply to Greg Kroah-Hartman

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

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

From: Jia Yang <[email protected]>

[ Upstream commit fc4f2f99530298a1739226947aa76525142d421d ]

mailbox_clear_channel() calls mbox_send_message() with NULL data to notify the remote side that the RX channel has been cleared. qcom_cpucp_mbox_send_data() blindly dereferenced the data pointer, causing a NULL pointer dereference kernel panic when invoked from this path under PREEMPT_RT.

Add an explicit NULL check and return early without writing to the TX register, which is the correct behaviour for a channel-clear notification.

Fixes 0e2a9a03106c ("mailbox: Add support for QTI CPUCP mailbox controller")
---
 drivers/mailbox/qcom-cpucp-mbox.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/mailbox/qcom-cpucp-mbox.c +8 -0
index 0f7fe189e8b1f..298b357c0f9a6 100644
@@ -117,6 +117,14 @@ static int qcom_cpucp_mbox_send_data(struct mbox_chan *chan, void *data)
 	unsigned long chan_id = channel_number(chan);
 	u32 *val = data;
 
+	/*
+	 * mailbox_clear_channel() calls mbox_send_message() with NULL data to
+	 * signal the remote side that the channel has been cleared.  Nothing
+	 * needs to be written to the TX register in that case, so just return.
+	 */
+	if (!val)
+		return 0;
+
 	writel(*val, cpucp->tx_base + APSS_CPUCP_TX_MBOX_CMD(chan_id) + APSS_CPUCP_MBOX_CMD_OFF);
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#1494 lore raw

PATCH 1478/1815 mailbox: rockchip: disable pclk on probe failure and unbind

In reply to Greg Kroah-Hartman

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

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

From: Linmao Li <[email protected]>

[ Upstream commit ded48fcbdc1e3ed1dc8e1974b7fe9639fcea6dd6 ]

rockchip_mbox_probe() enables the peripheral clock and then keeps going. None of the later failure paths - platform_get_irq(), devm_request_threaded_irq() and devm_mbox_controller_register() - disables it again. The driver has no remove callback either, so the clock also stays prepared and enabled once the device is unbound, and its enable count keeps growing over bind/unbind cycles.

Use devm_clk_get_enabled() to tie disabling and unpreparing the clock to the device lifetime. It is registered before the interrupts and the mailbox controller, so devres releases it after both are gone.

While rewriting the error path, switch it to dev_err_probe() so that a deferred probe is not reported as an error.

Fixes f70ed3b5dc8b ("mailbox: rockchip: Add Rockchip mailbox driver")
---
 drivers/mailbox/rockchip-mailbox.c | 17 ++++-------------
 1 file changed, 4 insertions(+), 13 deletions(-)
drivers/mailbox/rockchip-mailbox.c +4 -13
index a1a7dee643567..d55cbf7f2cb6d 100644
@@ -196,19 +196,10 @@ static int rockchip_mbox_probe(struct platform_device *pdev)
 	/* Each channel has two buffers for A2B and B2A */
 	mb->buf_size = (size_t)resource_size(res) / (drv_data->num_chans * 2);
 
-	mb->pclk = devm_clk_get(&pdev->dev, "pclk_mailbox");
-	if (IS_ERR(mb->pclk)) {
-		ret = PTR_ERR(mb->pclk);
-		dev_err(&pdev->dev, "failed to get pclk_mailbox clock: %d\n",
-			ret);
-		return ret;
-	}
-
-	ret = clk_prepare_enable(mb->pclk);
-	if (ret) {
-		dev_err(&pdev->dev, "failed to enable pclk: %d\n", ret);
-		return ret;
-	}
+	mb->pclk = devm_clk_get_enabled(&pdev->dev, "pclk_mailbox");
+	if (IS_ERR(mb->pclk))
+		return dev_err_probe(&pdev->dev, PTR_ERR(mb->pclk),
+				     "failed to get and enable pclk_mailbox clock\n");
 
 	for (i = 0; i < mb->mbox.num_chans; i++) {
 		irq = platform_get_irq(pdev, i);
Signature · 1 line
2.53.0
author maintainer
#1495 lore raw

PATCH 1479/1815 mailbox: pcc: Fix command timeout due to missed interrupt

In reply to Greg Kroah-Hartman

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

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

From: Huisong Li <[email protected]>

[ Upstream commit 3360b088175dc5d5c9166685836158470d00571e ]

PCC command execution can time out when a fast platform completes a transaction and signals the platform interrupt before pcc_send_data() marks the channel as in use. For shared platform interrupts, the type 3 handler uses chan_in_use to decide whether the interrupt belongs to the channel. If it observes false, it ignores the completion and the caller waits until timeout.

Publish chan_in_use before ringing the doorbell. Use WRITE_ONCE() for the lockless flag updates and READ_ONCE() in the interrupt handler. The following ordered I/O accessor orders the flag store before the platform is notified.

Clear chan_in_use if ringing the doorbell fails. Otherwise, leave it set until the interrupt handler completes the transaction, clearing it before the mailbox core can submit another transfer.

Fixes 3db174e478cb ("mailbox: pcc: Support shared interrupt for multiple subspaces")
---
 drivers/mailbox/pcc.c | 41 +++++++++++++++++++++++++++--------------
 1 file changed, 27 insertions(+), 14 deletions(-)
drivers/mailbox/pcc.c +27 -14
index 636879ae1db76..7a8e749374b5c 100644
@@ -91,12 +91,11 @@ struct pcc_chan_reg {
  * @plat_irq: platform interrupt
  * @type: PCC subspace type
  * @plat_irq_flags: platform interrupt flags
- * @chan_in_use: this flag is used just to check if the interrupt needs
- *		handling when it is shared. Since only one transfer can occur
- *		at a time and mailbox takes care of locking, this flag can be
- *		accessed without a lock. Note: the type only support the
- *		communication from OSPM to Platform, like type3, use it, and
- *		other types completely ignore it.
+ * @chan_in_use: lockless flag used by type 3 initiator subspaces to filter
+ *		platform interrupts. Only one transfer can occur at a time, but
+ *		the interrupt handler may sample the flag on another CPU, so all
+ *		accesses must use READ_ONCE() or WRITE_ONCE(). Other subspace
+ *		types do not test it.
  */
 struct pcc_chan_info {
 	struct pcc_mbox_chan chan;
@@ -320,8 +319,13 @@ static irqreturn_t pcc_mbox_irq(int irq, void *p)
 	if (pcc_chan_reg_read_modify_write(&pchan->plat_irq_ack))
 		return IRQ_NONE;
 
+	/*
+	 * Initiator subspaces use this flag to filter shared interrupts. Use
+	 * READ_ONCE() to sample the lockless flag written by pcc_send_data()
+	 * on another CPU.
+	 */
 	if (pchan->type == ACPI_PCCT_TYPE_EXT_PCC_MASTER_SUBSPACE &&
-	    !pchan->chan_in_use)
+	    !READ_ONCE(pchan->chan_in_use))
 		return IRQ_NONE;
 
 	if (!pcc_mbox_cmd_complete_check(pchan))
@@ -331,12 +335,12 @@ static irqreturn_t pcc_mbox_irq(int irq, void *p)
 		return IRQ_NONE;
 
 	/*
-	 * Clear this flag after updating interrupt ack register and just
-	 * before mbox_chan_received_data() which might call pcc_send_data()
-	 * where the flag is set again to start new transfer. This is
-	 * required to avoid any possible race in updatation of this flag.
+	 * Clear this flag after updating the interrupt ack register and before
+	 * notifying the client and mailbox core. mbox_chan_txdone() may submit
+	 * the next queued transfer and set the flag again. Use WRITE_ONCE() for
+	 * the lockless update observed by the send and interrupt paths.
 	 */
-	pchan->chan_in_use = false;
+	WRITE_ONCE(pchan->chan_in_use, false);
 	mbox_chan_received_data(chan, NULL);
 	mbox_chan_txdone(chan, 0);
 
@@ -438,9 +442,18 @@ static int pcc_send_data(struct mbox_chan *chan, void *data)
 	if (ret)
 		return ret;
 
+	/*
+	 * Set chan_in_use before ringing the doorbell so a fast completion
+	 * interrupt is not mistaken for a shared interrupt from another
+	 * subspace. Use WRITE_ONCE() for the lockless flag update. The
+	 * ordered I/O accessor used to ring the doorbell orders this store
+	 * before the platform is notified.
+	 */
+	if (pchan->plat_irq > 0)
+		WRITE_ONCE(pchan->chan_in_use, true);
 	ret = pcc_chan_reg_read_modify_write(&pchan->db);
-	if (!ret && pchan->plat_irq > 0)
-		pchan->chan_in_use = true;
+	if (ret && pchan->plat_irq > 0)
+		WRITE_ONCE(pchan->chan_in_use, false);
 
 	return ret;
 }
Signature · 1 line
2.53.0
author maintainer
#1496 lore raw

PATCH 1480/1815 mailbox: riscv-sbi-mpxy: validate RPMI notification lengths

In reply to Greg Kroah-Hartman

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

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

From: Pengpeng Hou <[email protected]>

[ Upstream commit 11d5af151bcbe78f5a579e0faecd3be9cea0399a ]

The SBI return value controls how many bytes are copied from shared memory into the RPMI notification buffer. It is not validated against the negotiated shared-memory size before that copy. The event walker also uses a reversed loop condition and can inspect a short event record.

Validate the complete notification length before copying it, iterate only while a full event header remains, and stop when a declared event payload extends beyond the copied notification data.

Fixes bf3022a4eb11 ("mailbox: Add RISC-V SBI message proxy (MPXY) based mailbox driver")
Assisted-by Codex:gpt-5
---
 drivers/mailbox/riscv-sbi-mpxy-mbox.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/mailbox/riscv-sbi-mpxy-mbox.c +10 -2
index 7c9c006b7244a..714f7fb97a2fd 100644
@@ -314,8 +314,13 @@ static int mpxy_get_notifications(u32 channel_id,
 			 channel_id, 0, 0, 0, 0, 0);
 	if (sret.error)
 		goto err_put_cpu;
+	if (sret.value < 0 || mpxy_shmem_size < sizeof(*notif_data) ||
+	    sret.value > mpxy_shmem_size - sizeof(*notif_data)) {
+		put_cpu();
+		return -EOVERFLOW;
+	}
 
-	memcpy(notif_data, mpxy->shmem, sret.value + 16);
+	memcpy(notif_data, mpxy->shmem, sret.value + sizeof(*notif_data));
 	*events_data_len = sret.value;
 
 err_put_cpu:
@@ -480,11 +485,14 @@ static void mpxy_mbox_peek_rpmi_data(struct mbox_chan *chan,
 	struct rpmi_mbox_message msg;
 	unsigned long pos = 0;
 
-	while (pos < events_data_len && (events_data_len - pos) <= sizeof(*event)) {
+	while (events_data_len - pos >= sizeof(*event)) {
 		event = (struct rpmi_notification_event *)(notif->events_data + pos);
 
 		msg.type = RPMI_MBOX_MSG_TYPE_NOTIFICATION_EVENT;
 		msg.notif.event_datalen = le16_to_cpu(event->event_datalen);
+		if (msg.notif.event_datalen >
+		    events_data_len - pos - sizeof(*event))
+			break;
 		msg.notif.event_id = event->event_id;
 		msg.notif.event_data = event->event_data;
 		msg.error = 0;
Signature · 1 line
2.53.0
author maintainer
#1497 lore raw

PATCH 1481/1815 null_blk: use DEFINE_MUTEX for the file-scope mutex

In reply to Greg Kroah-Hartman

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

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

From: Zizhi Wo <[email protected]>

[ Upstream commit 017dac7670909eaea3eb36e6b3b5a8be9ce0a14d ]

In null_init(), mutex_init(&lock) currently happens after configfs_register_subsystem(), which exposes the nullb subsystem to userspace. A racing mkdir() into /sys/kernel/config/nullb/ can reach null_find_dev_by_name() -> mutex_lock(&lock) before the mutex is initialized, trigger warning:

[  123.137788] DEBUG_LOCKS_WARN_ON(lock->magic != lock)
[  123.137796] WARNING: kernel/locking/mutex.c:159 at mutex_lock+0x171/0x1c0, CPU#13: mkdir/1301
[  123.140090] Modules linked in: null_blk(+) nft_fib_inet nft_fib_ipv4
......
[  123.154926] Call Trace:
[  123.155172]  <TASK>
[  123.155419]  ? __pfx_mutex_lock+0x10/0x10
[  123.156181]  ? __pfx__raw_spin_lock+0x10/0x10
[  123.156571]  nullb_group_make_group+0x20/0x100 [null_blk]
[  123.157011]  configfs_mkdir+0x47b/0xc70
[  123.157337]  ? __pfx_configfs_mkdir+0x10/0x10
[  123.157719]  ? may_create_dentry+0x242/0x2e0
[  123.158061]  vfs_mkdir+0x2a9/0x6c0
[  123.158352]  filename_mkdirat+0x3dc/0x500
[  123.158710]  ? __pfx_filename_mkdirat+0x10/0x10
[  123.159070]  ? strncpy_from_user+0x3a/0x1d0
[  123.159413]  __x64_sys_mkdir+0x6b/0x90
[  123.159760]  do_syscall_64+0xea/0x600

Replace the runtime mutex_init(&lock) with a static DEFINE_MUTEX(lock) declaration to fix this issue.

---
 drivers/block/null_blk/main.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/block/null_blk/main.c +1 -3
index f8c0fd57e041a..eba204b277854 100644
@@ -66,7 +66,7 @@ struct nullb_page {
 #define NULLB_PAGE_FREE (MAP_SZ - 2)
 
 static LIST_HEAD(nullb_list);
-static struct mutex lock;
+static DEFINE_MUTEX(lock);
 static int null_major;
 static DEFINE_IDA(nullb_indexes);
 static struct blk_mq_tag_set tag_set;
@@ -2166,8 +2166,6 @@ static int __init null_init(void)
 	if (ret)
 		return ret;
 
-	mutex_init(&lock);
-
 	null_major = register_blkdev(0, "nullb");
 	if (null_major < 0) {
 		ret = null_major;
Signature · 1 line
2.53.0
author maintainer
#1498 lore raw

PATCH 1482/1815 null_blk: register configfs subsystem after creating default devices

In reply to Greg Kroah-Hartman

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

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

From: Zizhi Wo <[email protected]>

[ Upstream commit c9d293d6bb0575fcb1f3408129453187e2a28a4e ]

In null_init(), configfs_register_subsystem() currently runs before register_blkdev(), so when null_blk is built as a module, a racing mkdir()
+ poweron from userspace can reach null_add_dev() while null_major is still
0. __add_disk() then hits WARN_ON(disk->minors) (major=0 with minors!=0) and fails:

[root@fedora ~]# [ 2366.521436] WARNING: block/genhd.c:476 at __add_disk+0x8a7/0xde0,

[ 2366.523552] Modules linked in: null_blk(+) nft_fib_inet nft_fib_ipv4 nft_fib_ipv6 nft_fib
[ 2366.529081] CPU: 26 UID: 0 PID: 1600 Comm: sh Not tainted 7.2.0-rc1+ #66 PREEMPT(full)
......
[ 2366.547251] Call Trace:
[ 2366.547575]  <TASK>
[ 2366.547831]  ? _raw_spin_lock+0x84/0xe0
[ 2366.548260]  add_disk_fwnode+0x114/0x560
[ 2366.548739]  null_add_dev+0x102d/0x1b80 [null_blk]
[ 2366.549310]  ? __pfx_null_add_dev+0x10/0x10 [null_blk]
[ 2366.549906]  ? mutex_lock+0xde/0x1c0
[ 2366.550361]  ? __pfx_mutex_lock+0x10/0x10
[ 2366.550827]  nullb_device_power_store+0x1e7/0x280 [null_blk]
[ 2366.551499]  ? __pfx_nullb_device_power_store+0x10/0x10 [null_blk]
[ 2366.552177]  ? __kmalloc_cache_noprof+0x1f5/0x470
[ 2366.552748]  ? configfs_write_iter+0x35c/0x4e0
[ 2366.553242]  configfs_write_iter+0x286/0x4e0
[ 2366.553787]  vfs_write+0x52d/0xd00
[ 2366.554169]  ? __pfx_vfs_write+0x10/0x10
[ 2366.554679]  ? __pfx___css_rstat_updated+0x10/0x10
[ 2366.555196]  ? fdget_pos+0x1cf/0x4c0
[ 2366.555649]  ksys_write+0xfc/0x1d0

......

Additionally, the err_dev path destroys all devices on nullb_list while configfs is still registered. If a racing mkdir() + poweron puts a user device on the list, null_destroy_dev()->null_free_dev() kfrees the user device's nullb_device but /sys/kernel/config/nullb/<name> is still reachable. Any userspace access to the item will trigger a UAF.

For simplicity, move configfs_register_subsystem() to the end to solve the problems above.

---
 drivers/block/null_blk/main.c | 16 ++++++----------
 1 file changed, 6 insertions(+), 10 deletions(-)
drivers/block/null_blk/main.c +6 -10
index eba204b277854..4613035222cd5 100644
@@ -2162,15 +2162,9 @@ static int __init null_init(void)
 	config_group_init(&nullb_subsys.su_group);
 	mutex_init(&nullb_subsys.su_mutex);
 
-	ret = configfs_register_subsystem(&nullb_subsys);
-	if (ret)
-		return ret;
-
 	null_major = register_blkdev(0, "nullb");
-	if (null_major < 0) {
-		ret = null_major;
-		goto err_conf;
-	}
+	if (null_major < 0)
+		return null_major;
 
 	for (i = 0; i < nr_devices; i++) {
 		ret = null_create_dev();
@@ -2178,6 +2172,10 @@ static int __init null_init(void)
 			goto err_dev;
 	}
 
+	ret = configfs_register_subsystem(&nullb_subsys);
+	if (ret)
+		goto err_dev;
+
 	pr_info("module loaded\n");
 	return 0;
 
@@ -2187,8 +2185,6 @@ static int __init null_init(void)
 		null_destroy_dev(nullb);
 	}
 	unregister_blkdev(null_major, "nullb");
-err_conf:
-	configfs_unregister_subsystem(&nullb_subsys);
 	return ret;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1499 lore raw

PATCH 1483/1815 null_blk: free global tag_set on init error path

In reply to Greg Kroah-Hartman

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

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

From: Zizhi Wo <[email protected]>

[ Upstream commit 5a1c5ff3a49ba93a1fd0b70537e7a0164071760d ]

If shared_tags is enabled, null_setup_tagset() allocates the global tag_set via null_init_global_tag_set(). If device creation later fails, err_dev destroys the default devices and calls unregister_blkdev(), but never frees the global tag_set. Since module init failed, null_exit() is never invoked, so the global tag_set's tags and maps are permanently leaked.

Free the global tag_set in err_dev, matching null_exit() which does if (tag_set.ops) blk_mq_free_tag_set(&tag_set).

---
 drivers/block/null_blk/main.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/block/null_blk/main.c +2 -0
index 4613035222cd5..fda1ffd2a64ec 100644
@@ -2185,6 +2185,8 @@ static int __init null_init(void)
 		null_destroy_dev(nullb);
 	}
 	unregister_blkdev(null_major, "nullb");
+	if (tag_set.ops)
+		blk_mq_free_tag_set(&tag_set);
 	return ret;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1500 lore raw

PATCH 1484/1815 null_blk: free zones array on device power-off

In reply to Greg Kroah-Hartman

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

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

From: Zizhi Wo <[email protected]>

[ Upstream commit 2a6357a9b935a34f5508618fee8a7fffbf7722a8 ]

null_init_zoned_dev() allocates dev->zones when a zoned device is powered on, but null_del_dev() never frees it on power-off; dev->zones is only freed later in null_free_dev(), when the configfs directory is removed. If the device is powered off and then on again, null_init_zoned_dev() allocates a new array and overwrites the dev->zones pointer, leaking the previous allocation each power cycle.

Free dev->zones in null_del_dev() via null_free_zoned_dev() to solve it. And calling null_free_zoned_dev() in null_free_dev() is no longer necessary because every caller already invokes null_del_dev() first: via nullb_group_drop_item() before nullb_device_release(), in the null_add_dev() error path of null_create_dev(), and in null_destroy_dev(). Remove the redundant call.

And take &lock around zone_cond_store() in the two store wrappers to serialize dev->zones check-and-deref against its alloc/free, which already run under &lock. The reason there was no problem before is that only nullb_device_release() or null_exit() frees the dev->zones, which guarantees that subsequent users won't access the configfs interface.

Fixes ca4b2a011948 ("null_blk: add zone support")
Assisted-by Claude-Code:GLM-5.2
---
 drivers/block/null_blk/main.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
drivers/block/null_blk/main.c +13 -3
index fda1ffd2a64ec..78bc0206c43fe 100644
@@ -579,8 +579,13 @@ static ssize_t nullb_device_zone_readonly_store(struct config_item *item,
 						const char *page, size_t count)
 {
 	struct nullb_device *dev = to_nullb_device(item);
+	ssize_t ret;
+
+	mutex_lock(&lock);
+	ret = zone_cond_store(dev, page, count, BLK_ZONE_COND_READONLY);
+	mutex_unlock(&lock);
 
-	return zone_cond_store(dev, page, count, BLK_ZONE_COND_READONLY);
+	return ret;
 }
 CONFIGFS_ATTR_WO(nullb_device_, zone_readonly);
 
@@ -588,8 +593,13 @@ static ssize_t nullb_device_zone_offline_store(struct config_item *item,
 					       const char *page, size_t count)
 {
 	struct nullb_device *dev = to_nullb_device(item);
+	ssize_t ret;
 
-	return zone_cond_store(dev, page, count, BLK_ZONE_COND_OFFLINE);
+	mutex_lock(&lock);
+	ret = zone_cond_store(dev, page, count, BLK_ZONE_COND_OFFLINE);
+	mutex_unlock(&lock);
+
+	return ret;
 }
 CONFIGFS_ATTR_WO(nullb_device_, zone_offline);
 
@@ -836,7 +846,6 @@ static void null_free_dev(struct nullb_device *dev)
 	if (!dev)
 		return;
 
-	null_free_zoned_dev(dev);
 	badblocks_exit(&dev->badblocks);
 	kfree(dev);
 }
@@ -1777,6 +1786,7 @@ static void null_del_dev(struct nullb *nullb)
 	}
 
 	put_disk(nullb->disk);
+	null_free_zoned_dev(dev);
 	if (nullb->tag_set == &nullb->__tag_set)
 		blk_mq_free_tag_set(nullb->tag_set);
 	kfree(nullb->queues);
Signature · 1 line
2.53.0
author maintainer
#1501 lore raw

PATCH 1485/1815 null_blk: reject per-device queue resize for shared tag set

In reply to Greg Kroah-Hartman

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

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

From: Zizhi Wo <[email protected]>

[ Upstream commit 1cdfe2fa62b48728a9b436fbbd3dbe4c11593e24 ]

When shared_tags is enabled, null_setup_tagset() makes the device use the global tag_set, whose driver_data stays NULL. null_map_queues() therefore falls back to the module-wide g_submit_queues/g_poll_queues instead of any per-device value.

Resizing submit_queues or poll_queues via configfs on such a device calls blk_mq_update_nr_hw_queues() on the shared set, shrinking set->nr_hw_queues. __blk_mq_realloc_hw_ctxs() only grows the q->queue_hw_ctx[] allocation, so on shrink it merely exits and NULLs the now-excess hctx slots. null_map_queues(), however, keeps mapping CPUs with the unchanged g_submit_queues/g_poll_queues, so mq_map[] ends up pointing at those NULLed hctx slots. blk_mq_map_swqueue() then dereferences the NULL hctx (hctx->cpumask), crashing the kernel:

[  460.218374] KASAN: null-ptr-deref in range [0x0000000000000098-0x000000000000009f]
[  460.219003] CPU: 24 UID: 0 PID: 1492 Comm: sh Not tainted 7.2.0-rc2+ #67 PREEMPT(full)
[  460.219792] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-4.fc41 04/01/2014
[  460.220452] RIP: 0010:blk_mq_map_swqueue+0x4db/0x1430
......
[  460.228977] Call Trace:
[  460.229175]  <TASK>
[  460.229354]  blk_mq_update_nr_hw_queues+0xd49/0x11c0
[  460.229779]  ? __pfx_blk_mq_update_nr_hw_queues+0x10/0x10
[  460.230200]  nullb_update_nr_hw_queues+0x1a9/0x370 [null_blk]
[  460.230694]  nullb_device_submit_queues_store+0xd9/0x170 [null_blk]
[  460.231190]  ? __pfx_nullb_device_submit_queues_store+0x10/0x10 [null_blk]
[  460.231776]  ? configfs_write_iter+0x35c/0x4e0
[  460.232122]  configfs_write_iter+0x286/0x4e0
[  460.232460]  vfs_write+0x52d/0xd00
[  460.232779]  ? __x64_sys_openat+0x108/0x1d0
[  460.233106]  ? __pfx_vfs_write+0x10/0x10
[  460.233413]  ? fdget_pos+0x1cf/0x4c0
[  460.233745]  ? fput_close+0x133/0x190
[  460.234038]  ? __pfx_expand_files+0x10/0x10
[  460.234368]  ksys_write+0xfc/0x1d0

Reproducer:
modprobe null_blk shared_tags=1 submit_queues=64 poll_queues=1 mkdir /sys/kernel/config/nullb/dev
echo 1 > /sys/kernel/config/nullb/dev/power
echo 1 > /sys/kernel/config/nullb/dev/submit_queues

A per-device resize of a shared tag set is meaningless anyway, so reject it with -EINVAL in nullb_update_nr_hw_queues() when the device is bound to the global tag_set.

Fixes 45919fbfe1c4 ("null_blk: Enable modifying 'submit_queues' after an instance has been configured")
Assisted-by Claude-Code:GLM-5.2
---
 drivers/block/null_blk/main.c | 9 +++++++++
 1 file changed, 9 insertions(+)
drivers/block/null_blk/main.c +9 -0
index 78bc0206c43fe..6494b802756b5 100644
@@ -382,6 +382,15 @@ static int nullb_update_nr_hw_queues(struct nullb_device *dev,
 	if (!dev->nullb)
 		return 0;
 
+	/*
+	 * A shared tag_set is mapped via the module-wide queue counts, so a
+	 * per-device resize is meaningless. On shrink it would also leave
+	 * mq_map[] pointing at NULLed hctx slots, causing a NULL deref in
+	 * blk_mq_map_swqueue(). Reject it.
+	 */
+	if (dev->shared_tags)
+		return -EINVAL;
+
 	/*
 	 * Make sure at least one submit queue exists.
 	 */
Signature · 1 line
2.53.0
author maintainer
#1502 lore raw

PATCH 1486/1815 null_blk: serialize configfs attribute stores with the lock

In reply to Greg Kroah-Hartman

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

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

From: Zizhi Wo <[email protected]>

[ Upstream commit 7e7fff51808237703a3a1df6dd5cae1dfd1db86d ]

The NULLB_DEVICE_ATTR _store takes no lock: apply_fn attributes (submit_queues, poll_queues) get dev->NAME written again after apply_fn returns, outside its lock; APPLY=NULL attributes are entirely lockless. configfs only serializes stores per-open-file, so concurrent stores on separate fds race.

For apply_fn attributes, once one store's apply_fn has reconfigured the hardware, a second (losing) store can still overwrite dev->NAME afterwards. This leaves dev->submit_queues out of sync with the live queue count, which is later caught by the WARN_ON_ONCE() in null_map_queues().

For !apply_fn attributes, power_store()'s null_add_dev() validates and builds the device under "lock" but only sets CONFIGURED afterwards. A store slipping in during this window can change a field mid-setup -- for example, zone_nr_conv can be pushed above nr_zones after it has already been clamped, leading to an out-of-bounds dev->zones[] access.

Take "lock" in the macro around the apply_fn call, the CONFIGURED test and the field write, and move it out of nullb_apply_submit_queues()/ nullb_apply_poll_queues() so both paths are covered once. This serializes stores with power_store's setup and with each other.

Fixes 45919fbfe1c4 ("null_blk: Enable modifying 'submit_queues' after an instance has been configured")
---
 drivers/block/null_blk/main.c | 17 +++--------------
 1 file changed, 3 insertions(+), 14 deletions(-)
drivers/block/null_blk/main.c +3 -14
index 6494b802756b5..0db0ac65cf49e 100644
@@ -360,6 +360,7 @@ nullb_device_##NAME##_store(struct config_item *item, const char *page,	\
 	ret = nullb_device_##TYPE##_attr_store(&new_value, page, count);\
 	if (ret < 0)							\
 		return ret;						\
+	guard(mutex)(&lock);						\
 	if (apply_fn)							\
 		ret = apply_fn(dev, new_value);				\
 	else if (test_bit(NULLB_DEV_FL_CONFIGURED, &dev->flags)) 	\
@@ -430,25 +431,13 @@ static int nullb_update_nr_hw_queues(struct nullb_device *dev,
 static int nullb_apply_submit_queues(struct nullb_device *dev,
 				     unsigned int submit_queues)
 {
-	int ret;
-
-	mutex_lock(&lock);
-	ret = nullb_update_nr_hw_queues(dev, submit_queues, dev->poll_queues);
-	mutex_unlock(&lock);
-
-	return ret;
+	return nullb_update_nr_hw_queues(dev, submit_queues, dev->poll_queues);
 }
 
 static int nullb_apply_poll_queues(struct nullb_device *dev,
 				   unsigned int poll_queues)
 {
-	int ret;
-
-	mutex_lock(&lock);
-	ret = nullb_update_nr_hw_queues(dev, dev->submit_queues, poll_queues);
-	mutex_unlock(&lock);
-
-	return ret;
+	return nullb_update_nr_hw_queues(dev, dev->submit_queues, poll_queues);
 }
 
 NULLB_DEVICE_ATTR(size, ulong, NULL);
Signature · 1 line
2.53.0
author maintainer
#1503 lore raw

PATCH 1487/1815 null_blk: serialize configfs attribute updates with device setup

In reply to Greg Kroah-Hartman

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

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

From: Niklas Cassel <[email protected]>

[ Upstream commit 4e1f23f9c33c156be7e313b40695af5a3a834739 ]

The attribute store methods generated with NULLB_DEVICE_ATTR() refuse to change the configuration of a live device by testing NULLB_DEV_FL_CONFIGURED, but that flag is only set by nullb_device_power_store() after null_add_dev() has returned, and the store methods take no lock at all. configfs only serializes writes to the same open file (buffer->mutex), so a write to any attribute can run concurrently with null_add_dev() and change the device configuration while it is being used.

null_add_dev() reads the configuration several times, e.g. dev->zoned is read once to set up the queue limits and once to initialize the zone resources:

CPU0: echo 1 > nullb0/power CPU1: echo 1 > nullb0/zoned
nullb_device_power_store()

    mutex_lock(&lock)
    null_add_dev()
      if (dev->zoned) -> false
        /* no BLK_FEAT_ZONED */       nullb_device_zoned_store()
                                        test_bit(FL_CONFIGURED) -> 0
                                        dev->zoned = true
      blk_mq_alloc_disk()
        /* queue is not zoned */
      if (nullb->dev->zoned) -> true
        null_register_zoned_dev()
          blk_revalidate_disk_zones()

blk_revalidate_disk_zones() is then called for a queue that does not have BLK_FEAT_ZONED set, which triggers its WARN_ON_ONCE() and fails the device setup with -EIO:

  WARNING: CPU: 2 PID: 322 at block/blk-zoned.c:2357 blk_revalidate_disk_zones+0x4c/0x560

Clearing dev->zoned in the same window is worse: the queue is created with BLK_FEAT_ZONED but the zone resources are never initialized, so add_disk() succeeds for a zoned disk that has no zones. And a store that lands after the last dev->zoned test leaves dev->zoned set while dev->zones is still NULL, which null_process_zoned_cmd() dereferences on the first write.

Fix this by taking the global lock, which nullb_device_power_store() already holds across null_add_dev() and null_del_dev(), around both the NULLB_DEV_FL_CONFIGURED test and the update of the device configuration. The submit_queues and poll_queues apply callbacks are now called with that lock held, so remove the locking they did themselves.

Since the store methods can run as soon as configfs_register_subsystem() returns, that is, before null_init() gets to mutex_init(&lock), also initialize the lock statically with DEFINE_MUTEX().

---
 drivers/block/null_blk/main.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)
drivers/block/null_blk/main.c +11 -3
index 0db0ac65cf49e..4a9beec211b92 100644
@@ -340,7 +340,15 @@ static ssize_t nullb_device_bool_attr_store(bool *val, const char *page,
 	return count;
 }
 
-/* The following macro should only be used with TYPE = {uint, ulong, bool}. */
+/*
+ * The following macro should only be used with TYPE = {uint, ulong, bool}.
+ *
+ * The device configuration is modified under the global lock to serialize
+ * attribute changes against null_add_dev() and null_del_dev(): without this,
+ * an attribute could be changed while null_add_dev() is running, that is,
+ * before NULLB_DEV_FL_CONFIGURED is set, which would let null_add_dev()
+ * observe inconsistent values for the device configuration.
+ */
 #define NULLB_DEVICE_ATTR(NAME, TYPE, APPLY)				\
 static ssize_t								\
 nullb_device_##NAME##_show(struct config_item *item, char *page)	\
@@ -380,6 +388,8 @@ static int nullb_update_nr_hw_queues(struct nullb_device *dev,
 	struct blk_mq_tag_set *set;
 	int ret, nr_hw_queues;
 
+	lockdep_assert_held(&lock);
+
 	if (!dev->nullb)
 		return 0;
 
@@ -2215,8 +2225,6 @@ static void __exit null_exit(void)
 
 	if (tag_set.ops)
 		blk_mq_free_tag_set(&tag_set);
-
-	mutex_destroy(&lock);
 }
 
 module_init(null_init);
Signature · 1 line
2.53.0
author maintainer
#1504 lore raw

PATCH 1488/1815 blk-iolatency: clear delay state when freeing policy data

In reply to Greg Kroah-Hartman

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

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

From: Usama Arif <[email protected]>

[ Upstream commit 8935bf22c0a0db517a7f72f7097300e05dd852f5 ]

io.latency can throttle a group which has no latency target of its own. When a sibling misses its target, check_scale_change() scales down its peers, and a peer that reaches queue depth one gets blkcg_use_delay() called on it on every further scale-down, even with min_lat_nsec == 0.

iolatency_pd_offline() resets the target through iolatency_set_min_lat_nsec(), which clears the delay only on a nonzero to zero transition, so it never clears such a peer. Freeing the policy data then leaves blkg->use_delay set and blkcg->congestion_count elevated with nothing left that can drop it.

blk_cgroup_congested() then returns true for every task in that cgroup and its descendants for as long as the cgroup lives: page_cache_sync_ra() cuts readahead to a single page, page_cache_async_ra() skips it altogether, and __folio_throttle_swaprate() takes swap_avail_lock and schedules a throttle on anonymous folio allocation.

Clear the delay in iolatency_pd_free(). By then bio-held blkg references have drained, or the queue is frozen for policy deactivation, so check_scale_change() cannot re-arm it. The free callback can also see policy data which was never attached to a blkg, hence the pd->blkg check.

Fixes d70675121546 ("block: introduce blk-iolatency io controller")
---
 block/blk-iolatency.c | 9 +++++++++
 1 file changed, 9 insertions(+)
block/blk-iolatency.c +9 -0
index 9eb69010c34e6..2caa79a008ad1 100644
@@ -1043,6 +1043,15 @@ static void iolat_release(struct rcu_head *rcu)
 
 static void iolatency_pd_free(struct blkg_policy_data *pd)
 {
+	struct blkcg_gq *blkg = pd_to_blkg(pd);
+
+	/*
+	 * Groups throttled as collateral have min_lat_nsec == 0, so
+	 * iolatency_pd_offline() leaves their delay set.  Drop it here, where
+	 * no in-flight bio can re-arm it via check_scale_change().
+	 */
+	if (blkg)
+		blkcg_clear_delay(blkg);
 	call_rcu(&pd->rcu_head, iolat_release);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1505 lore raw

PATCH 1489/1815 blk-iocost: clear delay state when freeing policy data

In reply to Greg Kroah-Hartman

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

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

From: Usama Arif <[email protected]>

[ Upstream commit 97cb95d2148835ae86ff916b145aef332d40439d ]

iocg_kick_delay() turns sufficiently large debt into an explicit block-cgroup delay with blkcg_set_delay(), setting blkg->use_delay to -1 and incrementing blkcg->congestion_count. Clearing it again depends on iocg_kick_delay() running from the period timer, the waitq timer or the issue path.

ioc_pd_free() removes the iocg from active_iocgs and cancels its waitq timer, and no further bios can arrive, so once it has run nothing is left which can reduce the debt and clear the delay. The blkcg stays marked congested for the rest of its life.

blk_cgroup_congested() then returns true for every task in that cgroup and its descendants: page_cache_sync_ra() cuts readahead to a single page, page_cache_async_ra() skips it altogether, and __folio_throttle_swaprate() takes swap_avail_lock and schedules a throttle on anonymous folio allocation.

Clear it explicitly, after the list removal and the synchronous hrtimer_cancel() so that neither timer processing nor an I/O path can re-arm it. The free callback can also see policy data which was never attached to a blkg, hence the pd->blkg check.

---
 block/blk-iocost.c | 7 +++++++
 1 file changed, 7 insertions(+)
block/blk-iocost.c +7 -0
index b60625613e095..64b92aa3e5d48 100644
@@ -3063,6 +3063,7 @@ static void iocg_release(struct rcu_head *rcu)
 static void ioc_pd_free(struct blkg_policy_data *pd)
 {
 	struct ioc_gq *iocg = pd_to_iocg(pd);
+	struct blkcg_gq *blkg = pd_to_blkg(pd);
 	struct ioc *ioc = iocg->ioc;
 	unsigned long flags;
 
@@ -3085,6 +3086,12 @@ static void ioc_pd_free(struct blkg_policy_data *pd)
 		hrtimer_cancel(&iocg->waitq_timer);
 	}
 
+	/* off ->active_iocgs and timer gone, so nothing can re-arm the delay */
+	iocg->delay = 0;
+	iocg->indelay_since = 0;
+	if (blkg)
+		blkcg_clear_delay(blkg);
+
 	call_rcu(&pd->rcu_head, iocg_release);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1506 lore raw

PATCH 1490/1815 ublk: reject non-power-of-2 zone sizes in SET_PARAMS

In reply to Greg Kroah-Hartman

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

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

From: Yao Sang <[email protected]>

[ Upstream commit 2707acf1856da266139986c9398ad722fd4f48c0 ]

UBLK_F_ZONED uses params.basic.chunk_sectors as zone size. ublk uses ilog2(chunk_sectors) to get number of zones, so the value must be power of 2.

If chunk_sectors is 96 and dev_sectors is 96 * 16, userspace asks for 16 zones. But the shift calculation gets 24 zones.

Block layer rejects such zone size when the disk is started. But SET_PARAMS has already returned success, which is confusing for userspace. Reject it in SET_PARAMS with other zoned parameter checks.

Fixes 29802d7ca33b ("ublk: enable zoned storage support")
---
 drivers/block/ublk_drv.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/block/ublk_drv.c +1 -1
index a5b120b42e493..0bbf1d5a4fbc6 100644
@@ -970,7 +970,7 @@ static int ublk_validate_params(const struct ublk_device *ub)
 		if (p->max_sectors < PAGE_SECTORS)
 			return -EINVAL;
 
-		if (ublk_dev_is_zoned(ub) && !p->chunk_sectors)
+		if (ublk_dev_is_zoned(ub) && !is_power_of_2(p->chunk_sectors))
 			return -EINVAL;
 	} else
 		return -EINVAL;
Signature · 1 line
2.53.0
author maintainer
#1507 lore raw

PATCH 1491/1815 ublk: avoid teardown retry loop on xarray allocation failure

In reply to Greg Kroah-Hartman

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

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

From: Yao Sang <[email protected]>

[ Upstream commit 4fd66a7f829f3f38f92a79081f0f2688aed644f0 ]

__ublk_shmem_remove_ranges() removes matching maple tree ranges in batches, but first stores each range into a temporary xarray so that the pages can be unpinned after dropping the maple tree lock.

That temporary xarray is filled under the maple tree lock with xa_store(..., GFP_ATOMIC). If the store fails before mas_erase(), the current range is left in the tree and the helper returns false. The outer ublk_shmem_remove_ranges() loop then immediately retries the same range. While the atomic allocation keeps failing, the teardown path has no forward progress.

The issue can be reproduced with radix_tree_node failslab injection after a SHMEM_ZC buffer has already been registered:

# Kernel config:

  #   CONFIG_BLK_DEV_UBLK=y
  #   CONFIG_DEBUG_FS=y
  #   CONFIG_FAULT_INJECTION=y
  #   CONFIG_FAULT_INJECTION_DEBUG_FS=y
  #   CONFIG_FAILSLAB=y

echo 10 > /proc/sys/vm/nr_hugepages
mkdir -p /tmp/htlb
mount -t hugetlbfs none /tmp/htlb
fallocate -l 4M /tmp/htlb/ublk_buf

  dev_id=$(kublk add -t null --shmem_zc \
		--htlb /tmp/htlb/ublk_buf |
	   awk -F '[ :]' '/dev id/ {print $3}')

echo 1 > /sys/kernel/slab/radix_tree_node/failslab echo Y > /sys/kernel/debug/failslab/cache-filter echo Y > /sys/kernel/debug/failslab/ignore-gfp-wait echo 1 > /sys/kernel/debug/failslab/interval echo -1 > /sys/kernel/debug/failslab/times echo 100 > /sys/kernel/debug/failslab/probability

kublk del -n "$dev_id"

On the unfixed kernel the delete command was still running after 3 seconds. Disabling failslab made it return. The fault-injection stack showed:

should_failslab
kmem_cache_alloc_lru_noprof
__xas_nomem
__xa_store
xa_store
__ublk_shmem_remove_ranges
ublk_cdev_rel
ublk_ctrl_del_dev

Remove the allocation from the teardown loop. Keep the existing batch limit, but collect {base_pfn, nr_pages} pairs in a fixed-size stack array. Once a matching range is found, the range is erased from the maple tree before dropping the lock, so each successful scan makes progress without depending on any GFP_ATOMIC allocation.

With the same failslab settings, the fixed kernel completed "kublk del -n $dev_id" successfully in about 45 ms.

Fixes 309e02dccf64 ("ublk: avoid unpinning pages under maple tree spinlock")
---
 drivers/block/ublk_drv.c | 31 ++++++++++++++-----------------
 1 file changed, 14 insertions(+), 17 deletions(-)
drivers/block/ublk_drv.c +14 -17
index 0bbf1d5a4fbc6..b71283588ea77 100644
@@ -5522,39 +5522,36 @@ static void ublk_unpin_range_pages(unsigned long base_pfn,
 
 /*
  * Inner loop: erase up to UBLK_REMOVE_BATCH matching ranges under
- * mas_lock, collecting them into an xarray. Then drop the lock and
- * unpin pages + free ranges outside spinlock context.
+ * mas_lock, collecting the page ranges in a fixed-size array. Then
+ * drop the lock and unpin pages + free ranges outside spinlock context.
  *
  * Returns true if the tree walk completed, false if more ranges remain.
- * Xarray key is the base PFN, value encodes nr_pages via xa_mk_value().
  */
 #define UBLK_REMOVE_BATCH	64
 
+struct ublk_unpin_range {
+	unsigned long base_pfn;
+	unsigned long nr_pages;
+};
+
 static bool __ublk_shmem_remove_ranges(struct ublk_device *ub,
 					int buf_index, int *ret)
 {
 	MA_STATE(mas, &ub->buf_tree, 0, ULONG_MAX);
 	struct ublk_buf_range *range;
-	struct xarray to_unpin;
-	unsigned long idx;
+	struct ublk_unpin_range to_unpin[UBLK_REMOVE_BATCH];
 	unsigned int count = 0;
+	unsigned int i;
 	bool done = false;
-	void *entry;
-
-	xa_init(&to_unpin);
 
 	mas_lock(&mas);
 	mas_for_each(&mas, range, ULONG_MAX) {
-		unsigned long nr;
-
 		if (buf_index >= 0 && range->buf_index != buf_index)
 			continue;
 
 		*ret = 0;
-		nr = mas.last - mas.index + 1;
-		if (xa_err(xa_store(&to_unpin, mas.index,
-				    xa_mk_value(nr), GFP_ATOMIC)))
-			goto unlock;
+		to_unpin[count].base_pfn = mas.index;
+		to_unpin[count].nr_pages = mas.last - mas.index + 1;
 		mas_erase(&mas);
 		kfree(range);
 		if (++count >= UBLK_REMOVE_BATCH)
@@ -5564,9 +5561,9 @@ static bool __ublk_shmem_remove_ranges(struct ublk_device *ub,
 unlock:
 	mas_unlock(&mas);
 
-	xa_for_each(&to_unpin, idx, entry)
-		ublk_unpin_range_pages(idx, xa_to_value(entry));
-	xa_destroy(&to_unpin);
+	for (i = 0; i < count; i++)
+		ublk_unpin_range_pages(to_unpin[i].base_pfn,
+				       to_unpin[i].nr_pages);
 
 	return done;
 }
Signature · 1 line
2.53.0
author maintainer
#1508 lore raw

PATCH 1492/1815 block: mtip32xx: synchronize ioctls with device removal

In reply to Greg Kroah-Hartman

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

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

From: Hongyan Xu <[email protected]>

[ Upstream commit 68940f841d013192086a0f6d7cfbac2cd079e228 ]

The ioctl handlers only test REMOVE_PENDING before entering mtip_hw_ioctl(). Removal can set that bit immediately afterwards and free dd->port in mtip_hw_exit() while an ioctl still dereferences it. An already open block device can reach the handlers while del_gendisk() is in progress.

Serialize both native and compat ioctls with removal. Set REMOVE_PENDING before taking the mutex so new callers fail after an in-flight ioctl has drained, and hold the mutex until the port has been torn down.

Fixes 88523a61558a ("block: Add driver for Micron RealSSD pcie flash cards")
---
 drivers/block/mtip32xx/mtip32xx.c | 7 +++++++
 drivers/block/mtip32xx/mtip32xx.h | 2 ++
 2 files changed, 9 insertions(+)
drivers/block/mtip32xx/mtip32xx.c +7 -0
index f214a616386c8..113bdb868c469 100644
@@ -3048,6 +3048,8 @@ static int mtip_block_ioctl(struct block_device *dev,
 	if (!dd)
 		return -ENOTTY;
 
+	guard(mutex)(&dd->ioctl_mutex);
+
 	if (unlikely(test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag)))
 		return -ENOTTY;
 
@@ -3086,6 +3088,8 @@ static int mtip_block_compat_ioctl(struct block_device *dev,
 	if (!dd)
 		return -ENOTTY;
 
+	guard(mutex)(&dd->ioctl_mutex);
+
 	if (unlikely(test_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag)))
 		return -ENOTTY;
 
@@ -3721,6 +3725,7 @@ static int mtip_pci_probe(struct pci_dev *pdev,
 	dd = kzalloc_node(sizeof(struct driver_data), GFP_KERNEL, my_node);
 	if (!dd)
 		return -ENOMEM;
+	mutex_init(&dd->ioctl_mutex);
 
 	/* Attach the private data to this PCI device.  */
 	pci_set_drvdata(pdev, dd);
@@ -3887,6 +3892,7 @@ static void mtip_pci_remove(struct pci_dev *pdev)
 	}
 
 	set_bit(MTIP_DDF_REMOVE_PENDING_BIT, &dd->dd_flag);
+	mutex_lock(&dd->ioctl_mutex);
 
 	if (test_bit(MTIP_DDF_INIT_DONE_BIT, &dd->dd_flag))
 		del_gendisk(dd->disk);
@@ -3915,6 +3921,7 @@ static void mtip_pci_remove(struct pci_dev *pdev)
 
 	/* De-initialize the protocol layer. */
 	mtip_hw_exit(dd);
+	mutex_unlock(&dd->ioctl_mutex);
 
 	if (dd->isr_workq) {
 		destroy_workqueue(dd->isr_workq);
drivers/block/mtip32xx/mtip32xx.h +2 -0
index f7328f19ac5c2..0963c07b58457 100644
@@ -12,6 +12,7 @@
 #define __MTIP32XX_H__
 
 #include <linux/spinlock.h>
+#include <linux/mutex.h>
 #include <linux/rwsem.h>
 #include <linux/ata.h>
 #include <linux/interrupt.h>
@@ -432,6 +433,7 @@ struct driver_data {
 	struct request_queue *queue; /* Our request queue. */
 
 	struct blk_mq_tag_set tags; /* blk_mq tags */
+	struct mutex ioctl_mutex;
 
 	struct mtip_port *port; /* Pointer to the port data structure. */
 
Signature · 1 line
2.53.0
author maintainer
#1509 lore raw

PATCH 1493/1815 selftests/mm: thuge-gen: fix test_shmget() for PAGE_SIZE check

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 08745c62350126bc31b09548137be87e2866f628 ]

Commit 49a4e7186b08 ("selftests/mm: thuge-gen: add setup of HugeTLB pages") changed thuge-gen test to use common functions for reading hugetlb attributes from sysfs, but it missed that the original read_free() function special cased PAGE_SIZE tests.

For PAGE_SIZE tests, failure to read sysfs was ignored and read_free() returned 0.

This allowed test_shmget() to essentially skip the check of how many huge pages was consumed when it ran with PAGE_SIZE.

Commit 3199b0c09efa ("selftests/mm: fix read_file() return value check") fixed checks for read_file() return value and this exposed the issue in test_shmget() that checks the number of free hugetlb pages even for PAGE_SIZE test, tries to access

/sys/kernel/mm/hugepages/hugepages-<PAGE_SIZE>/free_hugepages

and obviously fails there.

Gate the checks for free huge pages on size != getpagesize() and initialize before and after variables to values matching PAGE_SIZE test.

Fixes 49a4e7186b08 ("selftests/mm: thuge-gen: add setup of HugeTLB pages")
Cc Liam R. Howlett <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
---
 tools/testing/selftests/mm/thuge-gen.c | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
tools/testing/selftests/mm/thuge-gen.c +10 -5
index 22b9c2f1c35d2..50d0805b65db9 100644
@@ -71,12 +71,16 @@ void test_mmap(unsigned long size, unsigned flags)
 
 void test_shmget(unsigned long size, unsigned flags)
 {
-	int id;
-	unsigned long before, after;
+	/* values for PAGE_SIZE test */
+	unsigned long before = NUM_PAGES;
+	unsigned long after = 0;
 	struct shm_info i;
 	char *map;
+	int id;
+
+	if (size != getpagesize())
+		before = hugetlb_free_pages(size);
 
-	before = hugetlb_free_pages(size);
 	id = shmget(IPC_PRIVATE, size * NUM_PAGES, IPC_CREAT|0600|flags);
 	if (id < 0) {
 		if (errno == EPERM) {
@@ -97,10 +101,11 @@ void test_shmget(unsigned long size, unsigned flags)
 	shmctl(id, IPC_RMID, NULL);
 
 	memset(map, 0xff, size*NUM_PAGES);
-	after = hugetlb_free_pages(size);
+	if (size != getpagesize())
+		after = hugetlb_free_pages(size);
 
 	show(size);
-	ksft_test_result(size == getpagesize() || (before - after) == NUM_PAGES,
+	ksft_test_result((before - after) == NUM_PAGES,
 			 "%s: mmap %lu %x\n", __func__, size, flags);
 	if (shmdt(map))
 		ksft_exit_fail_msg("%s: shmdt: %s\n", __func__, strerror(errno));
Signature · 1 line
2.53.0
author maintainer
#1510 lore raw

PATCH 1494/1815 apparmor: fix deadlock in complain-mode change_hat

In reply to Greg Kroah-Hartman

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

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

From: John Johansen <[email protected]>

[ Upstream commit 4ec11f14d1d6fdda787d991b142537be7841d395 ]

The use of change_hat when in complain mode can cause a deadlock when the hat doesn't exist and a new learning profile is created for the missing profile. This is because change_hat() has taken the lock to search the hat list and creating the new learning profile needs to take the lock to add it to the list.

Quoted 1 line

From the bug report:

Originally found in 7.0.0 in LTS ubuntu 26.04 with pam_apparmor + su in complain mode set to change hats. Then verified in newest available vanilla kernel I've compiled to see if still present:

7.2-rc7 vanilla -> affected

checked also some other kernels:
6.18.44 vanilla -> affected
6.12.95 with debian patches -> unaffected

On systems without bug (for example 6.12.95 debian) it just prints:

aa_change_hat rc=0

On systems with bug, the executable always hangs, prints nothing and becomes unkillable. (And once stuck this way, it will cause any further hat changes to also cause the changing process to get stuck)

Then in syslog you can find hint about cause:

kernel: INFO: task hat:3409 blocked for more than 483 seconds.
kernel:       Not tainted 7.2.0-rc7 #1
kernel: "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message.
kernel: task:hat             state:D stack:0     pid:3409  tgid:3409  ppid:2605   task_flags:0x400000 flags:0x00080800
kernel: Call Trace:
kernel:  <TASK>
kernel:  __schedule+0x48f/0xfe0
kernel:  schedule+0x27/0xa0
kernel:  schedule_preempt_disabled+0x15/0x30
kernel:  __mutex_lock.constprop.0+0x569/0xa10
kernel:  aa_new_learning_profile+0x15f/0x210
kernel:  build_change_hat+0x19f/0x3b0
kernel:  change_hat.isra.0+0x5dd/0xd60
kernel:  aa_change_hat+0x2f3/0x710
kernel:  aa_setprocattr_changehat+0x121/0x1f0
kernel:  do_setattr+0x28c/0x340
kernel:  apparmor_setselfattr+0x20/0x50
kernel:  security_setselfattr+0xf6/0x110
kernel:  __x64_sys_lsm_set_self_attr+0x53/0x90
kernel:  do_syscall_64+0xdd/0x5e0
kernel:  ? __mod_memcg_lruvec_state+0xfd/0x260
kernel:  ? lruvec_stat_mod_folio+0x8d/0xd0
kernel:  ? __folio_mod_stat+0x2d/0x90
kernel:  ? map_anon_folio_pte_nopf+0xd1/0x1f0
kernel:  ? do_anonymous_page+0x184/0xa10
kernel:  ? __handle_mm_fault+0x805/0x870
kernel:  ? count_memcg_events+0xef/0x230
kernel:  ? handle_mm_fault+0x1f0/0x2f0
kernel:  ? do_user_addr_fault+0x2bb/0x7b0
kernel:  ? do_syscall_64+0x94/0x5e0
kernel:  ? exc_page_fault+0x75/0x160
kernel:  entry_SYSCALL_64_after_hwframe+0x76/0x7e
kernel: RIP: 0033:0x7f815e134c8d
kernel: RSP: 002b:00007fff6df94ea8 EFLAGS: 00000246 ORIG_RAX: 00000000000001cc
kernel: RAX: ffffffffffffffda RBX: 0000556d8c81d040 RCX: 00007f815e134c8d
kernel: RDX: 0000000000000046 RSI: 0000556d8c81d040 RDI: 0000000000000064
kernel: RBP: 00007fff6df94ef0 R08: 00007f815e212ac8 R09: 000000000000000c
kernel: R10: 0000000000000000 R11: 0000000000000246 R12: 0000556d8c81d010
kernel: R13: 0000000000000026 R14: 0000000000000046 R15: 0000000000000064
kernel:  </TASK>
kernel: INFO: task hat:3409 is blocked on a mutex likely owned by task hat:3409.

To fix the issue, lift the locking out of the core of aa_new_learning_profile(), introduce a wrapper function that takes the lock where needed, and have build_change_hat() call the core function that no longer takes the lock.

In addition fix 4 other issues introduced by commit
32e92764d6f8d ("apparmor: grab ns lock and refresh when looking up changehat child profiles")
- aa_get_profile_rcu() was replaced-by: aa_get_profile without the accompanying rcu_dereference_protected()
- an extra aa_get_label(label) was introduced at the start of
change_hat() without an accompanying aa_put_label() causing a
reference count leak.
- a reference count leak was introduced in the label_is_stale(label)
case, where the newest profile would be leaked instead of the
label passed to the function.
- a potential UAF when the lookup walks up the tree with new_ns != ns
the new label reference is put, and then used for the next lookup.
The mutex_lock, will block replacement, and removal in the locked
ns. However there are two cases where putting the reference can
result in the label being freed even with the lock held.

1. the label does not have a list reference (possible for temporary or special profiles) in which case the put can trigger the cleanup.
2. the new label reference is in a different namespace, which does not have a lock held on it. This extends case 1 to also include replacement, and removal that could be occurring in the namespace new is in.

Fixes 32e92764d6f8d ("apparmor: grab ns lock and refresh when looking up changehat child profiles")
---
 security/apparmor/domain.c         | 26 +++++++++++++++++---------
 security/apparmor/include/policy.h |  3 +++
 security/apparmor/policy.c         | 22 +++++++++++++++++-----
 3 files changed, 37 insertions(+), 14 deletions(-)
security/apparmor/domain.c +17 -9
index 578f7cabebd51..e88c19c9b175a 100644
@@ -1133,8 +1133,8 @@ static struct aa_label *build_change_hat(const struct cred *subj_cred,
 	if (!hat) {
 		error = -ENOENT;
 		if (COMPLAIN_MODE(profile)) {
-			hat = aa_new_learning_profile(profile, true, name,
-						      GFP_KERNEL);
+			hat = __aa_new_learning_profile(profile, true, name,
+							GFP_KERNEL);
 			if (!hat) {
 				info = "failed null profile create";
 				error = -ENOMEM;
@@ -1172,6 +1172,7 @@ static struct aa_label *change_hat(const struct cred *subj_cred,
 	bool sibling = false;
 	const char *name, *info = NULL;
 	int i, error;
+	bool needput = false;
 
 	AA_BUG(!label);
 	AA_BUG(!hats);
@@ -1184,7 +1185,6 @@ static struct aa_label *change_hat(const struct cred *subj_cred,
 	 * the profiles and label, we can rely on the namespaces being live
 	 * and avoid incrementing their refcounts while grabbing the lock.
 	 */
-	label = aa_get_label(label);
 	ns = labels_ns(label);
 
 retry:
@@ -1192,15 +1192,19 @@ static struct aa_label *change_hat(const struct cred *subj_cred,
 	if (label_is_stale(label)) {
 		new = aa_get_newest_label(label);
 		new_ns = labels_ns(new);
+
+		if (needput)
+			/* aa_put_label() is safe to call when under lock */
+			aa_put_label(label);
+		label = new;
+		needput = true;
+		/* check if replaced with label in parent ns, and lock there */
 		if (new_ns != ns) {
-			aa_put_label(new);
 			mutex_unlock(&ns->lock);
 			ns = new_ns;
-			label = new;
+			/* retry will bottom out at the root of the tree */
 			goto retry;
 		}
-		aa_put_label(label);
-		label = new;
 	}
 
 	if (PROFILE_IS_HAT(labels_profile(label)))
@@ -1211,7 +1215,8 @@ static struct aa_label *change_hat(const struct cred *subj_cred,
 		name = hats[i];
 		label_for_each_in_scope(it, labels_ns(label), label, profile) {
 			if (sibling && PROFILE_IS_HAT(profile)) {
-				root = aa_get_profile(profile->parent);
+				root = aa_get_profile(rcu_dereference_protected(profile->parent,
+						      mutex_is_locked(&ns->lock)));
 			} else if (!sibling && !PROFILE_IS_HAT(profile)) {
 				root = aa_get_profile(profile);
 			} else {	/* conflicting change type */
@@ -1272,6 +1277,8 @@ static struct aa_label *change_hat(const struct cred *subj_cred,
 		}
 	}
 	mutex_unlock(&ns->lock);
+	if (needput)
+		aa_put_label(label);
 	return ERR_PTR(error);
 
 build:
@@ -1282,7 +1289,8 @@ static struct aa_label *change_hat(const struct cred *subj_cred,
 	mutex_unlock(&ns->lock);
 	AA_BUG(!new);
 	/* return new label or error ptr */
-
+	if (needput)
+		aa_put_label(label);
 	return new;
 }
 
security/apparmor/include/policy.h +3 -0
index 3895f8774a3f9..c6439ce6e436a 100644
@@ -295,6 +295,9 @@ struct aa_profile *aa_alloc_profile(const char *name, struct aa_proxy *proxy,
 				    gfp_t gfp);
 struct aa_profile *aa_alloc_null(struct aa_profile *parent, const char *name,
 				 gfp_t gfp);
+struct aa_profile *__aa_new_learning_profile(struct aa_profile *parent,
+					     bool hat, const char *base,
+					     gfp_t gfp);
 struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat,
 					   const char *base, gfp_t gfp);
 void aa_free_profile(struct aa_profile *profile);
security/apparmor/policy.c +17 -5
index 94b4a7e727cc1..cd87370578dda 100644
@@ -719,7 +719,7 @@ struct aa_profile *aa_alloc_null(struct aa_profile *parent, const char *name,
 }
 
 /**
- * aa_new_learning_profile - create or find a null-X learning profile
+ * __aa_new_learning_profile - create or find a null-X learning profile
  * @parent: profile that caused this profile to be created (NOT NULL)
  * @hat: true if the null- learning profile is a hat
  * @base: name to base the null profile off of
@@ -736,8 +736,9 @@ struct aa_profile *aa_alloc_null(struct aa_profile *parent, const char *name,
  *
  * Returns: new refcounted profile else NULL on failure
  */
-struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat,
-					   const char *base, gfp_t gfp)
+struct aa_profile *__aa_new_learning_profile(struct aa_profile *parent,
+					     bool hat, const char *base,
+					     gfp_t gfp)
 {
 	struct aa_profile *p, *profile;
 	const char *bname;
@@ -745,6 +746,7 @@ struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat,
 	size_t name_sz;
 
 	AA_BUG(!parent);
+	AA_BUG(!mutex_is_locked(&parent->ns->lock));
 
 	if (base) {
 		name_sz = strlen(parent->base.hname) + 8 + strlen(base);
@@ -778,7 +780,6 @@ struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat,
 	if (hat)
 		profile->label.flags |= FLAG_HAT;
 
-	mutex_lock_nested(&profile->ns->lock, profile->ns->level);
 	p = __find_child(&parent->base.profiles, bname);
 	if (p) {
 		aa_free_profile(profile);
@@ -786,7 +787,6 @@ struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat,
 	} else {
 		__add_profile(&parent->base.profiles, profile);
 	}
-	mutex_unlock(&profile->ns->lock);
 
 	/* refcount released by caller */
 out:
@@ -800,6 +800,18 @@ struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat,
 	return NULL;
 }
 
+struct aa_profile *aa_new_learning_profile(struct aa_profile *parent, bool hat,
+					   const char *base, gfp_t gfp)
+{
+	struct aa_profile *profile;
+
+	mutex_lock_nested(&parent->ns->lock, parent->ns->level);
+	profile = __aa_new_learning_profile(parent, hat, base, gfp);
+	mutex_unlock(&parent->ns->lock);
+
+	return profile;
+}
+
 /**
  * replacement_allowed - test to see if replacement is allowed
  * @profile: profile to test if it can be replaced  (MAYBE NULL)
Signature · 1 line
2.53.0
author maintainer
#1511 lore raw

PATCH 1495/1815 hwmon: (coretemp) Fix core_data leak on CPUs without PTS

In reply to Greg Kroah-Hartman

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

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

From: Szymon Wilczek <[email protected]>

[ Upstream commit 0cd8450c257faa0cece0e0c43d3b55d1a389acc7 ]

pdata->core_data is allocated in init_temp_data() when the first core temp_data of a package is created, but it is only released from destroy_temp_data(), and only in the branch that handles the package temp_data.

Package temp_data is created solely when the CPU supports X86_FEATURE_PTS. On a CPU without it, coretemp_cpu_online() never calls coretemp_add_core() with pkg_flag set, so pdata->pkg_data stays NULL. coretemp_cpu_offline() then skips the removal of the package interface, destroy_temp_data() is never called for package data, and the array is still allocated when coretemp_device_remove() frees the platform data that pointed at it.

Release the array in coretemp_device_remove(). destroy_temp_data() sets pdata->core_data to NULL when it frees it, so the added kfree() is a no-op on CPUs that do have PTS.

Tested on an Intel Core i5-1135G7. The driver was instrumented to log every allocation and release of pdata->core_data, and the PTS check in coretemp_cpu_online() was patched out to emulate a CPU without package thermal support. Without this change the array was allocated and never released, and coretemp_device_remove() still saw a non-NULL pointer. With it the array is released and the pointer accounting balances. On an unmodified build the release still happens via the package temp_data and the added kfree() sees NULL, with no slab warnings over repeated module load and unload cycles.

Fixes 1a793caf6f69 ("hwmon: (coretemp) Use dynamic allocated memory for core temp_data")
---
 drivers/hwmon/coretemp.c | 1 +
 1 file changed, 1 insertion(+)
drivers/hwmon/coretemp.c +1 -0
index 6215ea49faaa9..ab9c8cbf887aa 100644
@@ -650,6 +650,7 @@ static void coretemp_device_remove(int zoneid)
 	struct platform_data *pdata = platform_get_drvdata(pdev);
 
 	ida_destroy(&pdata->ida);
+	kfree(pdata->core_data);
 	kfree(pdata);
 	platform_device_unregister(pdev);
 }
Signature · 1 line
2.53.0
author maintainer
#1512 lore raw

PATCH 1496/1815 hwmon: (emc1403) Drop hysteresis for low limit temperature

In reply to Greg Kroah-Hartman

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

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

From: Marius Cristea <[email protected]>

[ Upstream commit 75f2c0b3690702c90863c2e138cb5520670845ea ]

Remove the hysteresis for low temperature limit, in hardware the hysteresis is applied only to the maxim limit and the critical limit temperature.

Fixes 54392ce4446e3 ("hwmon: (emc1403) Add support for min_hyst attributes")
[groeck: Updated subject]
---
 Documentation/hwmon/emc1403.rst |  8 ++++----
 drivers/hwmon/emc1403.c         | 27 +++++++++++----------------
 2 files changed, 15 insertions(+), 20 deletions(-)
Documentation/hwmon/emc1403.rst +4 -4
index 77060d5153238..ce258f0fccc60 100644
@@ -71,10 +71,10 @@ and EMC14x8 support eight sensors (one internal, seven external).
 
 The chips implement three limits for each sensor: low (tempX_min), high
 (tempX_max) and critical (tempX_crit.) The chips also implement an
-hysteresis mechanism which applies to all limits. The relative difference
-is stored in a single register on the chip, which means that the relative
-difference between the limit and its hysteresis is always the same for
-all three limits.
+hysteresis mechanism which applies to high and critical limits. The relative
+difference is stored in a single register on the chip, which means that the
+relative difference between the limit and its hysteresis is always the same
+for high and critical limits.
 
 This implementation detail implies the following:
 
drivers/hwmon/emc1403.c +11 -16
index cd753b38709f2..2f6dadbce68a5 100644
@@ -305,10 +305,9 @@ static int emc1403_get_hyst(struct thermal_data *data, int channel,
 	ret = regmap_read(data->regmap, 0x21, &hyst);
 	if (ret < 0)
 		return ret;
-	if (map == temp_min)
-		*val = limit + hyst * 1000;
-	else
-		*val = limit - hyst * 1000;
+
+	*val = limit - hyst * 1000;
+
 	return 0;
 }
 
@@ -324,9 +323,6 @@ static int emc1403_temp_read(struct thermal_data *data, u32 attr, int channel, l
 	case hwmon_temp_input:
 		ret = emc1403_get_temp(data, channel, ema1403_temp_map[attr], val);
 		break;
-	case hwmon_temp_min_hyst:
-		ret = emc1403_get_hyst(data, channel, temp_min, val);
-		break;
 	case hwmon_temp_max_hyst:
 		ret = emc1403_get_hyst(data, channel, temp_max, val);
 		break;
@@ -548,7 +544,6 @@ static umode_t emc1403_temp_is_visible(const void *_data, u32 attr, int channel)
 	case hwmon_temp_max_alarm:
 	case hwmon_temp_crit_alarm:
 	case hwmon_temp_fault:
-	case hwmon_temp_min_hyst:
 	case hwmon_temp_max_hyst:
 		return 0444;
 	case hwmon_temp_min:
@@ -591,35 +586,35 @@ static const struct hwmon_channel_info * const emc1403_info[] = {
 	HWMON_CHANNEL_INFO(chip, HWMON_C_UPDATE_INTERVAL),
 	HWMON_CHANNEL_INFO(temp,
 			   HWMON_T_INPUT | HWMON_T_MIN | HWMON_T_MAX |
-			   HWMON_T_CRIT | HWMON_T_MIN_HYST | HWMON_T_MAX_HYST |
+			   HWMON_T_CRIT | HWMON_T_MAX_HYST |
 			   HWMON_T_CRIT_HYST | HWMON_T_MIN_ALARM |
 			   HWMON_T_MAX_ALARM | HWMON_T_CRIT_ALARM,
 			   HWMON_T_INPUT | HWMON_T_MIN | HWMON_T_MAX |
-			   HWMON_T_CRIT | HWMON_T_MIN_HYST | HWMON_T_MAX_HYST |
+			   HWMON_T_CRIT | HWMON_T_MAX_HYST |
 			   HWMON_T_CRIT_HYST | HWMON_T_MIN_ALARM |
 			   HWMON_T_MAX_ALARM | HWMON_T_CRIT_ALARM | HWMON_T_FAULT,
 			   HWMON_T_INPUT | HWMON_T_MIN | HWMON_T_MAX |
-			   HWMON_T_CRIT | HWMON_T_MIN_HYST | HWMON_T_MAX_HYST |
+			   HWMON_T_CRIT | HWMON_T_MAX_HYST |
 			   HWMON_T_CRIT_HYST | HWMON_T_MIN_ALARM |
 			   HWMON_T_MAX_ALARM | HWMON_T_CRIT_ALARM | HWMON_T_FAULT,
 			   HWMON_T_INPUT | HWMON_T_MIN | HWMON_T_MAX |
-			   HWMON_T_CRIT | HWMON_T_MIN_HYST | HWMON_T_MAX_HYST |
+			   HWMON_T_CRIT | HWMON_T_MAX_HYST |
 			   HWMON_T_CRIT_HYST | HWMON_T_MIN_ALARM |
 			   HWMON_T_MAX_ALARM | HWMON_T_CRIT_ALARM | HWMON_T_FAULT,
 			   HWMON_T_INPUT | HWMON_T_MIN | HWMON_T_MAX |
-			   HWMON_T_CRIT | HWMON_T_MIN_HYST | HWMON_T_MAX_HYST |
+			   HWMON_T_CRIT | HWMON_T_MAX_HYST |
 			   HWMON_T_CRIT_HYST | HWMON_T_MIN_ALARM |
 			   HWMON_T_MAX_ALARM | HWMON_T_CRIT_ALARM | HWMON_T_FAULT,
 			   HWMON_T_INPUT | HWMON_T_MIN | HWMON_T_MAX |
-			   HWMON_T_CRIT | HWMON_T_MIN_HYST | HWMON_T_MAX_HYST |
+			   HWMON_T_CRIT | HWMON_T_MAX_HYST |
 			   HWMON_T_CRIT_HYST | HWMON_T_MIN_ALARM |
 			   HWMON_T_MAX_ALARM | HWMON_T_CRIT_ALARM | HWMON_T_FAULT,
 			   HWMON_T_INPUT | HWMON_T_MIN | HWMON_T_MAX |
-			   HWMON_T_CRIT | HWMON_T_MIN_HYST | HWMON_T_MAX_HYST |
+			   HWMON_T_CRIT | HWMON_T_MAX_HYST |
 			   HWMON_T_CRIT_HYST | HWMON_T_MIN_ALARM |
 			   HWMON_T_MAX_ALARM | HWMON_T_CRIT_ALARM | HWMON_T_FAULT,
 			   HWMON_T_INPUT | HWMON_T_MIN | HWMON_T_MAX |
-			   HWMON_T_CRIT | HWMON_T_MIN_HYST | HWMON_T_MAX_HYST |
+			   HWMON_T_CRIT | HWMON_T_MAX_HYST |
 			   HWMON_T_CRIT_HYST | HWMON_T_MIN_ALARM |
 			   HWMON_T_MAX_ALARM | HWMON_T_CRIT_ALARM | HWMON_T_FAULT
 			   ),
Signature · 1 line
2.53.0
author maintainer
#1513 lore raw

PATCH 1497/1815 bpf: Check pointer type for all atomic RMW paths

In reply to Greg Kroah-Hartman

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

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

From: Yiyang Chen <[email protected]>

[ Upstream commit 4bc49ae344d65cfcef738f281ac575cf73ca2fc5 ]

Atomic RMW verification records an instruction pointer type only when the current destination is PTR_TO_ARENA. A second path can therefore reach the same instruction with an ordinary pointer without comparing it against the saved arena type.

The post-verification fixup uses the saved type to rewrite the instruction to BPF_PROBE_ATOMIC for every path. Record the actual destination type for all atomic RMW paths so the existing mismatch check rejects incompatible uses of one instruction.

---
 kernel/bpf/verifier.c | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)
kernel/bpf/verifier.c +3 -5
index e55c145de6ac0..14a9fd2d54720 100644
@@ -6529,11 +6529,9 @@ static int check_atomic_rmw(struct bpf_verifier_env *env,
 	if (err)
 		return err;
 
-	if (is_arena_reg(env, insn->dst_reg)) {
-		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
-		if (err)
-			return err;
-	}
+	err = save_aux_ptr_type(env, dst_reg->type, false);
+	if (err)
+		return err;
 	/* Check whether we can write into the same memory. */
 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
Signature · 1 line
2.53.0
author maintainer
#1514 lore raw

PATCH 1498/1815 ksmbd: Do not skip lock checks for single-byte ranges

In reply to Greg Kroah-Hartman

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

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

From: Guangshuo Li <[email protected]>

[ Upstream commit d40c24634fe077a0dc91fd11fccf44ce12b454d5 ]

check_lock_range() uses inclusive ranges. Its callers pass the end offset as start + length - 1, so start == end represents a valid single-byte range rather than an empty range.

The start == end shortcut therefore skips mandatory byte-range lock checks for one-byte reads, writes, copychunk operations and one-byte truncate ranges. A conflicting lock covering that byte is not checked and the operation is allowed to proceed.

Remove the shortcut. The truncate size == inode->i_size case is already handled by only calling check_lock_range() when the new size differs from the current file size.

Fixes 5d510ac31626 ("ksmbd: skip lock-range check on equal size to avoid size==0 underflow")
---
 fs/smb/server/vfs.c | 3 ---
 1 file changed, 3 deletions(-)
fs/smb/server/vfs.c +0 -3
index d324585c0566b..233d127f27015 100644
@@ -297,9 +297,6 @@ static int check_lock_range(struct file *filp, loff_t start, loff_t end,
 	struct file_lock_context *ctx = locks_inode_context(file_inode(filp));
 	int error = 0;
 
-	if (start == end)
-		return 0;
-
 	if (!ctx || list_empty_careful(&ctx->flc_posix))
 		return 0;
 
Signature · 1 line
2.53.0
author maintainer
#1515 lore raw

PATCH 1499/1815 smb: server: fix leak of ksmbd_ipc_login_request_ext() returned buffer

In reply to Greg Kroah-Hartman

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

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

From: Enzo Matsumiya <[email protected]>

[ Upstream commit 1c3ebf832d010c08afe1359215d4121cb1ed2de5 ]

Free it unconditionally after ksmbd_alloc_user() calls.

kmemleak splat:
unreferenced object 0xffff888103b83540 (size 192):

    comm "pool-0", pid 16970, jiffies 4377290937
    hex dump (first 32 bytes):
      00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00  ................
      00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
    backtrace (crc 408ccc66):
      __kvmalloc_node_noprof+0x730/0x920
      handle_generic_event+0xec/0x1a0 [ksmbd]
      genl_family_rcv_msg_doit+0xe0/0x130
      genl_rcv_msg+0x181/0x290
      netlink_rcv_skb+0x4f/0x100
      genl_rcv+0x28/0x40
      netlink_unicast+0x1e6/0x2c0
      netlink_sendmsg+0x20a/0x450
      ____sys_sendmsg+0x2e8/0x310
      ___sys_sendmsg+0x78/0xc0
      __sys_sendmsg+0x63/0xc0
      do_syscall_64+0xa1/0x670
      entry_SYSCALL_64_after_hwframe+0x76/0x7e
Fixes a77e0e02af1c ("ksmbd: add support for supplementary groups")
---
 fs/smb/server/auth.c             | 1 +
 fs/smb/server/mgmt/user_config.c | 1 +
 2 files changed, 2 insertions(+)
fs/smb/server/auth.c +1 -0
index 4e7b6f0e6b8cd..f2100e3ec54c9 100644
@@ -439,6 +439,7 @@ int ksmbd_krb5_authenticate(struct ksmbd_session *sess, char *in_blob,
 		resp_ext = ksmbd_ipc_login_request_ext(resp->login_response.account);
 
 	user = ksmbd_alloc_user(&resp->login_response, resp_ext);
+	kvfree(resp_ext);
 	if (!user) {
 		ksmbd_debug(AUTH, "login failure\n");
 		retval = -ENOMEM;
fs/smb/server/mgmt/user_config.c +1 -0
index cf45841d9d1b9..03184a3303b9f 100644
@@ -26,6 +26,7 @@ struct ksmbd_user *ksmbd_login_user(const char *account)
 		resp_ext = ksmbd_ipc_login_request_ext(account);
 
 	user = ksmbd_alloc_user(resp, resp_ext);
+	kvfree(resp_ext);
 out:
 	kvfree(resp);
 	return user;
Signature · 1 line
2.53.0
author maintainer
#1516 lore raw

PATCH 1500/1815 ksmbd: fix slab-out-of-bounds read in ksmbd_alloc_user()

In reply to Greg Kroah-Hartman

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

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

From: Yunseong Kim <[email protected]>

[ Upstream commit 7405d0ba294306721843bc551611775e6edef516 ]

ksmbd_alloc_user() copies resp->hash_sz bytes out of the mountd IPC login response with

	user->passkey_sz = resp->hash_sz;
	user->passkey = kmalloc(resp->hash_sz, KSMBD_DEFAULT_GFP);
	if (user->passkey)
		memcpy(user->passkey, resp->hash, resp->hash_sz);

resp->hash_sz is a __u16 supplied by the response, but resp->hash[] is only KSMBD_REQ_MAX_HASH_SZ bytes. A malformed or malicious login response can set hash_sz well beyond that (up to 65535), so the memcpy() reads past the end of the response object. ipc_validate_msg() does not bound hash_sz, so reject any response whose hash_sz exceeds the on-stack hash[] buffer before allocating and copying.

[ 2030.238706] BUG: KASAN: slab-out-of-bounds in ksmbd_alloc_user+0x278/0x680
[ 2030.240549] Read of size 65535 at addr ffff888121bb6680 by task kworker/4:1/18611
[ 2030.242296]
[ 2030.242710] CPU: 4 UID: 0 PID: 18611 Comm: kworker/4:1 Not tainted 7.1.0-next-20260623-virtme #96 PREEMPT(lazy)
[ 2030.242732] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014
[ 2030.242743] Workqueue: ksmbd-io handle_ksmbd_work
[ 2030.242763] Call Trace:
[ 2030.242769]  <TASK>
[ 2030.242776]  dump_stack_lvl+0xa2/0xd0
[ 2030.242794]  print_address_description+0x77/0x200
[ 2030.242815]  ? ksmbd_alloc_user+0x278/0x680
[ 2030.242831]  print_report+0x58/0x70
[ 2030.242848]  kasan_report+0x117/0x150
[ 2030.242869]  ? ksmbd_alloc_user+0x278/0x680
[ 2030.242888]  kasan_check_range+0x3c7/0x3f0
[ 2030.242908]  ? ksmbd_alloc_user+0x278/0x680
[ 2030.242925]  __asan_memcpy+0x29/0x70
[ 2030.242942]  ksmbd_alloc_user+0x278/0x680
[ 2030.242960]  ksmbd_login_user+0xc3/0x120
[ 2030.242978]  ntlm_authenticate+0x5e6/0x1b00
[ 2030.243017]  ? __pfx_ntlm_authenticate+0x10/0x10
[ 2030.243035]  ? ksmbd_session_lookup+0x188/0x1d0
[ 2030.243054]  ? __pfx_ksmbd_session_lookup+0x10/0x10
[ 2030.243090]  ? __sanitizer_cov_trace_switch+0x7b/0x140
[ 2030.243108]  smb2_sess_setup+0x1e4a/0x27b0
[ 2030.243126]  ? copy_from_kernel_nofault+0x199/0x300
[ 2030.243156]  ? __pfx_smb2_sess_setup+0x10/0x10
[ 2030.243173]  ? get_smb2_cmd_val+0xe3/0x1c0
[ 2030.243208]  handle_ksmbd_work+0x954/0x1280
[ 2030.243230]  ? __pfx_handle_ksmbd_work+0x10/0x10
[ 2030.243249]  ? process_scheduled_works+0xa07/0x1490
[ 2030.243270]  ? process_scheduled_works+0xa07/0x1490
[ 2030.243291]  process_scheduled_works+0xa70/0x1490
[ 2030.243320]  ? __pfx_process_scheduled_works+0x10/0x10
[ 2030.243340]  ? do_raw_spin_lock+0x130/0x300
[ 2030.243358]  ? lock_is_held_type+0x7b/0x110
[ 2030.243388]  worker_thread+0x932/0xe20
[ 2030.243415]  kthread+0x38a/0x470
[ 2030.243431]  ? __pfx_worker_thread+0x10/0x10
[ 2030.243451]  ? __pfx_kthread+0x10/0x10
[ 2030.243467]  ret_from_fork+0x484/0x910
[ 2030.243485]  ? __pfx_ret_from_fork+0x10/0x10
[ 2030.243501]  ? __switch_to+0xc77/0x12c0
[ 2030.243523]  ? __pfx_kthread+0x10/0x10
[ 2030.243540]  ret_from_fork_asm+0x1a/0x30
[ 2030.243564]  </TASK>
[ 2030.243570]
[ 2030.290164] Allocated by task 19279:
[ 2030.290911]  kasan_save_track+0x3e/0x80
[ 2030.292179]  __kasan_kmalloc+0x72/0x90
[ 2030.293217]  __kvmalloc_node_noprof+0x3ff/0x6b0
[ 2030.294467]  handle_generic_event+0x59b/0x750
[ 2030.295345]  genl_family_rcv_msg_doit+0x238/0x340
[ 2030.296553]  genl_rcv_msg+0x606/0x7b0
[ 2030.297129]  netlink_rcv_skb+0x22b/0x4a0
[ 2030.298500]  genl_rcv+0x2d/0x40
[ 2030.299273]  netlink_unicast+0x7ba/0x930
[ 2030.300019]  netlink_sendmsg+0x8c3/0xb00
[ 2030.301073]  __sock_sendmsg+0xec/0x140
[ 2030.301579]  __sys_sendto+0x357/0x470
[ 2030.302255]  __x64_sys_sendto+0xe3/0x100
[ 2030.303425]  do_syscall_64+0x135/0x460
[ 2030.304763]  entry_SYSCALL_64_after_hwframe+0x77/0x7f
[ 2030.305594]
[ 2030.305819] The buggy address belongs to the object at ffff888121bb6640
[ 2030.305819]  which belongs to the cache kmalloc-192 of size 192
[ 2030.309595] The buggy address is located 64 bytes inside of
[ 2030.309595]  allocated 166-byte region [ffff888121bb6640, ffff888121bb66e6)
[ 2030.312484]
[ 2030.312719] The buggy address belongs to the physical page:
[ 2030.314315] page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x121bb6
[ 2030.316481] head: order:1 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
[ 2030.318248] flags: 0x100000000000040(head|node=0|zone=2)
[ 2030.319662] page_type: f5(slab)
[ 2030.320242] raw: 0100000000000040 ffff8881000424c0 ffffea00047c1510 ffff888100040468
[ 2030.321911] raw: 0000000000000000 0000000000150015 00000000f5000000 0000000000000000
[ 2030.324413] head: 0100000000000040 ffff8881000424c0 ffffea00047c1510 ffff888100040468
[ 2030.326150] head: 0000000000000000 0000000000150015 00000000f5000000 0000000000000000
[ 2030.327960] head: 0100000000000001 ffffffffffffff81 00000000ffffffff 00000000ffffffff
[ 2030.329615] head: ffff888121bb7ab0 0000000000000000 00000000ffffffff 0000000000000000
[ 2030.331861] page dumped because: kasan: bad access detected
[ 2030.332946]
[ 2030.333502] Memory state around the buggy address:
[ 2030.334698]  ffff888121bb6580: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 2030.336475]  ffff888121bb6600: fc fc fc fc fc fc fc fc 00 00 00 00 00 00 00 00
[ 2030.338143] >ffff888121bb6680: 00 00 00 00 00 00 00 00 00 00 00 00 06 fc fc fc
[ 2030.339116]                                                        ^
[ 2030.341315]  ffff888121bb6700: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 2030.342801]  ffff888121bb6780: fc fc fc fc fc fc fc fc fa fb fb fb fb fb fb fb
[ 2030.344643] ==================================================================

Found with ksmbdzzer [2], a KSMBD fuzzer that drives libFuzzer with a kcov-dataflow [1] coverage vector: it folds each instrumented comparison/argument's runtime operand value together with its PC (the default arm mixes them as pc⊕val) so that a new operand value at a known site counts as new coverage.

[1] https://lwn.net/Articles/1077606/
[2] https://github.com/yskzalloc/kcov-dataflow

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/mgmt/user_config.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
fs/smb/server/mgmt/user_config.c +11 -0
index 03184a3303b9f..0be08cf1896c4 100644
@@ -37,6 +37,17 @@ struct ksmbd_user *ksmbd_alloc_user(struct ksmbd_login_response *resp,
 {
 	struct ksmbd_user *user;
 
+	/*
+	 * resp->hash_sz is a __u16 taken from the mountd IPC login response but
+	 * resp->hash[] is only KSMBD_REQ_MAX_HASH_SZ bytes.  A malformed or
+	 * malicious response can set hash_sz far beyond that (up to 65535),
+	 * making the memcpy() below read past the response object
+	 * (slab-out-of-bounds in ksmbd_alloc_user()).  Reject any oversized
+	 * hash rather than trust the length.
+	 */
+	if (resp->hash_sz > sizeof(resp->hash))
+		return NULL;
+
 	user = kmalloc_obj(struct ksmbd_user, KSMBD_DEFAULT_GFP);
 	if (!user)
 		return NULL;
Signature · 1 line
2.53.0
author maintainer
#1517 lore raw

PATCH 1501/1815 smb: smbdirect: free completion queues with ib_free_cq()

In reply to Greg Kroah-Hartman

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

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

From: Yunseong Kim <[email protected]>

[ Upstream commit fe2c0cacbcff9d56c03b296f68f22151c4223b04 ]

smbdirect_connection_destroy_qp() creates the send and receive completion queues with ib_alloc_cq_any(), which for IB_POLL_WORKQUEUE arms an internal completion handler that runs ib_cq_poll_work() on a workqueue. Tearing those CQs down with ib_destroy_cq() frees them without first cancelling that poll work.

If the provider posts a completion late -- for example Soft-RoCE (rxe) posting an RNR error from rxe_receiver() after rdma_destroy_qp() -- the handler re-queues ib_cq_poll_work() on the already-freed CQ, and a follow-on access faults in rxe_req_notify_cq().

Use ib_free_cq(), which cancel_work_sync()es the poll work before freeing the CQ, so no completion handler can run against a freed queue.

[ 1236.599526] ==================================================================
[ 1236.602142] BUG: KASAN: slab-use-after-free in ib_cq_poll_work+0xd0/0x1a0
[ 1236.605524] Read of size 8 at addr ffff888111865800 by task kworker/4:1H/82
[ 1236.609017]
[ 1236.609270] CPU: 4 UID: 0 PID: 82 Comm: kworker/4:1H Not tainted 7.2.0-rc3-next-20260717-virtme #110 PREEMPT(lazy)
[ 1236.609287] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014
[ 1236.609498] Workqueue: ib-comp-wq ib_cq_poll_work
[ 1236.609525] Call Trace:
[ 1236.609536]  <TASK>
[ 1236.609545]  __dump_stack+0x21/0x60
[ 1236.609562]  dump_stack_lvl+0xc2/0x100
[ 1236.609573]  print_address_description+0x77/0x200
[ 1236.609587]  ? ib_cq_poll_work+0xd0/0x1a0
[ 1236.609597]  print_report+0x58/0x70
[ 1236.609607]  kasan_report+0x117/0x150
[ 1236.609623]  ? ib_cq_poll_work+0xd0/0x1a0
[ 1236.609636]  ? process_scheduled_works+0x954/0x1600
[ 1236.609650]  ib_cq_poll_work+0xd0/0x1a0
[ 1236.609662]  ? process_scheduled_works+0x954/0x1600
[ 1236.609674]  process_scheduled_works+0xc22/0x1600
[ 1236.609698]  ? __pfx_process_scheduled_works+0x10/0x10
[ 1236.609713]  ? __pfx_assign_work+0x10/0x10
[ 1236.609726]  ? lock_is_held_type+0x7b/0x110
[ 1236.609741]  worker_thread+0x975/0xee0
[ 1236.609757]  ? __pfx_do_raw_spin_lock+0x10/0x10
[ 1236.609775]  ? __kthread_parkme+0x21e/0x260
[ 1236.609789]  kthread+0x3a6/0x490
[ 1236.609800]  ? __pfx_worker_thread+0x10/0x10
[ 1236.609809]  ? __pfx_kthread+0x10/0x10
[ 1236.609820]  ret_from_fork+0x55a/0xa20
[ 1236.609835]  ? __pfx_ret_from_fork+0x10/0x10
[ 1236.609850]  ? __pfx_kthread+0x10/0x10
[ 1236.609861]  ret_from_fork_asm+0x1a/0x30
[ 1236.609880]  </TASK>
[ 1236.609886]
[ 1236.661292] Allocated by task 5076:
[ 1236.662640]  kasan_save_track+0x3e/0x80
[ 1236.663842]  __kasan_kmalloc+0x72/0x90
[ 1236.664763]  __kmalloc_noprof+0x2b0/0x5d0
[ 1236.665356]  __ib_alloc_cq+0x284/0x1000
[ 1236.666573]  __ib_alloc_cq_any+0x23e/0x340
[ 1236.668654]  smbdirect_connection_create_qp+0x6f7/0x1070
[ 1236.669757]  smbdirect_accept_connect_request+0x500/0x1ca0
[ 1236.672625]  smbdirect_listen_rdma_event_handler+0x1655/0x1c50
[ 1236.673930]  cma_listen_handler+0x1bf/0x260
[ 1236.674923]  cma_cm_event_handler+0x128/0x380
[ 1236.676926]  cma_ib_req_handler+0x2d3d/0x4de0
[ 1236.678368]  cm_process_work+0xb0/0x530
[ 1236.680454]  cm_queue_work_unlock+0xb1/0x230
[ 1236.681673]  cm_work_handler+0x969f/0xdca0
[ 1236.682704]  process_scheduled_works+0xc22/0x1600
[ 1236.683447]  worker_thread+0x975/0xee0
[ 1236.685901]  kthread+0x3a6/0x490
[ 1236.688164]  ret_from_fork+0x55a/0xa20
[ 1236.689522]  ret_from_fork_asm+0x1a/0x30
[ 1236.690073]
[ 1236.690378] Freed by task 5137:
[ 1236.692242]  kasan_save_track+0x3e/0x80
[ 1236.694272]  kasan_save_free_info+0x40/0x50
[ 1236.695514]  __kasan_slab_free+0x3a/0x60
[ 1236.696773]  kfree+0x14e/0x4e0
[ 1236.697216]  ib_destroy_cq_user+0x18d/0x250
[ 1236.699817]  smbdirect_connection_destroy_qp+0xf2/0x280
[ 1236.702115]  smbdirect_socket_destroy_sync+0x1607/0x2720
[ 1236.704062]  smbdirect_socket_release+0x140/0x280
[ 1236.705286]  smb_direct_free_transport+0x3b/0x90
[ 1236.707241]  __ksmbd_conn_release_work+0x99/0xf0
[ 1236.709287]  process_scheduled_works+0xc22/0x1600
[ 1236.710763]  worker_thread+0x975/0xee0
[ 1236.711262]  kthread+0x3a6/0x490
[ 1236.711720]  ret_from_fork+0x55a/0xa20
[ 1236.712232]  ret_from_fork_asm+0x1a/0x30
[ 1236.712762]
[ 1236.712992] Last potentially related work creation:
[ 1236.715157]  kasan_save_stack+0x3e/0x60
[ 1236.716993]  kasan_record_aux_stack+0x99/0xb0
[ 1236.718864]  insert_work+0xb2/0x4a0
[ 1236.720916]  __queue_work+0xebb/0x1260
[ 1236.722397]  queue_work_on+0x23b/0x350
[ 1236.723809]  ib_cq_completion_workqueue+0xac/0x160
[ 1236.724895]  rxe_cq_post+0x433/0x7c0
[ 1236.726273]  rxe_receiver+0xa41/0xd0d0
[ 1236.727754]  do_work+0x272/0x860
[ 1236.728896]  process_scheduled_works+0xc22/0x1600
[ 1236.730026]  worker_thread+0x975/0xee0
[ 1236.731499]  kthread+0x3a6/0x490
[ 1236.732132]  ret_from_fork+0x55a/0xa20
[ 1236.733171]  ret_from_fork_asm+0x1a/0x30
[ 1236.734224]
[ 1236.734871] Second to last potentially related work creation:
[ 1236.736001]  kasan_save_stack+0x3e/0x60
[ 1236.737161]  kasan_record_aux_stack+0x99/0xb0
[ 1236.739074]  insert_work+0xb2/0x4a0
[ 1236.740414]  __queue_work+0xebb/0x1260
[ 1236.740932]  queue_work_on+0x23b/0x350
[ 1236.741849]  ib_cq_completion_workqueue+0xac/0x160
[ 1236.744099]  rxe_cq_post+0x433/0x7c0
[ 1236.745514]  rxe_receiver+0xa41/0xd0d0
[ 1236.746091]  do_work+0x272/0x860
[ 1236.747187]  process_scheduled_works+0xc22/0x1600
[ 1236.749060]  worker_thread+0x975/0xee0
[ 1236.750224]  kthread+0x3a6/0x490
[ 1236.751480]  ret_from_fork+0x55a/0xa20
[ 1236.751989]  ret_from_fork_asm+0x1a/0x30
[ 1236.752974]
[ 1236.753627] The buggy address belongs to the object at ffff888111865800
[ 1236.753627]  which belongs to the cache kmalloc-1k of size 1024
[ 1236.757729] The buggy address is located 0 bytes inside of
[ 1236.757729]  freed 1024-byte region [ffff888111865800, ffff888111865c00)
[ 1236.760816]
[ 1236.761373] The buggy address belongs to the physical page:
[ 1236.762599] page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x111860
[ 1236.764306] head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
[ 1236.765281] flags: 0x100000000000040(head|node=0|zone=2)
[ 1236.765979] page_type: f5(slab)
[ 1236.766410] raw: 0100000000000040 ffff8881000430c0 ffffea0004a7e210 ffffea0004586210
[ 1236.770418] raw: 0000000000000000 00000000000a000a 00000000f5000000 0000000000000000
[ 1236.775899] head: 0100000000000040 ffff8881000430c0 ffffea0004a7e210 ffffea0004586210
[ 1236.782823] head: 0000000000000000 00000000000a000a 00000000f5000000 0000000000000000
[ 1236.786239] head: 0100000000000003 fffffffffffffe01 00000000ffffffff 00000000ffffffff
[ 1236.790658] head: 0000000000000000 0000000000000000 00000000ffffffff 0000000000000000
[ 1236.794132] page dumped because: kasan: bad access detected
[ 1236.798301]
[ 1236.799640] Memory state around the buggy address:
[ 1236.802028]  ffff888111865700: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 1236.806254]  ffff888111865780: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 1236.809036] >ffff888111865800: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 1236.813968]                    ^
[ 1236.816416]  ffff888111865880: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 1236.819454]  ffff888111865900: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 1236.823143] ==================================================================
[ 1236.830365] Disabling lock debugging due to kernel taint
[ 1236.831136] BUG: unable to handle page fault for address: ffffc90006dc8080
[ 1236.838157] #PF: supervisor read access in kernel mode
[ 1236.843686] #PF: error_code(0x0000) - not-present page
[ 1236.849393] PGD 100000067 P4D 100000067 PUD 100366067 PMD 12913e067 PTE 0
[ 1236.854156] Oops: Oops: 0000 [#1] SMP KASAN NOPTI
[ 1236.857893] CPU: 4 UID: 0 PID: 82 Comm: kworker/4:1H Tainted: G    B               7.2.0-rc3-next-20260717-virtme #110 PREEMPT(lazy)
[ 1236.860893] ksmbd: smb_direct: smbdirect_connection_recv_io_refill() failed -ECONNRESET
[ 1236.864209] Tainted: [B]=BAD_PAGE
[ 1236.864220] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014
[ 1236.864233] Workqueue: ib-comp-wq ib_cq_poll_work
[ 1236.878314] RIP: 0010:rxe_req_notify_cq+0x13a/0x350
[ 1236.881683] Code: 20 87 fd 4c 89 fe 48 ba 00 00 00 00 00 fc ff df 4c 8b 3e 49 83 ef 80 4c 89 f8 48 c1 e8 03 0f b6 04 10 84 c0 0f 85 9b 01 00 00 <45> 8b 2f 41 80 3c 16 00 74 18 49 89 f6 48 89 f7 e8 71 20 87 fd 4c
[ 1236.886819] ksmbd: smb_direct: smbdirect_connection_recv_io_refill() failed -ECONNRESET
[ 1236.890671] RSP: 0018:ffff88810222f920 EFLAGS: 00010046
[ 1236.890705] RAX: 0000000000000000 RBX: ffff88810222f920 RCX: ffffffff84c92863
[ 1236.901613] RDX: dffffc0000000000 RSI: ffff888120456d48 RDI: ffff888120456d48
[ 1236.903979] RBP: ffff88810222fa20 R08: 0000000000000003 R09: 0000000000000004
[ 1236.908958] R10: dffffc0000000000 R11: ffffed1020445f10 R12: ffff888120456d40
[ 1236.914473] R13: dffffc0000000000 R14: 1ffff1102408ada9 R15: ffffc90006dc8080
[ 1236.918946] FS:  0000000000000000(0000) GS:ffff88842600d000(0000) knlGS:0000000000000000
[ 1236.921600] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 1236.925779] CR2: ffffc90006dc8080 CR3: 000000012b35f003 CR4: 0000000000f72ef0
[ 1236.926809] ksmbd: smb_direct: smbdirect_connection_recv_io_refill() failed -ECONNRESET
[ 1236.928302] PKRU: 55555554
[ 1236.928328] Call Trace:
[ 1236.928338]  <TASK>
[ 1236.928352]  ? ib_cq_poll_work+0xd0/0x1a0
[ 1236.928374]  ? __pfx_rxe_req_notify_cq+0x10/0x10
[ 1236.941601]  ? ib_cq_poll_work+0xd0/0x1a0
[ 1236.943306]  ib_cq_poll_work+0xfe/0x1a0
[ 1236.943961]  ? process_scheduled_works+0x954/0x1600
[ 1236.947036]  process_scheduled_works+0xc22/0x1600
[ 1236.951626]  ? __pfx_process_scheduled_works+0x10/0x10
[ 1236.954316]  ? __pfx_assign_work+0x10/0x10
[ 1236.958110]  ? lock_is_held_type+0x7b/0x110
[ 1236.960042]  worker_thread+0x975/0xee0
[ 1236.962668]  ? __pfx_do_raw_spin_lock+0x10/0x10
[ 1236.965334]  ? __kthread_parkme+0x21e/0x260
[ 1236.966058]  kthread+0x3a6/0x490
[ 1236.968115]  ? __pfx_worker_thread+0x10/0x10
[ 1236.971020]  ? __pfx_kthread+0x10/0x10
[ 1236.974488]  ret_from_fork+0x55a/0xa20
[ 1236.977419]  ? __pfx_ret_from_fork+0x10/0x10
[ 1236.979846]  ? __pfx_kthread+0x10/0x10
[ 1236.981238]  ret_from_fork_asm+0x1a/0x30
[ 1236.984086]  </TASK>
[ 1236.986181] Modules linked in:
[ 1236.989048] CR2: ffffc90006dc8080
[ 1236.990412] ---[ end trace 0000000000000000 ]---
[ 1236.994119] RIP: 0010:rxe_req_notify_cq+0x13a/0x350
[ 1236.998482] Code: 20 87 fd 4c 89 fe 48 ba 00 00 00 00 00 fc ff df 4c 8b 3e 49 83 ef 80 4c 89 f8 48 c1 e8 03 0f b6 04 10 84 c0 0f 85 9b 01 00 00 <45> 8b 2f 41 80 3c 16 00 74 18 49 89 f6 48 89 f7 e8 71 20 87 fd 4c
[ 1237.006635] RSP: 0018:ffff88810222f920 EFLAGS: 00010046
[ 1237.008513] RAX: 0000000000000000 RBX: ffff88810222f920 RCX: ffffffff84c92863
[ 1237.014100] RDX: dffffc0000000000 RSI: ffff888120456d48 RDI: ffff888120456d48
[ 1237.021058] RBP: ffff88810222fa20 R08: 0000000000000003 R09: 0000000000000004
[ 1237.024939] R10: dffffc0000000000 R11: ffffed1020445f10 R12: ffff888120456d40
[ 1237.030203] R13: dffffc0000000000 R14: 1ffff1102408ada9 R15: ffffc90006dc8080
[ 1237.034299] FS:  0000000000000000(0000) GS:ffff88842600d000(0000) knlGS:0000000000000000
[ 1237.037311] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 1237.042838] CR2: ffffc90006dc8080 CR3: 000000012b35f003 CR4: 0000000000f72ef0

Found with ksmbdzzer [2], a KSMBD fuzzer that drives libFuzzer with a kcov-dataflow [1] coverage vector: it folds each instrumented comparison/argument's runtime operand value together with its PC (the default arm mixes them as pc⊕val) so that a new operand value at a known site counts as new coverage.

[1] https://lwn.net/Articles/1077606/
[2] https://github.com/yskzalloc/kcov-dataflow

Fixes 6073eb3e3175 ("smb: smbdirect: introduce smbdirect_connection_{create,destroy}_qp()")
---
 fs/smb/smbdirect/connection.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)
fs/smb/smbdirect/connection.c +11 -2
index 8adf580975344..fe99537207176 100644
@@ -403,12 +403,21 @@ void smbdirect_connection_destroy_qp(struct smbdirect_socket *sc)
 		sc->ib.qp = NULL;
 		rdma_destroy_qp(sc->rdma.cm_id);
 	}
+	/*
+	 * These CQs were created with ib_alloc_cq_any(), which arms an internal
+	 * completion handler (ib_cq_poll_work for IB_POLL_WORKQUEUE). They MUST be
+	 * torn down with ib_free_cq(), which cancel_work_sync()es that poll work
+	 * before freeing the CQ. ib_destroy_cq() skips that step, so a completion
+	 * posted late by the (software) provider — e.g. rxe posting an RNR error
+	 * from rxe_receiver after rdma_destroy_qp() — re-queues ib_cq_poll_work on
+	 * an already-freed CQ (KASAN slab-use-after-free in ib_cq_poll_work).
+	 */
 	if (sc->ib.recv_cq) {
-		ib_destroy_cq(sc->ib.recv_cq);
+		ib_free_cq(sc->ib.recv_cq);
 		sc->ib.recv_cq = NULL;
 	}
 	if (sc->ib.send_cq) {
-		ib_destroy_cq(sc->ib.send_cq);
+		ib_free_cq(sc->ib.send_cq);
 		sc->ib.send_cq = NULL;
 	}
 	if (sc->ib.pd) {
Signature · 1 line
2.53.0
author maintainer
#1518 lore raw

PATCH 1502/1815 smb: smbdirect: destroy QP before mem pools on accept failure

In reply to Greg Kroah-Hartman

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

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

From: Yunseong Kim <[email protected]>

[ Upstream commit 383a9480f5f40bc46454cce27ccfad532cedad9c ]

On the rdma_accept_failed error path of smbdirect_accept_connect_request(), the receive io posted just above is owned by the QP (recv_io is set to NULL after a successful post). The error path fell through to smbdirect_connection_destroy_mem_pools() before smbdirect_connection_destroy_qp(), so the mem pools and the recv_io slab cache were destroyed while that recv_io was still outstanding on the QP.

The drain in smbdirect_connection_destroy_qp() (ib_drain_qp()) is what runs the recv completion that returns the recv_io to the free list, so destroying the pools first leaves the object outstanding at kmem_cache_destroy() time ("Slab cache still has objects") and later frees it into an already-destroyed mempool (mempool_free_bulk NULL-pointer dereference).

Give rdma_accept_failed its own teardown that drains the QP first, then destroys the mem pools, and returns. The remaining labels (post_recv_io_failed onward) run before the recv_io was ever posted, so they keep the mem-pools-then-qp order.

The outstanding recv_io at kmem_cache_destroy() time:

[ 3487.344647] =============================================================================
[ 3487.349942] BUG smbdirect_recv_io_cache_ffff88811ba99000 (Not tainted): Objects remaining on __kmem_cache_shutdown()
[ 3487.356078] -----------------------------------------------------------------------------
[ 3487.356078]
[ 3487.356738] Object 0xffff8881511c3440 @offset=13376
[ 3487.358464] Allocated in mempool_alloc_noprof+0x18c/0x290 age=1194 cpu=6 pid=22254
[ 3487.361197]  mempool_alloc_noprof+0x18c/0x290
[ 3487.361542]  smbdirect_connection_create_mem_pools+0x405/0x780
[ 3487.361972]  smbdirect_accept_connect_request+0x5a8/0x1b80
[ 3487.362359]  smbdirect_listen_rdma_event_handler+0x1579/0x1b90
[ 3487.362779]  cma_cm_event_handler+0x9c/0x230
[ 3487.363096]  cma_ib_req_handler+0x2682/0x45d0
[ 3487.363414]  cm_process_work+0x56/0x3d0
[ 3487.363676]  cm_work_handler+0x8a0e/0xd000
[ 3487.367496]  process_scheduled_works+0xa07/0x13a0
[ 3487.367859]  worker_thread+0x7c9/0xc80
[ 3487.368148]  kthread+0x341/0x430
[ 3487.368407]  ret_from_fork+0x3a8/0x7a0
[ 3487.368704]  ret_from_fork_asm+0x1a/0x30
[ 3487.370307] Slab 0xffffea0005447000 objects=19 used=1 fp=0xffff8881511c0040 flags=0x100000000000240(workingset|head|node=0|zone=2)
[ 3487.372840] ------------[ cut here ]------------
[ 3487.373195] WARNING: mm/slub.c:1244 at __slab_err+0x1a/0x30, CPU#6: kworker/6:84/22254
[ 3487.373759] Modules linked in:
[ 3487.373993] CPU: 6 UID: 0 PID: 22254 Comm: kworker/6:84 Tainted: G    B               7.1.0-next-20260623+ #88 PREEMPT(lazy)
[ 3487.374778] Tainted: [B]=BAD_PAGE
[ 3487.377830] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014
[ 3487.378515] Workqueue: ib_cm cm_work_handler
[ 3487.378820] RIP: 0010:__slab_err+0x1a/0x30
[ 3487.379129] Code: 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 0f 1f 44 00 00 e8 36 00 00 00 bf 05 00 00 00 be 01 00 00 00 e8 f7 75 45 00 90 <0f> 0b 90 c3 cc cc cc cc cc 66 66 66 66 2e 0f 1f 84 00 00 00 00 00
[ 3487.383255] RSP: 0018:ffff888220fc7050 EFLAGS: 00010093
[ 3487.383643] RAX: ffffffff8168e60a RBX: ffff88810955e640 RCX: ffff88821c381d80
[ 3487.384158] RDX: 0000000000000000 RSI: 0000000000000008 RDI: ffffffff870fa080
[ 3487.384662] RBP: ffff888220fc7068 R08: ffffffff870fa087 R09: 1ffffffff0e1f410
[ 3487.385192] R10: dffffc0000000000 R11: fffffbfff0e1f411 R12: ffffea0005447210
[ 3487.385674] R13: ffffea0005447000 R14: ffff888220fc7068 R15: ffff88812a8ab300
[ 3487.388932] FS:  0000000000000000(0000) GS:ffff888427e76000(0000) knlGS:0000000000000000
[ 3487.389529] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 3487.389934] CR2: 00007ffcf2d84fd8 CR3: 0000000111d64006 CR4: 0000000000f72ef0
[ 3487.390440] PKRU: 55555554
[ 3487.390641] Call Trace:
[ 3487.390826]  <TASK>
[ 3487.391209]  __kmem_cache_shutdown+0x1aa/0x2b0
[ 3487.392062]  ? smbdirect_connection_destroy_mem_pools+0x239/0x300
[ 3487.393565]  kmem_cache_destroy+0x9d/0x180
[ 3487.398663]  smbdirect_connection_destroy_mem_pools+0x239/0x300
[ 3487.403534]  ? __pfx_smb_direct_logging_needed+0x10/0x10
[ 3487.407562]  smbdirect_accept_connect_request+0x95c/0x1b80
[ 3487.412391]  ? __pfx_smbdirect_accept_connect_request+0x10/0x10
[ 3487.416753]  ? do_raw_spin_lock+0x130/0x300
[ 3487.420623]  ? smbdirect_socket_set_initial_parameters+0x28b/0x6a0
[ 3487.424322]  ? lock_acquire+0x4c/0x270
[ 3487.424409] ksmbd: can't change a file to a directory
[ 3487.426321]  ? trace_irq_enable+0x36/0x120
[ 3487.429144]  smbdirect_listen_rdma_event_handler+0x1579/0x1b90
[ 3487.432606]  ? __pfx_smbdirect_listen_rdma_event_handler+0x10/0x10
[ 3487.433595]  ? trace_cm_event_handler+0x51/0x170
[ 3487.435183]  ? __pfx_smbdirect_listen_rdma_event_handler+0x10/0x10
[ 3487.435646]  ? cma_listen_handler+0xf6/0x150
[ 3487.435975]  cma_cm_event_handler+0x9c/0x230
[ 3487.436288]  cma_ib_req_handler+0x2682/0x45d0
[ 3487.439039]  ? __pfx_cma_ib_req_handler+0x10/0x10
[ 3487.439540]  ? __pfx_roce_resolve_route_from_path+0x10/0x10
[ 3487.439972]  ? stack_depot_save_flags+0x34/0x840
[ 3487.440374]  ? __xas_nomem+0xa9/0x410
[ 3487.443356]  ? xas_clear_mark+0x26c/0x4a0
[ 3487.443673]  cm_process_work+0x56/0x3d0
[ 3487.443969]  ? _raw_spin_unlock_irq+0x28/0x50
[ 3487.444317]  cm_work_handler+0x8a0e/0xd000
[ 3487.444624]  ? __pfx_cm_work_handler+0x10/0x10
[ 3487.444971]  ? pwq_dec_nr_in_flight+0xa73/0xdf0
[ 3487.445344]  ? __pfx_pwq_dec_nr_in_flight+0x10/0x10
[ 3487.445737]  ? lock_acquire+0x4c/0x270
[ 3487.448833]  ? process_scheduled_works+0x995/0x13a0
[ 3487.449230]  ? process_scheduled_works+0x995/0x13a0
[ 3487.449588]  process_scheduled_works+0xa07/0x13a0
[ 3487.449938]  ? __pfx_process_scheduled_works+0x10/0x10
[ 3487.450334]  ? do_raw_spin_lock+0x130/0x300
[ 3487.450639]  ? assign_work+0x3bb/0x5c0
[ 3487.450916]  worker_thread+0x7c9/0xc80
[ 3487.451211]  kthread+0x341/0x430
[ 3487.451453]  ? __pfx_worker_thread+0x10/0x10
[ 3487.451756]  ? __pfx_kthread+0x10/0x10
[ 3487.454814]  ret_from_fork+0x3a8/0x7a0
[ 3487.455114]  ? __pfx_ret_from_fork+0x10/0x10
[ 3487.455450]  ? __switch_to+0xb76/0x1110
[ 3487.455772]  ? __pfx_kthread+0x10/0x10
[ 3487.456081]  ret_from_fork_asm+0x1a/0x30
[ 3487.456384]  </TASK>
[ 3487.456549] irq event stamp: 0
[ 3487.456767] hardirqs last  enabled at (0): [<0000000000000000>] 0x0
[ 3487.460124] hardirqs last disabled at (0): [<ffffffff81684648>] copy_process+0xa08/0x3a10
[ 3487.460726] softirqs last  enabled at (0): [<ffffffff81684648>] copy_process+0xa08/0x3a10
[ 3487.461328] softirqs last disabled at (0): [<0000000000000000>] 0x0
[ 3487.461778] ---[ end trace 0000000000000000 ]---
[ 3487.543875] ksmbd: can't change a file to a directory
[ 3487.599675] ksmbd: can't change a file to a directory
[ 3487.626694] ksmbd: can't change a file to a directory
[ 3487.824687] ksmbd: can't change a file to a directory
[ 3487.871840] ksmbd: can't change a file to a directory
[ 3487.986207] ------------[ cut here ]------------
[ 3487.987157] kmem_cache_destroy smbdirect_recv_io_cache_ffff88811ba99000: Slab cache still has objects when called from smbdirect_connection_destroy_mem_pools+0x239/0x300
[ 3487.987183] WARNING: mm/slab_common.c:572 at kmem_cache_destroy+0x15c/0x180, CPU#6: kworker/6:84/22254
[ 3487.999821] Modules linked in:
[ 3488.001902] CPU: 6 UID: 0 PID: 22254 Comm: kworker/6:84 Tainted: G    B   W           7.1.0-next-20260623+ #88 PREEMPT(lazy)
[ 3488.008289] Tainted: [B]=BAD_PAGE, [W]=WARN
[ 3488.010459] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014
[ 3488.014502] Workqueue: ib_cm cm_work_handler
[ 3488.017790] RIP: 0010:kmem_cache_destroy+0x16a/0x180
[ 3488.020662] Code: fd ff 48 8b 3d 2f c0 9c 06 48 89 de 5b 41 5e 5d e9 5b a3 0e 00 48 8d 3d a4 07 12 04 48 8b 53 58 48 c7 c6 91 9d 3e 85 4c 89 f1 <67> 48 0f b9 3a e9 33 ff ff ff 66 66 66 2e 0f 1f 84 00 00 00 00 00
[ 3488.028077] RSP: 0018:ffff888220fc70b8 EFLAGS: 00010202
[ 3488.032038] RAX: 0000000000000001 RBX: ffff88810955e640 RCX: ffffffff822bc079
[ 3488.035742] RDX: ffff88812404ec40 RSI: ffffffff853e9d91 RDI: ffffffff85f7ac50
[ 3488.037830] RBP: 0000000000000001 R08: ffff8883aef3e843 R09: 1ffff11075de7d08
[ 3488.041076] R10: dffffc0000000000 R11: ffffed1075de7d09 R12: 1ffff11024fa6c3c
[ 3488.045376] R13: ffff888127d361e8 R14: ffffffff822bc079 R15: ffff88811ba99538
[ 3488.049073] FS:  0000000000000000(0000) GS:ffff888427e76000(0000) knlGS:0000000000000000
[ 3488.052515] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 3488.054934] CR2: 00007ffcf2d84fd8 CR3: 0000000111d64006 CR4: 0000000000f72ef0
[ 3488.058529] PKRU: 55555554
[ 3488.060542] Call Trace:
[ 3488.061595]  <TASK>
[ 3488.062006]  smbdirect_connection_destroy_mem_pools+0x239/0x300
[ 3488.066041]  ? __pfx_smb_direct_logging_needed+0x10/0x10
[ 3488.068620]  smbdirect_accept_connect_request+0x95c/0x1b80
[ 3488.071594]  ? __pfx_smbdirect_accept_connect_request+0x10/0x10
[ 3488.073218] ksmbd: not allow base filename in rename
[ 3488.074751]  ? do_raw_spin_lock+0x130/0x300
[ 3488.076792] ksmbd: can't change a file to a directory
[ 3488.077942]  ? smbdirect_socket_set_initial_parameters+0x28b/0x6a0
[ 3488.080143]  ? lock_acquire+0x4c/0x270
[ 3488.080747]  ? trace_irq_enable+0x36/0x120
[ 3488.081400]  smbdirect_listen_rdma_event_handler+0x1579/0x1b90
[ 3488.085089]  ? __pfx_smbdirect_listen_rdma_event_handler+0x10/0x10
[ 3488.089333]  ? trace_cm_event_handler+0x51/0x170
[ 3488.092637]  ? __pfx_smbdirect_listen_rdma_event_handler+0x10/0x10
[ 3488.095741]  ? cma_listen_handler+0xf6/0x150
[ 3488.099638]  cma_cm_event_handler+0x9c/0x230
[ 3488.101552]  cma_ib_req_handler+0x2682/0x45d0
[ 3488.104571]  ? __pfx_cma_ib_req_handler+0x10/0x10
[ 3488.106790]  ? __pfx_roce_resolve_route_from_path+0x10/0x10
[ 3488.109799]  ? stack_depot_save_flags+0x34/0x840
[ 3488.112174]  ? __xas_nomem+0xa9/0x410
[ 3488.114217]  ? xas_clear_mark+0x26c/0x4a0
[ 3488.116854]  cm_process_work+0x56/0x3d0
[ 3488.118179]  ? _raw_spin_unlock_irq+0x28/0x50
[ 3488.120034]  cm_work_handler+0x8a0e/0xd000
[ 3488.121677]  ? __pfx_cm_work_handler+0x10/0x10
[ 3488.123682]  ? pwq_dec_nr_in_flight+0xa73/0xdf0
[ 3488.126928]  ? __pfx_pwq_dec_nr_in_flight+0x10/0x10
[ 3488.129390]  ? lock_acquire+0x4c/0x270
[ 3488.131432]  ? process_scheduled_works+0x995/0x13a0
[ 3488.132694] ksmbd: can't change a file to a directory
[ 3488.136702]  ? process_scheduled_works+0x995/0x13a0
[ 3488.140060]  process_scheduled_works+0xa07/0x13a0
[ 3488.143379]  ? __pfx_process_scheduled_works+0x10/0x10
[ 3488.147221]  ? do_raw_spin_lock+0x130/0x300
[ 3488.150790]  ? assign_work+0x3bb/0x5c0
[ 3488.154259]  worker_thread+0x7c9/0xc80
[ 3488.155730]  kthread+0x341/0x430
[ 3488.158309]  ? __pfx_worker_thread+0x10/0x10
[ 3488.160865]  ? __pfx_kthread+0x10/0x10
[ 3488.164384]  ret_from_fork+0x3a8/0x7a0
[ 3488.167020]  ? __pfx_ret_from_fork+0x10/0x10
[ 3488.170050]  ? __switch_to+0xb76/0x1110
[ 3488.171809]  ? __pfx_kthread+0x10/0x10
[ 3488.174955]  ret_from_fork_asm+0x1a/0x30
[ 3488.175605]  </TASK>
[ 3488.176206] irq event stamp: 0
[ 3488.179360] hardirqs last  enabled at (0): [<0000000000000000>] 0x0
[ 3488.186521] hardirqs last disabled at (0): [<ffffffff81684648>] copy_process+0xa08/0x3a10
[ 3488.191889] softirqs last  enabled at (0): [<ffffffff81684648>] copy_process+0xa08/0x3a10
[ 3488.196853] softirqs last disabled at (0): [<0000000000000000>] 0x0
[ 3488.200870] ---[ end trace 0000000000000000 ]---

Found with ksmbdzzer [2], a KSMBD fuzzer that drives libFuzzer with a kcov-dataflow [1] coverage vector: it folds each instrumented comparison/argument's runtime operand value together with its PC (the default arm mixes them as pc⊕val) so that a new operand value at a known site counts as new coverage.

[1] https://lwn.net/Articles/1077606/
[2] https://github.com/yskzalloc/kcov-dataflow

Fixes eb3ed1e9048c ("smb: smbdirect: introduce smbdirect_accept_connect_request()")
---
 fs/smb/smbdirect/accept.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
fs/smb/smbdirect/accept.c +13 -3
index 5297400058385..039c9bfbd8acd 100644
@@ -145,11 +145,21 @@ int smbdirect_accept_connect_request(struct smbdirect_socket *sc,
 
 rdma_accept_failed:
 	/*
-	 * smbdirect_connection_destroy_qp() calls ib_drain_qp(),
-	 * so that smbdirect_accept_negotiate_recv_done() will
-	 * call smbdirect_connection_put_recv_io()
+	 * The recv_io posted above is now owned by the QP (recv_io was set to
+	 * NULL after a successful post).  smbdirect_connection_destroy_qp()
+	 * calls ib_drain_qp(), whose completion
+	 * (smbdirect_accept_negotiate_recv_done) returns the recv_io to the
+	 * free list via smbdirect_connection_put_recv_io().  It therefore MUST
+	 * run BEFORE smbdirect_connection_destroy_mem_pools(): otherwise the
+	 * posted recv_io is still outstanding when kmem_cache_destroy() runs
+	 * ("Slab cache still has objects") and is later freed into an
+	 * already-destroyed mempool (mempool_free_bulk NULL-ptr-deref).
 	 */
+	smbdirect_connection_destroy_qp(sc);
+	smbdirect_connection_destroy_mem_pools(sc);
+	return ret;
 post_recv_io_failed:
+	/* post failed: recv_io was not accepted by the QP, still in hand */
 	if (recv_io)
 		smbdirect_connection_put_recv_io(recv_io);
 get_recv_io_failed:
Signature · 1 line
2.53.0
author maintainer
#1519 lore raw

PATCH 1503/1815 smb: smbdirect: avoid recursive listen.lock during cleanup

In reply to Greg Kroah-Hartman

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

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

From: Yunseong Kim <[email protected]>

[ Upstream commit 76fa42c004eb95a983bed8fd0e6e0e8428c751a5 ]

__smbdirect_socket_schedule_cleanup() and smbdirect_socket_cleanup_work() take sc->listen.lock and walk the listener's pending list, recursing into smbdirect_socket_schedule_cleanup() for each child, and every child takes its own listen.lock inside that walk.

This cannot deadlock for real: the nesting is strictly listener into child, a child never listens, so the outer and the inner lock are always different instances. lockdep only tracks lock classes, though; it sees the same class acquired twice and reports a possible recursive locking deadlock. This change therefore works around a lockdep limitation rather than fixing a real hang, but the report is still worth avoiding: lockdep disables itself after the first splat and then hides real locking bugs for the rest of the run.

Only a socket that was a listener owns a populated listen.ready/pending list; a child has empty lists and nothing to do in these blocks. Guard both of them with sc->listen.backlog != -1, the "was a listener" marker that smbdirect_socket_destroy() already uses: listen.backlog leaves its initial -1 exactly once, when smbdirect_socket_listen() succeeds. The alternative !sc->accept.listener test reads as "not a listener" while meaning the opposite, and it is also true for an accepted child, whose accept.listener has been cleared on hand-over. With the guard the walk only runs for a listener and never nests a child's listen.lock under it; a pending child stays on its listener's list for the free path (smbdirect_socket_destroy) to reap.

[  741.705044] WARNING: possible recursive locking detected
[  741.705403] 7.1.0-next-20260623+ #75 Not tainted
[  741.705695] --------------------------------------------
[  741.706022] ksmbd.control/18502 is trying to acquire lock:
[  741.706379] ffff888108d612f8 (&sc->listen.lock){....}-{3:3}, at: __smbdirect_socket_schedule_cleanup+0x719/0xd70
[  741.707008]
[  741.707008] but task is already holding lock:
[  741.707396] ffff8881087642f8 (&sc->listen.lock){....}-{3:3}, at: __smbdirect_socket_schedule_cleanup+0x719/0xd70
[  741.708025]
[  741.708025] other info that might help us debug this:
[  741.708448]  Possible unsafe locking scenario:
[  741.708448]
[  741.708845]        CPU0
[  741.709016]        ----
[  741.709186]   lock(&sc->listen.lock);
[  741.709453]   lock(&sc->listen.lock);
[  741.709705]
[  741.709705]  *** DEADLOCK ***
[  741.709705]
[  741.710095]  May be due to missing lock nesting notation
[  741.710095]
[  741.710663] 6 locks held by ksmbd.control/18502:
[  741.710975]  #0: ffff888109e51420 (sb_writers#7){.+.+}-{0:0}, at: vfs_write+0x1e7/0xc70
[  741.711561]  #1: ffff888126ec3880 (&of->mutex){+.+.}-{4:4}, at: kernfs_fop_write_iter+0x1be/0x4d0
[  741.712147]  #2: ffff888102af17b0 (kn->active#45){.+.+}-{0:0}, at: kernfs_fop_write_iter+0x205/0x4d0
[  741.712803]  #3: ffffffff85ad1e00 (ctrl_lock){+.+.}-{4:4}, at: kill_server_store+0x1e0/0x2b0
[  741.713381]  #4: ffffffff85ad41a0 (init_lock){+.+.}-{4:4}, at: ksmbd_conn_transport_destroy+0x5b/0x3c0
[  741.713995]  #5: ffff8881087642f8 (&sc->listen.lock){....}-{3:3}, at: __smbdirect_socket_schedule_cleanup+0x719/0xd70
[  741.714736]
[  741.714736] stack backtrace:
[  741.715038] CPU: 4 UID: 0 PID: 18502 Comm: ksmbd.control Not tainted 7.1.0-next-20260623+ #75 PREEMPT(lazy)
[  741.715043] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014
[  741.715046] Call Trace:
[  741.715049]  <TASK>
[  741.715052]  dump_stack_lvl+0x77/0xa0
[  741.715058]  print_deadlock_bug+0x279/0x290
[  741.715065]  __lock_acquire+0x272a/0x2e30
[  741.715070]  ? stack_trace_save+0xae/0x100
[  741.715075]  ? smb_direct_logging_vaprintf+0x1a0/0x230
[  741.715079]  ? __pfx_smb_direct_logging_vaprintf+0x10/0x10
[  741.715082]  ? __timer_delete+0x58/0x320
[  741.715087]  lock_acquire+0xd3/0x270
[  741.715091]  ? __smbdirect_socket_schedule_cleanup+0x719/0xd70
[  741.715095]  ? entry_SYSCALL_64_after_hwframe+0x77/0x7f
[  741.715099]  _raw_spin_lock_irqsave+0x42/0x60
[  741.715105]  ? __smbdirect_socket_schedule_cleanup+0x719/0xd70

Note the two addresses above: ffff888108d612f8 is the child's lock, ffff8881087642f8 the listener's, always distinct objects.

Found with ksmbdzzer [2], a KSMBD fuzzer that drives libFuzzer with a kcov-dataflow [1] coverage vector: it folds each instrumented comparison/argument's runtime operand value together with its PC (the default arm mixes them as pc⊕val) so that a new operand value at a known site counts as new coverage.

[1] https://lwn.net/Articles/1077606/
[2] https://github.com/yskzalloc/kcov-dataflow

Fixes dc691b91ad16 ("smb: smbdirect: introduce smbdirect_socket_{listen,accept}()")
---
 fs/smb/smbdirect/socket.c | 42 +++++++++++++++++++++++++++++----------
 1 file changed, 32 insertions(+), 10 deletions(-)
fs/smb/smbdirect/socket.c +32 -10
index 39cca7219c4df..8dec47a6603cb 100644
@@ -305,12 +305,26 @@ void __smbdirect_socket_schedule_cleanup(struct smbdirect_socket *sc,
 	 * disconnect all pending and ready sockets
 	 *
 	 * First we move ready sockets to pending again.
+	 *
+	 * Only a socket that was a listener (listen.backlog != -1) owns a
+	 * populated listen.ready/pending list.  Guarding on that also keeps
+	 * lockdep quiet: without it, the listener holds sc->listen.lock while
+	 * the loop recurses into each child psc, which takes psc->listen.lock.
+	 * Those are always different instances of the same lock class -- a
+	 * child never listens, so the nesting is strictly listener -> child
+	 * and cannot really deadlock -- but lockdep only sees the class and
+	 * reports "possible recursive locking".  A child has empty listen
+	 * lists and nothing to do here, so skipping it loses nothing, and a
+	 * pending child stays on its listener's list for the free path
+	 * (smbdirect_socket_destroy) to reap.
 	 */
-	spin_lock_irqsave(&sc->listen.lock, flags);
-	list_splice_init(&sc->listen.ready, &sc->listen.pending);
-	list_for_each_entry_safe(psc, tsc, &sc->listen.pending, accept.list)
-		smbdirect_socket_schedule_cleanup(psc, sc->first_error);
-	spin_unlock_irqrestore(&sc->listen.lock, flags);
+	if (sc->listen.backlog != -1) { /* was a listener */
+		spin_lock_irqsave(&sc->listen.lock, flags);
+		list_splice_init(&sc->listen.ready, &sc->listen.pending);
+		list_for_each_entry_safe(psc, tsc, &sc->listen.pending, accept.list)
+			smbdirect_socket_schedule_cleanup(psc, sc->first_error);
+		spin_unlock_irqrestore(&sc->listen.lock, flags);
+	}
 
 	switch (sc->status) {
 	case SMBDIRECT_SOCKET_RESOLVE_ADDR_FAILED:
@@ -405,12 +419,20 @@ static void smbdirect_socket_cleanup_work(struct work_struct *work)
 	 * disconnect all pending and ready sockets
 	 *
 	 * First we move ready sockets to pending again.
+	 *
+	 * Guarded on listen.backlog != -1 for the same reason as in
+	 * __smbdirect_socket_schedule_cleanup(): only a listener owns a
+	 * populated listen list, and skipping the block for a child avoids
+	 * nesting psc->listen.lock under a listener's listen.lock (different
+	 * instances of one class -- harmless, but lockdep cannot tell).
 	 */
-	spin_lock_irqsave(&sc->listen.lock, flags);
-	list_splice_init(&sc->listen.ready, &sc->listen.pending);
-	list_for_each_entry_safe(psc, tsc, &sc->listen.pending, accept.list)
-		smbdirect_socket_schedule_cleanup(psc, sc->first_error);
-	spin_unlock_irqrestore(&sc->listen.lock, flags);
+	if (sc->listen.backlog != -1) { /* was a listener */
+		spin_lock_irqsave(&sc->listen.lock, flags);
+		list_splice_init(&sc->listen.ready, &sc->listen.pending);
+		list_for_each_entry_safe(psc, tsc, &sc->listen.pending, accept.list)
+			smbdirect_socket_schedule_cleanup(psc, sc->first_error);
+		spin_unlock_irqrestore(&sc->listen.lock, flags);
+	}
 
 	switch (sc->status) {
 	case SMBDIRECT_SOCKET_NEGOTIATE_NEEDED:
Signature · 1 line
2.53.0
author maintainer
#1520 lore raw

PATCH 1504/1815 smb: smbdirect: release pending child sockets outside the handler lock

In reply to Greg Kroah-Hartman

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

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

From: Yunseong Kim <[email protected]>

[ Upstream commit db82fbe4bb68e68e4aef00ef5b79f92991d8ef8e ]

smbdirect_socket_destroy() releases the listener's pending/ready child sockets while still holding the listener's handler lock, the &id_priv->handler_mutex taken via rdma_lock_handler(), not sc->listen.lock, and before the listener's own rdma_destroy_id(). That ordering has one real consequence and one cosmetic one.

The real one: smbdirect_socket_release() drops the child's last reference, which destroys the child's cm_id. Doing that before the listener's rdma_destroy_id() lets _cma_cancel_listens(), running from the listener's _destroy_id(), walk an already freed child id_priv, which KASAN catches as a slab-use-after-free during listener shutdown:

[ 4758.909130] BUG: KASAN: slab-use-after-free in __mutex_lock+0x1469/0x1560
[ 4758.911450] Read of size 1 at addr ffff88821c381db4 by task ksmbd.control/1652
[ 4758.913262] Call Trace:
[ 4758.913267]  <TASK>
[ 4758.913299]  __mutex_lock+0x1469/0x1560
[ 4758.913408]  _cma_cancel_listens+0x312/0x3b0
[ 4758.913413]  _destroy_id+0x363/0xee0
[ 4758.913417]  smbdirect_socket_destroy_sync+0x17d5/0x2440
[ 4758.913443]  smbdirect_socket_release+0x124/0x230
[ 4758.913451]  ksmbd_rdma_stop_listening+0x9f/0x190
[ 4758.913457]  ksmbd_conn_transport_destroy+0x65/0x3c0
[ 4758.913463]  kill_server_store+0x1fb/0x2b0
[ 4758.913501]  kernfs_fop_write_iter+0x349/0x4d0
[ 4758.913507]  vfs_write+0x5e7/0xc70
[ 4758.913528]  ksys_write+0x12a/0x210
[ 4758.913541]  do_syscall_64+0x135/0x460
[ 4758.913555]  entry_SYSCALL_64_after_hwframe+0x77/0x7f

The cosmetic one: releasing a child recurses into smbdirect_socket_destroy(), which takes the child's own rdma_lock_handler() lock nested under the listener's. The listener's and the child's cm_id are always different instances, so this cannot deadlock for real; the CM core itself nests a new connection id's handler_mutex under the listening id's in cma_ib_req_handler(). But lockdep only sees one lock class, reports possible recursive locking, and then disables itself, hiding real locking bugs for the rest of the run:

[ 2424.579653] WARNING: possible recursive locking detected
[ 2424.581180] 7.1.0-next-20260623+ #89 Not tainted
[ 2424.582548] --------------------------------------------
[ 2424.584500] ksmbd.control/8854 is trying to acquire lock:
[ 2424.586817] ffff888102303c20 (&id_priv->handler_mutex){+.+.}-{4:4}, at: smbdirect_socket_destroy_sync+0xc39/0x2440
[ 2424.590590]
[ 2424.590590] but task is already holding lock:
[ 2424.591601] ffff888102046c20 (&id_priv->handler_mutex){+.+.}-{4:4}, at: smbdirect_socket_destroy_sync+0xc39/0x2440
[ 2424.594178]
[ 2424.594178] other info that might help us debug this:
[ 2424.596634]  Possible unsafe locking scenario:
[ 2424.596634]
[ 2424.598841]        CPU0
[ 2424.599765]        ----
[ 2424.600695]   lock(&id_priv->handler_mutex);
[ 2424.601836]   lock(&id_priv->handler_mutex);
[ 2424.602590]
[ 2424.602590]  *** DEADLOCK ***
[ 2424.602590]
[ 2424.604512]  May be due to missing lock nesting notation

Splice the pending/ready children onto a local list under the listener's listen.lock, while the handler lock is held so a concurrent CM CONNECT_REQUEST cannot add more, but defer the actual smbdirect_socket_release() calls until after the listener's cm_id has been destroyed and its handler lock dropped. The children are independent sockets whose teardown needs neither the listener's handler lock nor its cm_id.

Found with ksmbdzzer [2], a KSMBD fuzzer that drives libFuzzer with a kcov-dataflow [1] coverage vector: it folds each instrumented comparison/argument's runtime operand value together with its PC (the default arm mixes them as pc⊕val) so that a new operand value at a known site counts as new coverage.

[1] https://lwn.net/Articles/1077606/
[2] https://github.com/yskzalloc/kcov-dataflow

Fixes dc691b91ad16 ("smb: smbdirect: introduce smbdirect_socket_{listen,accept}()")
---
 fs/smb/smbdirect/socket.c | 56 ++++++++++++++++++++++++++++-----------
 1 file changed, 41 insertions(+), 15 deletions(-)
fs/smb/smbdirect/socket.c +41 -15
index 8dec47a6603cb..bb02df6158b97 100644
@@ -495,6 +495,7 @@ static void smbdirect_socket_destroy(struct smbdirect_socket *sc)
 	struct smbdirect_recv_io *recv_io;
 	struct smbdirect_recv_io *recv_tmp;
 	LIST_HEAD(all_list);
+	LIST_HEAD(pending_list);
 	unsigned long flags;
 
 	smbdirect_log_rdma_event(sc, SMBDIRECT_LOG_INFO,
@@ -552,24 +553,29 @@ static void smbdirect_socket_destroy(struct smbdirect_socket *sc)
 	 * disconnect all pending and ready sockets
 	 *
 	 * We move ready sockets to pending again.
+	 *
+	 * Capture them here -- rdma_lock_handler(sc->rdma.cm_id) is held above,
+	 * so a concurrent CM CONNECT_REQUEST cannot add more; sc->listen.lock
+	 * below only protects the list splice itself -- but DEFER releasing
+	 * them until the listener's cm_id is destroyed:
+	 *
+	 * - smbdirect_socket_release() -> smbdirect_socket_destroy() takes the
+	 *   child's own rdma_lock_handler() lock (&id_priv->handler_mutex).
+	 *   The listener's and the child's cm_id are always different
+	 *   instances, so the nesting cannot really deadlock, but lockdep only
+	 *   sees one lock class and reports "possible recursive locking".
+	 *
+	 * - rdma_destroy_id() of a child before the listener's own
+	 *   rdma_destroy_id() below lets _cma_cancel_listens() walk the freed
+	 *   child id_priv (KASAN slab-use-after-free in __mutex_lock()).
+	 *
+	 * The children are independent sockets whose teardown does not need
+	 * the listener's handler lock.
 	 */
 	spin_lock_irqsave(&sc->listen.lock, flags);
-	list_splice_tail_init(&sc->listen.ready, &all_list);
-	list_splice_tail_init(&sc->listen.pending, &all_list);
+	list_splice_tail_init(&sc->listen.ready, &pending_list);
+	list_splice_tail_init(&sc->listen.pending, &pending_list);
 	spin_unlock_irqrestore(&sc->listen.lock, flags);
-	psockets = list_count_nodes(&all_list);
-	if (sc->listen.backlog != -1) /* was a listener */
-		smbdirect_log_rdma_event(sc, SMBDIRECT_LOG_INFO,
-			"release %zu pending sockets\n", psockets);
-	list_for_each_entry_safe(psc, tsc, &all_list, accept.list) {
-		list_del_init(&psc->accept.list);
-		psc->accept.listener = NULL;
-		smbdirect_socket_release(psc);
-	}
-	if (sc->listen.backlog != -1) /* was a listener */
-		smbdirect_log_rdma_event(sc, SMBDIRECT_LOG_INFO,
-			"released %zu pending sockets\n", psockets);
-	INIT_LIST_HEAD(&all_list);
 
 	/* It's not possible for upper layer to get to reassembly */
 	if (sc->listen.backlog == -1) /* was not a listener */
@@ -599,6 +605,26 @@ static void smbdirect_socket_destroy(struct smbdirect_socket *sc)
 		sc->rdma.cm_id = NULL;
 	}
 
+	/*
+	 * The listener's rdma_lock_handler() lock is dropped and its cm_id is
+	 * destroyed, so it is safe to release the child sockets captured
+	 * above: each release recurses into smbdirect_socket_destroy() and
+	 * takes that child's own handler_mutex without nesting it under the
+	 * listener's, and _cma_cancel_listens() can no longer reach them.
+	 */
+	psockets = list_count_nodes(&pending_list);
+	if (sc->listen.backlog != -1) /* was a listener */
+		smbdirect_log_rdma_event(sc, SMBDIRECT_LOG_INFO,
+			"release %zu pending sockets\n", psockets);
+	list_for_each_entry_safe(psc, tsc, &pending_list, accept.list) {
+		list_del_init(&psc->accept.list);
+		psc->accept.listener = NULL;
+		smbdirect_socket_release(psc);
+	}
+	if (sc->listen.backlog != -1) /* was a listener */
+		smbdirect_log_rdma_event(sc, SMBDIRECT_LOG_INFO,
+			"released %zu pending sockets\n", psockets);
+
 	if (sc->listen.backlog == -1) /* was not a listener */
 		smbdirect_log_rdma_event(sc, SMBDIRECT_LOG_INFO,
 			"destroying mem pools\n");
Signature · 1 line
2.53.0
author maintainer
#1521 lore raw

PATCH 1505/1815 ksmbd: validate ipc response length before dereferencing its fields

In reply to Greg Kroah-Hartman

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

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

From: Yunseong Kim <[email protected]>

[ Upstream commit e9b33376bd07bca4175f7bcc2d6034ef250f8181 ]

ipc_validate_msg() computes the expected message size by reading length fields out of the response buffer supplied by the userspace ksmbd daemon (payload_sz, session_key_len, ngroups, ...). Those fields are read before the buffer is verified to be large enough to contain the struct they belong to, so a short response makes the read land past the end of the allocation.

handle_response() sizes entry->response purely from the netlink attribute length (nla_len()) and only guards the leading handle read, so the daemon can install a response as small as the kmalloc-8 object seen below. When ipc_msg_send_request() then calls ipc_validate_msg() for a KSMBD_EVENT_RPC_REQUEST, the cast to struct ksmbd_rpc_command reads resp->payload_sz at offset 8 of an 8-byte allocation:

[ 3697.841381] ==================================================================
[ 3697.844099] BUG: KASAN: slab-out-of-bounds in ipc_msg_send_request+0x763/0x800
[ 3697.846604] Read of size 4 at addr ffff888105f95910 by task kworker/4:3/20682
[ 3697.849061]
[ 3697.849801] CPU: 4 UID: 0 PID: 20682 Comm: kworker/4:3 Not tainted 7.2.0-rc3-next-20260717-virtme #117 PREEMPT(lazy)
[ 3697.850077] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.17.0-debian-1.17.0-1 04/01/2014
[ 3697.850303] Workqueue: ksmbd-io handle_ksmbd_work
[ 3697.850592] Call Trace:
[ 3697.850794]  <TASK>
[ 3697.850952]  __dump_stack+0x21/0x60
[ 3697.851239]  dump_stack_lvl+0xc2/0x100
[ 3697.851528]  print_address_description+0x77/0x200
[ 3697.851816]  ? ipc_msg_send_request+0x763/0x800
[ 3697.852024]  print_report+0x58/0x70
[ 3697.852316]  kasan_report+0x117/0x150
[ 3697.852585]  ? down_write+0x146/0x1f0
[ 3697.852809]  ? ipc_msg_send_request+0x763/0x800
[ 3697.853082]  ipc_msg_send_request+0x763/0x800
[ 3697.853385]  ? __pfx_ipc_msg_send_request+0x10/0x10
[ 3697.853604]  ? kasan_unpoison+0x48/0x70
[ 3697.853936]  ? __pfx___up_read+0x10/0x10
[ 3697.854221]  ksmbd_rpc_ioctl+0x380/0x520
[ 3697.854542]  ? __pfx_ksmbd_rpc_ioctl+0x10/0x10
[ 3697.854757]  ? kasan_unpoison+0x48/0x70
[ 3697.854962]  ? copy_from_kernel_nofault+0x32c/0x4e0
[ 3697.855166]  ? kasan_unpoison+0x48/0x70
[ 3697.855416]  fsctl_pipe_transceive+0x139/0x7a0
[ 3697.855705]  ? __pfx_copy_from_kernel_nofault+0x10/0x10
[ 3697.855937]  ? __pfx_fsctl_pipe_transceive+0x10/0x10
[ 3697.856388]  ? __sanitizer_cov_trace_switch+0x7b/0x140
[ 3697.856620]  smb2_ioctl+0x1141/0x3420
[ 3697.856994]  ? __pfx_smb2_ioctl+0x10/0x10
[ 3697.857182]  ? get_smb2_cmd_val+0xe3/0x1c0
[ 3697.857655]  handle_ksmbd_work+0x9ad/0x15e0
[ 3697.858034]  ? __pfx_handle_ksmbd_work+0x10/0x10
[ 3697.858251]  ? lock_release+0xf7/0x360
[ 3697.858466]  ? process_scheduled_works+0x954/0x1600
[ 3697.858698]  ? process_scheduled_works+0x954/0x1600
[ 3697.858905]  process_scheduled_works+0xc22/0x1600
[ 3697.859368]  ? __pfx_process_scheduled_works+0x10/0x10
[ 3697.859637]  ? __pfx_assign_work+0x10/0x10
[ 3697.859896]  ? lock_is_held_type+0x7b/0x110
[ 3697.860146]  worker_thread+0x975/0xee0
[ 3697.860524]  ? __pfx_do_raw_spin_lock+0x10/0x10
[ 3697.860830]  ? __kthread_parkme+0x21e/0x260
[ 3697.861105]  kthread+0x3a6/0x490
[ 3697.861423]  ? __pfx_worker_thread+0x10/0x10
[ 3697.861643]  ? __pfx_kthread+0x10/0x10
[ 3697.861878]  ret_from_fork+0x55a/0xa20
[ 3697.862194]  ? __pfx_ret_from_fork+0x10/0x10
[ 3697.862480]  ? __pfx_kthread+0x10/0x10
[ 3697.862714]  ret_from_fork_asm+0x1a/0x30
[ 3697.862965]  </TASK>
[ 3697.863039]
[ 3697.938882] Allocated by task 20761:
[ 3697.940257]  kasan_save_track+0x3e/0x80
[ 3697.941782]  __kasan_kmalloc+0x72/0x90
[ 3697.943228]  __kvmalloc_node_noprof+0x3e9/0x6a0
[ 3697.944948]  handle_generic_event+0x59b/0x750
[ 3697.946592]  genl_family_rcv_msg_doit+0x3d6/0x560
[ 3697.946977]  genl_rcv_msg+0x67c/0x900
[ 3697.947224]  netlink_rcv_skb+0x286/0x580
[ 3697.947488]  genl_rcv+0x2d/0x80
[ 3697.947706]  netlink_unicast+0x937/0xb70
[ 3697.947993]  netlink_sendmsg+0x977/0xc10
[ 3697.948268]  __sock_sendmsg+0x264/0x2d0
[ 3697.948536]  __sys_sendto+0x4de/0x690
[ 3697.948789]  __x64_sys_sendto+0x173/0x380
[ 3697.949069]  do_syscall_64+0x13d/0x420
[ 3697.949328]  entry_SYSCALL_64_after_hwframe+0x77/0x7f
[ 3697.949662]
[ 3697.949779] The buggy address belongs to the object at ffff888105f95908
[ 3697.949779]  which belongs to the cache kmalloc-8 of size 8
[ 3697.950550] The buggy address is located 0 bytes to the right of
[ 3697.950550]  allocated 8-byte region [ffff888105f95908, ffff888105f95910)
[ 3697.951455]
[ 3697.951574] The buggy address belongs to the physical page:
[ 3697.951958] page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff888105f951b8 pfn:0x105f95
[ 3697.952571] flags: 0x100000000000200(workingset|node=0|zone=2)
[ 3697.952973] page_type: f5(slab)
[ 3697.953198] raw: 0100000000000200 ffff888100042640 ffffea0004063610 ffff888100040588
[ 3697.953707] raw: ffff888105f951b8 00000000001c000e 00000000f5000000 0000000000000000
[ 3697.954240] page dumped because: kasan: bad access detected
[ 3697.954616]
[ 3697.954734] Memory state around the buggy address:
[ 3697.955063]  ffff888105f95800: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fa
[ 3697.955534]  ffff888105f95880: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 3697.956006] >ffff888105f95900: fc 00 fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 3697.956477]                          ^
[ 3697.956728]  ffff888105f95980: fc fc fc fa fc fc fc fc fc fc fc fc fc fc fc fc
[ 3697.957202]  ffff888105f95a00: fc fc fc fc fc fa fc fc fc fc fc fc fc fc fc fc
[ 3697.957671] ==================================================================

The final "entry->msg_sz != msg_sz" comparison cannot help: the offending read has already happened by the time it runs. Every case in the switch shares this pattern.

Floor entry->msg_sz against the base struct of each event type before dereferencing any of its length fields. On failure ipc_msg_send_request() already frees the response and returns NULL, so callers stay safe.

The malformed message originates from the ksmbd.mountd daemon over genl netlink rather than a remote SMB client, so triggering it requires a buggy or compromised daemon; it is still an out-of-bounds read the validator is meant to prevent.

Fixes d6a6aa81eac2 ("ksmbd: validate response sizes in ipc_validate_msg()")
---
 fs/smb/server/transport_ipc.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
fs/smb/server/transport_ipc.c +12 -0
index 0c581b9624d3e..c2bab860281e1 100644
@@ -497,6 +497,9 @@ static int ipc_validate_msg(struct ipc_msg_table_entry *entry)
 	{
 		struct ksmbd_rpc_command *resp = entry->response;
 
+		if (entry->msg_sz < sizeof(struct ksmbd_rpc_command))
+			return -EINVAL;
+
 		if (check_add_overflow(sizeof(struct ksmbd_rpc_command),
 				       resp->payload_sz, &msg_sz))
 			return -EINVAL;
@@ -506,6 +509,9 @@ static int ipc_validate_msg(struct ipc_msg_table_entry *entry)
 	{
 		struct ksmbd_spnego_authen_response *resp = entry->response;
 
+		if (entry->msg_sz < sizeof(struct ksmbd_spnego_authen_response))
+			return -EINVAL;
+
 		msg_sz = sizeof(struct ksmbd_spnego_authen_response) +
 				resp->session_key_len + resp->spnego_blob_len;
 		break;
@@ -514,6 +520,9 @@ static int ipc_validate_msg(struct ipc_msg_table_entry *entry)
 	{
 		struct ksmbd_share_config_response *resp = entry->response;
 
+		if (entry->msg_sz < sizeof(struct ksmbd_share_config_response))
+			return -EINVAL;
+
 		if (resp->payload_sz) {
 			if (resp->payload_sz < resp->veto_list_sz)
 				return -EINVAL;
@@ -528,6 +537,9 @@ static int ipc_validate_msg(struct ipc_msg_table_entry *entry)
 	{
 		struct ksmbd_login_response_ext *resp = entry->response;
 
+		if (entry->msg_sz < sizeof(struct ksmbd_login_response_ext))
+			return -EINVAL;
+
 		if (resp->ngroups) {
 			if (resp->ngroups < 0 ||
 			    resp->ngroups > NGROUPS_MAX) {
Signature · 1 line
2.53.0
author maintainer
#1522 lore raw

PATCH 1506/1815 ksmbd: do not advertise unimplemented CA support

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit eebdd3f1157e35a50df5ff2d3d9a305901df3254 ]

ksmbd durable handles are currently in-memory state. There is no persistent open recovery, cluster ownership epoch, fencing, or failover implementation behind the continuous-availability share flag.

Do not advertise SMB2 persistent-handle or continuous-availability capabilities until those guarantees exist. A client requesting DH2Q then falls back to the existing durable V2 behavior rather than being promised a persistent handle that cannot survive a server failure.

Stable-dep-of: 06c7b1d731bc ("ksmbd: free preauth sessions on connection teardown")

---
 fs/smb/server/smb2ops.c |  9 +++++----
 fs/smb/server/smb2pdu.c | 11 +++++------
 2 files changed, 10 insertions(+), 10 deletions(-)
fs/smb/server/smb2ops.c +5 -4
index c9a32ee096b58..9eb7e17379763 100644
@@ -266,8 +266,10 @@ void init_smb3_02_server(struct ksmbd_conn *conn)
 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL)
 		conn->vals->req_capabilities |= SMB2_GLOBAL_CAP_MULTI_CHANNEL;
 
-	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE)
-		conn->vals->req_capabilities |= SMB2_GLOBAL_CAP_PERSISTENT_HANDLES;
+	/*
+	 * Durable handles are in-memory only.  Do not advertise persistent
+	 * handles until CA recovery and fencing are implemented.
+	 */
 }
 
 /**
@@ -290,8 +292,7 @@ int init_smb3_11_server(struct ksmbd_conn *conn)
 	if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL)
 		conn->vals->req_capabilities |= SMB2_GLOBAL_CAP_MULTI_CHANNEL;
 
-	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE)
-		conn->vals->req_capabilities |= SMB2_GLOBAL_CAP_PERSISTENT_HANDLES;
+	/* See init_smb3_02_server(): persistent handles require CA recovery. */
 
 	INIT_LIST_HEAD(&conn->preauth_sess_table);
 	return 0;
fs/smb/server/smb2pdu.c +5 -6
index ebb832e47b49f..c85879607d1cc 100644
@@ -2324,12 +2324,11 @@ int smb2_tree_connect(struct ksmbd_work *work)
 		goto out_err1;
 	rsp->StructureSize = cpu_to_le16(16);
 out_err1:
-	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE && share &&
-	    test_share_config_flag(share,
-				   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
-		rsp->Capabilities = SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY;
-	else
-		rsp->Capabilities = 0;
+	/*
+	 * A configured CA share is not continuously available until persistent
+	 * open recovery, ownership fencing, and failover are implemented.
+	 */
+	rsp->Capabilities = 0;
 	rsp->Reserved = 0;
 	/* default manual caching */
 	rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
Signature · 1 line
2.53.0
author maintainer
#1523 lore raw

PATCH 1507/1815 ksmbd: free preauth sessions on connection teardown

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 06c7b1d731bc105a8644f1b70165ba8b9416cbab ]

SMB3.1.1 multichannel binding preserves the preauthentication hash in a preauth_session between the NTLM negotiate and authenticate requests. The binding NTLM negotiate allocates this object and returns STATUS_MORE_PROCESSING_REQUIRED. If the client disconnects before it sends the authenticate request, neither the authenticate nor error cleanup paths free the object.

Release any remaining preauthentication sessions when tearing down the connection. Initialize the list when allocating the connection so that this cleanup is safe regardless of the negotiated dialect.

Fixes f5a544e3bab7 ("ksmbd: add support for SMB3 multichannel")
---
 fs/smb/server/connection.c        |  3 +++
 fs/smb/server/mgmt/user_session.c | 11 +++++++++++
 fs/smb/server/mgmt/user_session.h |  1 +
 fs/smb/server/smb2ops.c           |  2 --
 4 files changed, 15 insertions(+), 2 deletions(-)
fs/smb/server/connection.c +3 -0
index ef6f202f4024c..636d6ce3386b2 100644
@@ -11,6 +11,7 @@
 #include "server.h"
 #include "smb_common.h"
 #include "mgmt/ksmbd_ida.h"
+#include "mgmt/user_session.h"
 #include "connection.h"
 #include "compress.h"
 #include "transport_tcp.h"
@@ -185,6 +186,7 @@ void ksmbd_conn_free(struct ksmbd_conn *conn)
 	kvfree(conn->request_buf);
 	kfree(conn->preauth_info);
 	kfree(conn->mechToken);
+	ksmbd_preauth_session_destroy(conn);
 	ksmbd_conn_put(conn);
 }
 
@@ -223,6 +225,7 @@ struct ksmbd_conn *ksmbd_conn_alloc(void)
 	init_waitqueue_head(&conn->r_count_q);
 	INIT_LIST_HEAD(&conn->requests);
 	INIT_LIST_HEAD(&conn->async_requests);
+	INIT_LIST_HEAD(&conn->preauth_sess_table);
 	spin_lock_init(&conn->request_lock);
 	spin_lock_init(&conn->credits_lock);
 	ida_init(&conn->async_ida);
fs/smb/server/mgmt/user_session.c +11 -0
index f99c86284ba3d..bf4a4222c1f57 100644
@@ -592,6 +592,17 @@ struct preauth_session *ksmbd_preauth_session_alloc(struct ksmbd_conn *conn,
 	return sess;
 }
 
+void ksmbd_preauth_session_destroy(struct ksmbd_conn *conn)
+{
+	struct preauth_session *sess, *tmp;
+
+	list_for_each_entry_safe(sess, tmp, &conn->preauth_sess_table,
+				 preauth_entry) {
+		list_del(&sess->preauth_entry);
+		kfree(sess);
+	}
+}
+
 void destroy_previous_session(struct ksmbd_conn *conn,
 			      struct ksmbd_user *user, u64 id)
 {
fs/smb/server/mgmt/user_session.h +1 -0
index 4637a8c8436d0..2a0168e083286 100644
@@ -104,6 +104,7 @@ void destroy_previous_session(struct ksmbd_conn *conn,
 			      struct ksmbd_user *user, u64 id);
 struct preauth_session *ksmbd_preauth_session_alloc(struct ksmbd_conn *conn,
 						    u64 sess_id);
+void ksmbd_preauth_session_destroy(struct ksmbd_conn *conn);
 struct preauth_session *ksmbd_preauth_session_lookup(struct ksmbd_conn *conn,
 						     unsigned long long id);
 
fs/smb/server/smb2ops.c +0 -2
index 9eb7e17379763..d1ddfd9028ef8 100644
@@ -293,8 +293,6 @@ int init_smb3_11_server(struct ksmbd_conn *conn)
 		conn->vals->req_capabilities |= SMB2_GLOBAL_CAP_MULTI_CHANNEL;
 
 	/* See init_smb3_02_server(): persistent handles require CA recovery. */
-
-	INIT_LIST_HEAD(&conn->preauth_sess_table);
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1524 lore raw

PATCH 1508/1815 ksmbd: support access-based directory enumeration

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit e5f42cb7577221080e4db0498d71e6db7e67f1a5 ]

SMB shares can advertise access-based directory enumeration. ksmbd does not currently provide a share option or filter inaccessible directory entries.

Add a hide-unreadable share flag and advertise SMB2_SHAREFLAG_ACCESS_BASED_DIRECTORY_ENUM when it is enabled. During QUERY_DIRECTORY, omit entries unless the connected user has FILE_READ_DATA, FILE_READ_EA, and FILE_READ_ATTRIBUTES access according to the Windows ACL.

Keep the existing implicit access allowances for normal CREATE permission checks while using strict access-mask matching for directory enumeration.

Stable-dep-of: b0148dc5625d ("ksmbd: serialize oplock close with pending break ownership")

---
 fs/smb/server/ksmbd_netlink.h |  1 +
 fs/smb/server/smb2pdu.c       | 24 +++++++++++++++++++++++-
 fs/smb/server/smbacl.c        | 13 ++++++++++---
 fs/smb/server/smbacl.h        |  3 ++-
 4 files changed, 36 insertions(+), 5 deletions(-)
fs/smb/server/ksmbd_netlink.h +1 -0
index 8ccd57fd904bc..c9e1b0b689d7f 100644
@@ -377,6 +377,7 @@ enum KSMBD_TREE_CONN_STATUS {
 #define KSMBD_SHARE_FLAG_UPDATE				BIT(14)
 #define KSMBD_SHARE_FLAG_CROSSMNT			BIT(15)
 #define KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY	BIT(16)
+#define KSMBD_SHARE_FLAG_HIDE_UNREADABLE		BIT(17)
 
 /*
  * Tree connect request flags.
fs/smb/server/smb2pdu.c +23 -1
index c85879607d1cc..8ef3123655c57 100644
@@ -2336,6 +2336,10 @@ int smb2_tree_connect(struct ksmbd_work *work)
 	if (conn->dialect == SMB311_PROT_ID &&
 	    conn->compress_algorithm != SMB3_COMPRESS_NONE)
 		rsp->ShareFlags |= cpu_to_le32(SMB2_SHAREFLAG_COMPRESS_DATA);
+	if (share && test_share_config_flag(share,
+					  KSMBD_SHARE_FLAG_HIDE_UNREADABLE))
+		rsp->ShareFlags |=
+			cpu_to_le32(SMB2_SHAREFLAG_ACCESS_BASED_DIRECTORY_ENUM);
 
 	rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
 	if (rc) {
@@ -3607,7 +3611,7 @@ int smb2_open(struct ksmbd_work *work)
 	if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
 		rc = smb_check_perm_dacl(conn, &path, &daccess,
 					 req->DesiredAccess,
-					 sess->user->uid);
+					 sess->user->uid, false);
 		if (rc)
 			goto err_out;
 	}
@@ -4582,6 +4586,7 @@ static int process_query_dir_entries(struct smb2_query_dir_private *priv)
 
 	for (i = 0; i < priv->d_info->num_entry; i++) {
 		struct dentry *dent;
+		struct path path;
 
 		if (dentry_name(priv->d_info, priv->info_level))
 			return -EINVAL;
@@ -4604,6 +4609,23 @@ static int process_query_dir_entries(struct smb2_query_dir_private *priv)
 			continue;
 		}
 
+		if (test_share_config_flag(priv->work->tcon->share_conf,
+					   KSMBD_SHARE_FLAG_HIDE_UNREADABLE)) {
+			__le32 daccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
+				FILE_READ_ATTRIBUTES_LE;
+
+			path.mnt = priv->dir_fp->filp->f_path.mnt;
+			path.dentry = dent;
+			rc = smb_check_perm_dacl(priv->work->conn, &path,
+						 &daccess, daccess,
+						 priv->work->sess->user->uid,
+						 true);
+			if (rc) {
+				dput(dent);
+				continue;
+			}
+		}
+
 		ksmbd_kstat.kstat = &kstat;
 		if (priv->info_level != FILE_NAMES_INFORMATION) {
 			rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
fs/smb/server/smbacl.c +10 -3
index 0537638153325..88bf7b97042f8 100644
@@ -1432,7 +1432,8 @@ bool smb_inherit_flags(int flags, bool is_dir)
 }
 
 int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,
-			__le32 *pdaccess, __le32 raw_daccess, int uid)
+			__le32 *pdaccess, __le32 raw_daccess, int uid,
+			bool strict)
 {
 	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
 	struct smb_ntsd *pntsd = NULL;
@@ -1617,8 +1618,14 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,
 	}
 
 check_access_bits:
-	if (granted &
-	    ~(access_bits | FILE_READ_ATTRIBUTES | READ_CONTROL | WRITE_DAC | DELETE)) {
+	if (strict) {
+		access_bits &= granted;
+	} else {
+		access_bits |= FILE_READ_ATTRIBUTES | READ_CONTROL |
+			WRITE_DAC | DELETE;
+	}
+
+	if (granted & ~access_bits) {
 		ksmbd_debug(SMB, "Access denied with winACL, granted : %x, access_req : %x\n",
 			    granted, le32_to_cpu(ace->access_req));
 		rc = -EACCES;
fs/smb/server/smbacl.h +2 -1
index bf0312bfa0405..01810c16cc046 100644
@@ -95,7 +95,8 @@ bool smb_inherit_flags(int flags, bool is_dir);
 int smb_inherit_dacl(struct ksmbd_conn *conn, const struct path *path,
 		     unsigned int uid, unsigned int gid);
 int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,
-			__le32 *pdaccess, __le32 raw_daccess, int uid);
+			__le32 *pdaccess, __le32 raw_daccess, int uid,
+			bool strict);
 int set_info_sec(struct ksmbd_conn *conn, struct ksmbd_tree_connect *tcon,
 		 const struct path *path, struct smb_ntsd *pntsd, int ntsd_len,
 		 bool type_check, bool get_write);
Signature · 1 line
2.53.0
author maintainer
#1525 lore raw

PATCH 1509/1815 ksmbd: fix durable handle v2 default timeout units (60 -> 60000)

In reply to Greg Kroah-Hartman

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

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

From: Gael Blivet <[email protected]>

[ Upstream commit c1d7bbfc5e081875053723d1a69eb2cf341eaaf1 ]

When a client's Durable Handle Request V2 sets Timeout=0 ("let the server choose"), fp->durable_timeout was set to 60. Every other use of this field is in milliseconds: DURABLE_HANDLE_MAX_TIMEOUT (300000) in smb2pdu.h, the nonzero branch immediately above (min_t(unsigned int, dh_info.timeout, DURABLE_HANDLE_MAX_TIMEOUT), where dh_info.timeout is the wire value and already milliseconds per spec), and the scavenger in vfs_cache.c, which adds it directly to jiffies_to_msecs(jiffies).

60 is off by 1000x: the handle becomes scavenger-eligible 60 milliseconds after close instead of 60 seconds. A client requesting Timeout=0 is relying entirely on the server's default to cover the gap between a dropped connection and its reconnect -- 60ms is not enough time for even a fast network blip to be detected and reconnected, so any real disruption loses the race and a subsequent DH2C reconnect fails with a durable-handle lookup miss instead of succeeding.

Assisted-by Claude:claude-sonnet-5

Stable-dep-of: b0148dc5625d ("ksmbd: serialize oplock close with pending break ownership")

---
 fs/smb/server/smb2pdu.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +8 -1
index 8ef3123655c57..c01c72ea00d2a 100644
@@ -4019,10 +4019,17 @@ int smb2_open(struct ksmbd_work *work)
 					min_t(unsigned int, dh_info.timeout,
 					      DURABLE_HANDLE_MAX_TIMEOUT);
 			else
-				fp->durable_timeout = 60;
+				fp->durable_timeout = 60000;
 		}
 	}
 
+	/*
+	 * conn->is_aapl detection above (this function's create-context
+	 * parsing) is skipped on the reconnect path below, since a
+	 * reconnect always arrives on a fresh connection -- if the client
+	 * cares, it sends its own AAPL context on this same CREATE, which
+	 * this function's normal (non-reconnect) parsing already handles.
+	 */
 reconnected_fp:
 	rsp->StructureSize = cpu_to_le16(89);
 	opinfo = opinfo_get(fp);
Signature · 1 line
2.53.0
author maintainer
#1526 lore raw

PATCH 1510/1815 ksmbd: add AAPL kAAPL_SERVER_QUERY create context support

In reply to Greg Kroah-Hartman

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

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

From: Gael Blivet <[email protected]>

[ Upstream commit 8f1b796ff1135f5660e1889973359331c61b78a0 ]

macOS clients (Finder, and specifically Time Machine's backupd) send an "AAPL" SMB2 create context on CREATE to negotiate AAPL-specific server capabilities (server_caps/vol_caps/model string). Without a response to this context, macOS Time Machine over SMB does not work at all.

Add the AAPL create context structs (create_aapl_rsp, aapl_server_query_req) and create_aapl_rsp_buf(), which builds the kAAPL_SERVER_QUERY response mirroring the layout observed from macOS's own smbd, including the model string workaround: omitting the model string when the client requested it causes smbfs.kext to enter a broken disconnect path requiring a full macOS reboot to recover from. Command codes and bitmap values reuse the existing SMB2_CRTCTX_AAPL_* constants in fs/smb/common/smb2pdu.h.

Wire format confirmed against AAPL's published public client kernel source (public client behavior reference) -- every field here and every SMB2_CRTCTX_AAPL_* constant matches exactly.

Hook the request parsing and response into smb2_open()'s existing create-context handling, following the same DataOffset+DataLength bounds-checking convention already used by every other context parser in this file. The AAPL model string is configurable via the existing netlink startup path (server_conf.aapl_model, default "Xserve").

This is scoped to shares with the new KSMBD_SHARE_FLAG_TIME_MACHINE flag only, not enabled globally -- AAPL's AAPL extension is undocumented, so containing its blast radius to shares that explicitly opt in limits risk to ordinary SMB shares.

conn->aapl_readdir_attr is set here when the client also advertises READDIR_ATTR support, but the actual inline-FinderInfo wire format (the feature that flag gates) is not implemented yet -- follow-up commit.

Assisted-by Claude:claude-sonnet-5

Stable-dep-of: b0148dc5625d ("ksmbd: serialize oplock close with pending break ownership")

---
 fs/smb/common/smbglob.h       |  1 +
 fs/smb/server/connection.h    |  1 +
 fs/smb/server/ksmbd_netlink.h |  4 +-
 fs/smb/server/oplock.c        | 77 +++++++++++++++++++++++++++++++++++
 fs/smb/server/oplock.h        |  1 +
 fs/smb/server/server.h        |  2 +
 fs/smb/server/smb2ops.c       |  4 ++
 fs/smb/server/smb2pdu.c       | 56 ++++++++++++++++++++++++-
 fs/smb/server/smb2pdu.h       | 59 +++++++++++++++++++++++++++
 fs/smb/server/transport_ipc.c |  9 ++++
 10 files changed, 212 insertions(+), 2 deletions(-)
fs/smb/common/smbglob.h +1 -0
index 4e33d91cdc9db..d9c7e6e7af295 100644
@@ -39,6 +39,7 @@ struct smb_version_values {
 	size_t		create_mxac_size;
 	size_t		create_disk_id_size;
 	size_t		create_posix_size;
+	size_t		create_aapl_size;
 };
 
 static inline unsigned int get_rfc1002_len(void *buf)
fs/smb/server/connection.h +1 -0
index 0e4ebfac55588..158feb019142f 100644
@@ -124,6 +124,7 @@ struct ksmbd_conn {
 	bool				binding;
 	atomic_t			refcnt;
 	bool				is_aapl;
+	bool				aapl_readdir_attr; /* READDIR_ATTR negotiated */
 	struct work_struct		release_work;
 };
 
fs/smb/server/ksmbd_netlink.h +3 -1
index c9e1b0b689d7f..1ea0a367b3969 100644
@@ -113,7 +113,8 @@ struct ksmbd_startup_request {
 	__u32	max_connections;	/* Number of maximum simultaneous connections */
 	__s8	bind_interfaces_only;
 	__u32	max_ip_connections;	/* Number of maximum connection per ip address */
-	__s8	reserved[499];		/* Reserved room */
+	__s8	aapl_model[32];		/* AAPL model string for Finder icon, e.g. "Xserve" */
+	__s8	reserved[467];		/* Reserved room */
 	__u32	ifc_list_sz;		/* interfaces list size */
 	__s8	____payload[];
 } __packed;
@@ -378,6 +379,7 @@ enum KSMBD_TREE_CONN_STATUS {
 #define KSMBD_SHARE_FLAG_CROSSMNT			BIT(15)
 #define KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY	BIT(16)
 #define KSMBD_SHARE_FLAG_HIDE_UNREADABLE		BIT(17)
+#define KSMBD_SHARE_FLAG_TIME_MACHINE			BIT(18)
 
 /*
  * Tree connect request flags.
fs/smb/server/oplock.c +77 -0

89 lines not on this page · raw message

fs/smb/server/oplock.h +1 -0
index 3f581d22bb676..f7f6afcc5434c 100644
@@ -125,6 +125,7 @@ void create_durable_v2_rsp_buf(char *cc, struct ksmbd_file *fp);
 void create_mxac_rsp_buf(char *cc, int maximal_access);
 void create_disk_id_rsp_buf(char *cc, __u64 file_id, __u64 vol_id);
 void create_posix_rsp_buf(char *cc, struct ksmbd_file *fp);
+void create_aapl_rsp_buf(char *cc, __u64 vol_caps, __u64 req_bitmap);
 struct create_context *smb2_find_context_vals(void *open_req, const char *tag, int tag_len);
 struct oplock_info *lookup_lease_in_table(struct ksmbd_conn *conn,
 					  char *lease_key);
fs/smb/server/server.h +2 -0
index b8a7317be86b4..4d4d268b59d5a 100644
@@ -48,6 +48,8 @@ struct ksmbd_server_config {
 	char			*conf[SERVER_CONF_WORK_GROUP + 1];
 	struct task_struct	*dh_task;
 	bool			bind_interfaces_only;
+	/* AAPL model string for Finder icon, e.g. "Xserve" */
+	char			aapl_model[32];
 };
 
 extern struct ksmbd_server_config server_conf;
fs/smb/server/smb2ops.c +4 -0
index d1ddfd9028ef8..8c1f5b5c98287 100644
@@ -37,6 +37,7 @@ static struct smb_version_values smb21_server_values = {
 	.create_mxac_size = sizeof(struct create_mxac_rsp),
 	.create_disk_id_size = sizeof(struct create_disk_id_rsp),
 	.create_posix_size = sizeof(struct create_posix_rsp),
+	.create_aapl_size = AAPL_RSP_MAX_SIZE,
 };
 
 static struct smb_version_values smb30_server_values = {
@@ -64,6 +65,7 @@ static struct smb_version_values smb30_server_values = {
 	.create_mxac_size = sizeof(struct create_mxac_rsp),
 	.create_disk_id_size = sizeof(struct create_disk_id_rsp),
 	.create_posix_size = sizeof(struct create_posix_rsp),
+	.create_aapl_size = AAPL_RSP_MAX_SIZE,
 };
 
 static struct smb_version_values smb302_server_values = {
@@ -91,6 +93,7 @@ static struct smb_version_values smb302_server_values = {
 	.create_mxac_size = sizeof(struct create_mxac_rsp),
 	.create_disk_id_size = sizeof(struct create_disk_id_rsp),
 	.create_posix_size = sizeof(struct create_posix_rsp),
+	.create_aapl_size = AAPL_RSP_MAX_SIZE,
 };
 
 static struct smb_version_values smb311_server_values = {
@@ -118,6 +121,7 @@ static struct smb_version_values smb311_server_values = {
 	.create_mxac_size = sizeof(struct create_mxac_rsp),
 	.create_disk_id_size = sizeof(struct create_disk_id_rsp),
 	.create_posix_size = sizeof(struct create_posix_rsp),
+	.create_aapl_size = AAPL_RSP_MAX_SIZE,
 };
 
 static struct smb_version_ops smb2_0_server_ops = {
fs/smb/server/smb2pdu.c +55 -1

80 lines not on this page · raw message

fs/smb/server/smb2pdu.h +59 -0

65 lines not on this page · raw message

fs/smb/server/transport_ipc.c +9 -0
index c2bab860281e1..2584b162415b3 100644
@@ -322,6 +322,15 @@ static int ipc_server_config_on_startup(struct ksmbd_startup_request *req)
 		goto out;
 	}
 	server_conf.share_fake_fscaps = req->share_fake_fscaps;
+
+	/* AAPL model string for Finder icon */
+	if (req->aapl_model[0])
+		strscpy(server_conf.aapl_model, req->aapl_model,
+			sizeof(server_conf.aapl_model));
+	else
+		strscpy(server_conf.aapl_model, "Xserve",
+			sizeof(server_conf.aapl_model));
+
 	ksmbd_init_domain(req->sub_auth);
 
 	if (req->smb2_max_read)
Signature · 1 line
2.53.0
author maintainer
#1527 lore raw

PATCH 1511/1815 ksmbd: defer CHANGE_NOTIFY completion instead of STATUS_NOT_IMPLEMENTED

In reply to Greg Kroah-Hartman

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

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

From: Gael Blivet <[email protected]>

[ Upstream commit 152036e875e8cfe41dc70328f7e499ccc5142d6c ]

smb2_notify() currently returns STATUS_NOT_IMPLEMENTED synchronously for every CHANGE_NOTIFY request. Genuine SMB2 servers never complete a CHANGE_NOTIFY spontaneously -- it's satisfied only by a real directory change or with STATUS_NOTIFY_CLEANUP when the watched handle is closed. macOS smbfs.kext depends on this deferred-completion contract:
receiving STATUS_NOT_IMPLEMENTED instead makes it hard-freeze on unmount, since it never sees the cleanup it's waiting for.

Add a notify_pendings list on struct ksmbd_file (protected by the existing f_lock) and a notify_entry list_head on struct ksmbd_work to link onto it. smb2_notify() now replies STATUS_PENDING immediately and queues a deferred STATUS_NOTIFY_CLEANUP response on the watched handle; __ksmbd_close_fd() drains and sends any pending notifications when the handle is actually closed. The drain splices the list out under fp->f_lock first, then processes the detached copy without the lock -- smb2_notify() on another connection can be adding to the same list at the same time a close happens on this one, and ksmbd_conn_write() can sleep (it takes the connection's write mutex), so it must not be called while the spinlock is held.

Also handle the FileId=FFFF...FFFF share-root sentinel that macOS backupd sends to watch for changes without holding an open handle -- without an immediate STATUS_PENDING/STATUS_NOTIFY_CLEANUP reply here, backupd aborts Time Machine setup with STATUS_FILE_CLOSED.

Assisted-by Claude:claude-sonnet-5

Stable-dep-of: b0148dc5625d ("ksmbd: serialize oplock close with pending break ownership")

---
 fs/smb/server/ksmbd_work.c |   1 +
 fs/smb/server/ksmbd_work.h |   2 +
 fs/smb/server/smb2pdu.c    | 226 ++++++++++++++++++++++++++++++++++++-
 fs/smb/server/vfs_cache.c  |  48 ++++++++
 fs/smb/server/vfs_cache.h  |   6 +
 5 files changed, 280 insertions(+), 3 deletions(-)
fs/smb/server/ksmbd_work.c +1 -0
index e2c2f45264bea..97502273a49c0 100644
@@ -56,6 +56,7 @@ struct ksmbd_work *ksmbd_alloc_work_struct(void)
 		INIT_LIST_HEAD(&work->request_entry);
 		INIT_LIST_HEAD(&work->async_request_entry);
 		INIT_LIST_HEAD(&work->fp_entry);
+		INIT_LIST_HEAD(&work->notify_entry);
 		INIT_LIST_HEAD(&work->aux_read_list);
 		work->iov_alloc_cnt = ARRAY_SIZE(work->iov_inline);
 		work->iov = work->iov_inline;
fs/smb/server/ksmbd_work.h +2 -0
index 88104f0cf3636..50c4aa779647d 100644
@@ -104,6 +104,8 @@ struct ksmbd_work {
 	/* List head at conn->async_requests */
 	struct list_head                async_request_entry;
 	struct list_head                fp_entry;
+	/* List head at ksmbd_file->notify_pendings */
+	struct list_head                notify_entry;
 };
 
 /**
fs/smb/server/smb2pdu.c +223 -3

244 lines not on this page · raw message

fs/smb/server/vfs_cache.c +48 -0

66 lines not on this page · raw message

fs/smb/server/vfs_cache.h +6 -0
index b9e27307a26c1..b5788b40df4b1 100644
@@ -135,6 +135,12 @@ struct ksmbd_file {
 
 	bool                            is_posix_ctxt;
 	struct durable_owner		owner;
+
+	/*
+	 * Pending CHANGE_NOTIFY completions for this handle, sent with
+	 * STATUS_NOTIFY_CLEANUP when the handle is closed.
+	 */
+	struct list_head		notify_pendings;
 };
 
 static inline void set_ctx_actor(struct dir_context *ctx,
Signature · 1 line
2.53.0
author maintainer
#1528 lore raw

PATCH 1512/1815 ksmbd: retain connection for pending notify work

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit f495154703cbcc0050cfd53469bd56965791616b ]

Deferred CHANGE_NOTIFY work keeps an async message ID after the original request work is released. A durable handle can outlive its connection, so the connection teardown can destroy its async IDA before the handle close releases the pending notify work.

Give the synthetic deferred work a connection reference. Release it after the async ID in ksmbd_free_work_struct(). This keeps the async IDA alive until the deferred work is released, even when the original connection has already left the connection list.

During server shutdown there is no client to receive a cleanup response. Skip the write and only release the pending work.

Stable-dep-of: b0148dc5625d ("ksmbd: serialize oplock close with pending break ownership")

---
 fs/smb/server/ksmbd_work.c | 2 ++
 fs/smb/server/ksmbd_work.h | 2 ++
 fs/smb/server/smb2pdu.c    | 4 +++-
 3 files changed, 7 insertions(+), 1 deletion(-)
fs/smb/server/ksmbd_work.c +2 -0
index 97502273a49c0..c3f8915c39523 100644
@@ -86,6 +86,8 @@ void ksmbd_free_work_struct(struct ksmbd_work *work)
 
 	if (work->async_id)
 		ksmbd_release_id(&work->conn->async_ida, work->async_id);
+	if (work->owns_conn_ref)
+		ksmbd_conn_put(work->conn);
 	kmem_cache_free(work_cache, work);
 }
 
fs/smb/server/ksmbd_work.h +2 -0
index 50c4aa779647d..e35a40d764d6e 100644
@@ -90,6 +90,8 @@ struct ksmbd_work {
 	bool                            compress_response:1;
 	/* Is this SYNC or ASYNC ksmbd_work */
 	bool                            asynchronous:1;
+	/* Work owns a reference to @conn. */
+	bool				owns_conn_ref:1;
 	bool                            need_invalidate_rkey:1;
 
 	unsigned int                    remote_key;
fs/smb/server/smb2pdu.c +3 -1
index 14ba8ed098ffa..ba00678c66193 100644
@@ -9851,7 +9851,9 @@ int smb2_notify(struct ksmbd_work *work)
 
 	smb2_send_interim_resp(work, STATUS_PENDING);
 
-	in_work->conn = work->conn;
+	/* Keep the async IDA alive until the deferred work is released. */
+	in_work->conn = ksmbd_conn_get(work->conn);
+	in_work->owns_conn_ref = true;
 	in_hdr = smb_get_msg(in_work->response_buf);
 	memcpy(in_hdr, ksmbd_resp_buf_next(work), __SMB2_HEADER_STRUCTURE_SIZE);
 	in_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
Signature · 1 line
2.53.0
author maintainer
#1529 lore raw

PATCH 1513/1815 ksmbd: add SMB3 request replay support

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit bb8bf7eb13b518b379356a0c5dee8a23d6ee37ac ]

SMB3 clients can replay selected requests after a channel disconnect by setting SMB2_FLAGS_REPLAY_OPERATION. The command sequence window rejects duplicate MessageIds on one connection, but it does not validate requests resent on another channel with a new MessageId.

Add the state and validation required to replay durable CREATE and file-handle operations:

- track each open ChannelSequence, outstanding request counts, and lock sequence entries.
- retain a request-owned open reference until the common response path completes ChannelSequence accounting.
- replay DurableHandleReqV2 CREATE requests by CreateGuid, validating the durable state, SecurityContext, session, lease key, and persistent flag.
- publish CreateGuid and SecurityContext before an oplock or lease break can defer CREATE, rejecting replays of that pending CREATE with STATUS_FILE_NOT_AVAILABLE.
- retain the original CREATE action and replay completed CreateGuid requests, including requests that did not receive a durable-handle grant, without modifying the existing open.
- make replayed oplock and lease break acknowledgements idempotent. And
- preserve SMB2_FLAGS_REPLAY_OPERATION in responses.

Return STATUS_FILE_NOT_AVAILABLE when ChannelSequence validation rejects a replayed WRITE, IOCTL, or SET_INFO request.

Stable-dep-of: b0148dc5625d ("ksmbd: serialize oplock close with pending break ownership")

---
 fs/smb/server/ksmbd_work.c        |   2 +
 fs/smb/server/ksmbd_work.h        |   9 +
 fs/smb/server/mgmt/user_session.c |   8 -
 fs/smb/server/oplock.c            |  39 ++-
 fs/smb/server/oplock.h            |   2 +-
 fs/smb/server/server.c            |   9 +-
 fs/smb/server/smb2pdu.c           | 525 ++++++++++++++++++++++++++++--
 fs/smb/server/smb2pdu.h           |   1 +
 fs/smb/server/vfs_cache.c         |  13 +-
 fs/smb/server/vfs_cache.h         |  18 +
 10 files changed, 587 insertions(+), 39 deletions(-)
fs/smb/server/ksmbd_work.c +2 -0
index c3f8915c39523..f35335307670f 100644
@@ -11,6 +11,7 @@
 #include "server.h"
 #include "connection.h"
 #include "ksmbd_work.h"
+#include "vfs_cache.h"
 #include "mgmt/ksmbd_ida.h"
 
 static struct kmem_cache *work_cache;
@@ -88,6 +89,7 @@ void ksmbd_free_work_struct(struct ksmbd_work *work)
 		ksmbd_release_id(&work->conn->async_ida, work->async_id);
 	if (work->owns_conn_ref)
 		ksmbd_conn_put(work->conn);
+	ksmbd_fd_put(work, work->request_open);
 	kmem_cache_free(work_cache, work);
 }
 
fs/smb/server/ksmbd_work.h +9 -0
index e35a40d764d6e..52d0c4dee65c9 100644
@@ -12,6 +12,7 @@
 struct ksmbd_conn;
 struct ksmbd_session;
 struct ksmbd_tree_connect;
+struct ksmbd_file;
 
 #define KSMBD_WORK_INLINE_IOVS	4
 
@@ -93,6 +94,7 @@ struct ksmbd_work {
 	/* Work owns a reference to @conn. */
 	bool				owns_conn_ref:1;
 	bool                            need_invalidate_rkey:1;
+	bool				request_open_chseq_tracked:1;
 
 	unsigned int                    remote_key;
 	/* cancel works */
@@ -100,6 +102,13 @@ struct ksmbd_work {
 	void                            **cancel_argv;
 	void                            (*cancel_fn)(void **argv);
 
+	/*
+	 * Refcounted open associated with the SMB2 command currently being
+	 * processed.
+	 */
+	struct ksmbd_file		*request_open;
+	__le16				request_open_chseq;
+
 	struct work_struct              work;
 	/* List head at conn->requests */
 	struct list_head                request_entry;
fs/smb/server/mgmt/user_session.c +0 -8
index bf4a4222c1f57..b5d79924439ff 100644
@@ -475,14 +475,6 @@ void ksmbd_sessions_deregister(struct ksmbd_conn *conn)
 
 	down_write(&conn->session_lock);
 	xa_for_each(&conn->sessions, id, sess) {
-		unsigned long chann_id;
-		struct channel *chann;
-
-		xa_for_each(&sess->ksmbd_chann_list, chann_id, chann) {
-			if (chann->conn != conn)
-				ksmbd_conn_set_exiting(chann->conn);
-		}
-
 		ksmbd_chann_del(conn, sess);
 		if (xa_empty(&sess->ksmbd_chann_list)) {
 			xa_erase(&conn->sessions, sess->id);
fs/smb/server/oplock.c +37 -2
index 0e9912777aaaa..7d77ee0cb953d 100644
@@ -1234,6 +1234,18 @@ static int oplock_break(struct oplock_info *brk_opinfo, struct ksmbd_inode *ci,
 		if (brk_opinfo->level == SMB2_OPLOCK_LEVEL_BATCH ||
 		    brk_opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
 			brk_opinfo->op_state = OPLOCK_ACK_WAIT;
+
+		/*
+		 * Keep a conflicting CREATE asynchronous while waiting for an
+		 * oplock-break acknowledgement.  Besides avoiding a blocked client
+		 * request, this lets a replay arrive while the original CREATE is
+		 * still pending and be rejected with FILE_NOT_AVAILABLE.
+		 */
+		if (in_work) {
+			setup_async_work(in_work, NULL, NULL);
+			smb2_send_interim_resp(in_work, STATUS_PENDING);
+			release_async_work(in_work);
+		}
 	}
 
 	err = smb2_oplock_break_noti(brk_opinfo, ci);
@@ -1476,12 +1488,13 @@ void smb_lazy_parent_lease_break_close(struct ksmbd_file *fp)
  * @tid:		Tree id of connection
  * @lctx:		lease context information on file open
  * @share_ret:		share mode
+ * @replay:		whether this is a replayed CREATE request
  *
  * Return:      0 on success, otherwise error
  */
 int smb_grant_oplock(struct ksmbd_work *work, int req_op_level, u64 pid,
 		     struct ksmbd_file *fp, __u16 tid,
-		     struct lease_ctx_info *lctx, int share_ret)
+		     struct lease_ctx_info *lctx, int share_ret, bool replay)
 {
 	int err = 0;
 	int break_level = SMB2_OPLOCK_LEVEL_II;
@@ -1565,6 +1578,21 @@ int smb_grant_oplock(struct ksmbd_work *work, int req_op_level, u64 pid,
 	prev_op_has_lease = prev_opinfo->is_lease;
 	if (prev_op_has_lease)
 		prev_op_state = prev_opinfo->o_lease->state;
+	/*
+	 * A replay received while this open is waiting for an oplock or lease
+	 * break must not observe an intermediate level and proceed as a new
+	 * open. This check has to precede break_needed. an oplock may already
+	 * have been downgraded from Batch to II while its acknowledgement is
+	 * still pending.
+	 */
+	if (replay &&
+	    (test_bit(0, &prev_opinfo->pending_break) ||
+	     prev_opinfo->op_state == OPLOCK_ACK_WAIT)) {
+		err = -EINPROGRESS;
+		opinfo_put(prev_opinfo);
+		goto err_out;
+	}
+
 	if (share_ret < 0 &&
 	    prev_opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
 		err = share_ret;
@@ -1595,7 +1623,14 @@ int smb_grant_oplock(struct ksmbd_work *work, int req_op_level, u64 pid,
 		goto set_lev;
 	}
 	if (err == -ENOENT) {
-		if (req_op_level != SMB2_OPLOCK_LEVEL_NONE)
+		/*
+		 * A pending durable CREATE can lose the previous oplock when
+		 * its holder closes the file. In that case grant the original
+		 * request its full caching state. Other opens still need the
+		 * normal shared-open downgrade below.
+		 */
+		if (!prev_durable_open &&
+		    req_op_level != SMB2_OPLOCK_LEVEL_NONE)
 			req_op_level = SMB2_OPLOCK_LEVEL_II;
 		goto set_lev;
 	}
fs/smb/server/oplock.h +1 -1
index f7f6afcc5434c..0ba93d54caca5 100644
@@ -96,7 +96,7 @@ struct oplock_break_info {
 
 int smb_grant_oplock(struct ksmbd_work *work, int req_op_level,
 		     u64 pid, struct ksmbd_file *fp, __u16 tid,
-		     struct lease_ctx_info *lctx, int share_ret);
+		     struct lease_ctx_info *lctx, int share_ret, bool replay);
 void smb_break_all_levII_oplock(struct ksmbd_work *work,
 				struct ksmbd_file *fp, int is_trunc);
 void smb_break_all_levII_oplock_no_interim(struct ksmbd_work *work,
fs/smb/server/server.c +8 -1
index 960c4c897c11f..95be17b797147 100644
@@ -15,6 +15,7 @@
 
 #include "server.h"
 #include "smb_common.h"
+#include "smb2pdu.h"
 #include "../common/smb2status.h"
 #include "connection.h"
 #include "transport_ipc.h"
@@ -229,8 +230,10 @@ static void __handle_ksmbd_work(struct ksmbd_work *work,
 		}
 
 		rc = __process_request(work, conn, &command);
-		if (rc == SERVER_HANDLER_ABORT)
+		if (rc == SERVER_HANDLER_ABORT) {
+			smb2_complete_request_open(work);
 			break;
+		}
 
 		/*
 		 * Call smb2_set_rsp_credits() function to set number of credits
@@ -243,10 +246,13 @@ static void __handle_ksmbd_work(struct ksmbd_work *work,
 			if (rc < 0) {
 				conn->ops->set_rsp_status(work,
 					STATUS_INVALID_PARAMETER);
+				smb2_complete_request_open(work);
 				goto send;
 			}
 		}
 
+		smb2_complete_request_open(work);
+
 		is_chained = is_chained_smb2_message(work);
 
 		if (work->sess &&
@@ -262,6 +268,7 @@ static void __handle_ksmbd_work(struct ksmbd_work *work,
 	} while (is_chained == true);
 
 send:
+	smb2_complete_request_open(work);
 	/*
 	 * Release any credit charge still outstanding for this request.  On
 	 * the normal path smb2_set_rsp_credits() already returned it, but the
fs/smb/server/smb2pdu.c +502 -23

778 lines not on this page · raw message

fs/smb/server/smb2pdu.h +1 -0
index 12582162e233a..1836259be8971 100644
@@ -406,6 +406,7 @@ bool smb3_encryption_negotiated(struct ksmbd_conn *conn);
 
 /* smb2 misc functions */
 int ksmbd_smb2_check_message(struct ksmbd_work *work);
+void smb2_complete_request_open(struct ksmbd_work *work);
 
 /* smb2 command handlers */
 int smb2_handle_negotiate(struct ksmbd_work *work);
fs/smb/server/vfs_cache.c +9 -4
index 66f73825be93e..0efef8c8176c2 100644
@@ -676,6 +676,11 @@ static struct ksmbd_file *ksmbd_fp_get(struct ksmbd_file *fp)
 	return fp;
 }
 
+struct ksmbd_file *ksmbd_file_get(struct ksmbd_file *fp)
+{
+	return ksmbd_fp_get(fp);
+}
+
 static struct ksmbd_file *__ksmbd_lookup_fd(struct ksmbd_file_table *ft,
 					    u64 id)
 {
@@ -1519,7 +1524,7 @@ void ksmbd_stop_durable_scavenger(void)
 }
 
 /*
- * ksmbd_vfs_copy_durable_owner - Copy owner info for durable reconnect
+ * ksmbd_vfs_set_durable_owner - Store owner info for durable replay/reconnect
  * @fp: ksmbd file pointer to store owner info
  * @user: user pointer to copy from
  *
@@ -1528,8 +1533,8 @@ void ksmbd_stop_durable_scavenger(void)
  *
  * Return: 0 on success, or negative error code on failure
  */
-static int ksmbd_vfs_copy_durable_owner(struct ksmbd_file *fp,
-		struct ksmbd_user *user)
+int ksmbd_vfs_set_durable_owner(struct ksmbd_file *fp,
+				struct ksmbd_user *user)
 {
 	char *name;
 
@@ -1600,7 +1605,7 @@ static bool session_fd_check(struct ksmbd_tree_connect *tcon,
 	if (WARN_ON_ONCE(!fp->conn))
 		return false;
 
-	if (ksmbd_vfs_copy_durable_owner(fp, user))
+	if (ksmbd_vfs_set_durable_owner(fp, user))
 		return false;
 
 	/*
fs/smb/server/vfs_cache.h +18 -0
index b5788b40df4b1..8bb4396f95238 100644
@@ -82,6 +82,13 @@ struct durable_owner {
 	char *name;
 };
 
+#define KSMBD_LOCK_SEQ_ARRAY_SIZE	64
+
+struct ksmbd_lock_sequence {
+	bool				valid;
+	u8				sequence;
+};
+
 struct ksmbd_file {
 	struct file			*filp;
 	u64				persistent_id;
@@ -101,6 +108,7 @@ struct ksmbd_file {
 	__le32				saccess;
 	__le32				coption;
 	__le32				cdoption;
+	__le32				create_file_attributes;
 	__u64				create_time;
 	__u64				change_time;
 	__u64				allocation_size;
@@ -121,6 +129,8 @@ struct ksmbd_file {
 
 	unsigned int			durable_timeout;
 	unsigned int			durable_scavenger_timeout;
+	/* CREATE action returned when this durable handle was established. */
+	__le32				create_action;
 
 	/* if ls is happening on directory, below is valid*/
 	struct ksmbd_readdir_data	readdir_data;
@@ -132,9 +142,14 @@ struct ksmbd_file {
 	bool				is_persistent;
 	bool				is_resilient;
 	bool				durable_reconnect_disabled;
+	bool				durable_replay_consumed;
 
 	bool                            is_posix_ctxt;
 	struct durable_owner		owner;
+	__le16				channel_sequence;
+	unsigned int			outstanding_requests;
+	unsigned int			outstanding_pre_requests;
+	struct ksmbd_lock_sequence	lock_seq[KSMBD_LOCK_SEQ_ARRAY_SIZE];
 
 	/*
 	 * Pending CHANGE_NOTIFY completions for this handle, sent with
@@ -173,6 +188,9 @@ struct ksmbd_file *ksmbd_lookup_fd_fast(struct ksmbd_work *work, u64 id);
 struct ksmbd_file *ksmbd_lookup_foreign_fd(struct ksmbd_work *work, u64 id);
 struct ksmbd_file *ksmbd_lookup_fd_slow(struct ksmbd_work *work, u64 id,
 					u64 pid);
+int ksmbd_vfs_set_durable_owner(struct ksmbd_file *fp,
+				struct ksmbd_user *user);
+struct ksmbd_file *ksmbd_file_get(struct ksmbd_file *fp);
 void ksmbd_fd_put(struct ksmbd_work *work, struct ksmbd_file *fp);
 struct ksmbd_inode *ksmbd_inode_lookup_lock(struct dentry *d);
 void ksmbd_inode_put(struct ksmbd_inode *ci);
Signature · 1 line
2.53.0
author maintainer
#1530 lore raw

PATCH 1514/1815 ksmbd: serialize oplock close with pending break ownership

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit b0148dc5625dbfd50596ac63c7487c12e8a8ab03 ]

close may abort an in-flight oplock break while another breaker already holds an opinfo reference. Releasing pending_break wakes that waiter, but without serializing the close transition with bit acquisition it can become a new break owner through the test_and_set_bit() fast path. It can then overwrite OPLOCK_CLOSING with OPLOCK_ACK_WAIT and continue a break for a dying opinfo.

Make OPLOCK_CLOSING terminal once the opinfo is removed from the inode list. Serialize that transition, pending_break acquisition, and OPLOCK_ACK_WAIT setup with an opinfo state lock. A breaker which loses the race releases its ownership and returns -ENOENT. Explicitly wake pending_break waiters during close so they can observe the terminal state.

Also prevent ACK and timeout paths from replacing OPLOCK_CLOSING with OPLOCK_STATE_NONE.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/oplock.c  | 86 ++++++++++++++++++++++++++++++++++-------
 fs/smb/server/oplock.h  |  1 +
 fs/smb/server/smb2pdu.c | 12 ++++--
 3 files changed, 81 insertions(+), 18 deletions(-)
fs/smb/server/oplock.c +71 -15
index 7d77ee0cb953d..04dc572ed1bbf 100644
@@ -90,6 +90,7 @@ static struct oplock_info *alloc_opinfo(struct ksmbd_work *work,
 	opinfo->conn = ksmbd_conn_get(work->conn);
 	opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
 	opinfo->op_state = OPLOCK_STATE_NONE;
+	spin_lock_init(&opinfo->state_lock);
 	opinfo->pending_break = 0;
 	opinfo->fid = id;
 	opinfo->Tid = Tid;
@@ -546,14 +547,23 @@ void close_id_del_oplock(struct ksmbd_file *fp)
 	opinfo_del(opinfo);
 
 	rcu_assign_pointer(fp->f_opinfo, NULL);
-	if (opinfo->op_state == OPLOCK_ACK_WAIT) {
-		opinfo->op_state = OPLOCK_CLOSING;
-		wake_up_interruptible_all(&opinfo->oplock_q);
-		if (opinfo->is_lease) {
-			atomic_set(&opinfo->breaking_cnt, 0);
-			wake_up_interruptible_all(&opinfo->oplock_brk);
-		}
-	}
+	spin_lock(&opinfo->state_lock);
+	if (opinfo->op_state == OPLOCK_ACK_WAIT && opinfo->is_lease)
+		atomic_set(&opinfo->breaking_cnt, 0);
+	/*
+	 * An opinfo that has been removed from the inode list is terminal. Keep
+	 * this transition and releasing pending_break under state_lock. a breaker
+	 * takes the same lock before it acquires pending_break or sets ACK_WAIT.
+	 */
+	opinfo->op_state = OPLOCK_CLOSING;
+	clear_bit_unlock(0, &opinfo->pending_break);
+	spin_unlock(&opinfo->state_lock);
+	wake_up_interruptible_all(&opinfo->oplock_q);
+	if (opinfo->is_lease)
+		wake_up_interruptible_all(&opinfo->oplock_brk);
+	/* memory barrier is needed for wake_up_bit() */
+	smp_mb__after_atomic();
+	wake_up_bit(&opinfo->pending_break, 0);
 
 	opinfo_count_dec(fp);
 	atomic_dec(&opinfo->refcount);
@@ -735,12 +745,18 @@ static bool wait_for_break_ack(struct oplock_info *opinfo)
 
 	/* is this a timeout ? */
 	if (!rc) {
+		spin_lock(&opinfo->state_lock);
+		if (opinfo->op_state == OPLOCK_CLOSING) {
+			spin_unlock(&opinfo->state_lock);
+			return false;
+		}
 		if (opinfo->is_lease) {
 			opinfo->o_lease->state = SMB2_LEASE_NONE_LE;
 			lease_update_oplock_levels(opinfo->o_lease);
 		}
 		opinfo->level = SMB2_OPLOCK_LEVEL_NONE;
 		opinfo->op_state = OPLOCK_STATE_NONE;
+		spin_unlock(&opinfo->state_lock);
 		return true;
 	}
 
@@ -755,9 +771,35 @@ static void wake_up_oplock_break(struct oplock_info *opinfo)
 	wake_up_bit(&opinfo->pending_break, 0);
 }
 
+static bool oplock_break_set_ack_wait(struct oplock_info *opinfo)
+{
+	bool ret = false;
+
+	spin_lock(&opinfo->state_lock);
+	if (opinfo->op_state != OPLOCK_CLOSING) {
+		opinfo->op_state = OPLOCK_ACK_WAIT;
+		ret = true;
+	}
+	spin_unlock(&opinfo->state_lock);
+
+	return ret;
+}
+
 static int oplock_break_pending(struct oplock_info *opinfo, int req_op_level)
 {
-	while (test_and_set_bit(0, &opinfo->pending_break)) {
+	for (;;) {
+		bool closing;
+
+		spin_lock(&opinfo->state_lock);
+		closing = opinfo->op_state == OPLOCK_CLOSING;
+		if (!closing && !test_and_set_bit(0, &opinfo->pending_break)) {
+			spin_unlock(&opinfo->state_lock);
+			break;
+		}
+		spin_unlock(&opinfo->state_lock);
+		if (closing)
+			return -ENOENT;
+
 		if (opinfo->is_lease)
 			opinfo->o_lease->reuse_epoch = true;
 
@@ -766,9 +808,12 @@ static int oplock_break_pending(struct oplock_info *opinfo, int req_op_level)
 		/* Not immediately break to none. */
 		opinfo->open_trunc = 0;
 
-		if (opinfo->op_state == OPLOCK_CLOSING)
+		spin_lock(&opinfo->state_lock);
+		closing = opinfo->op_state == OPLOCK_CLOSING;
+		spin_unlock(&opinfo->state_lock);
+		if (closing)
 			return -ENOENT;
-		else if (opinfo->level <= req_op_level) {
+		if (opinfo->level <= req_op_level) {
 			if (opinfo->is_lease == false)
 				return 1;
 
@@ -1185,7 +1230,11 @@ static int oplock_break(struct oplock_info *brk_opinfo, struct ksmbd_inode *ci,
 
 		if (lease->state & (SMB2_LEASE_WRITE_CACHING_LE |
 				SMB2_LEASE_HANDLE_CACHING_LE)) {
-			brk_opinfo->op_state = OPLOCK_ACK_WAIT;
+			if (!oplock_break_set_ack_wait(brk_opinfo)) {
+				atomic_dec_if_positive(&brk_opinfo->breaking_cnt);
+				wake_up_oplock_break(brk_opinfo);
+				return -ENOENT;
+			}
 		} else
 			atomic_dec(&brk_opinfo->breaking_cnt);
 
@@ -1232,8 +1281,12 @@ static int oplock_break(struct oplock_info *brk_opinfo, struct ksmbd_inode *ci,
 			return err < 0 ? err : 0;
 
 		if (brk_opinfo->level == SMB2_OPLOCK_LEVEL_BATCH ||
-		    brk_opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
-			brk_opinfo->op_state = OPLOCK_ACK_WAIT;
+		    brk_opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
+			if (!oplock_break_set_ack_wait(brk_opinfo)) {
+				wake_up_oplock_break(brk_opinfo);
+				return -ENOENT;
+			}
+		}
 
 		/*
 		 * Keep a conflicting CREATE asynchronous while waiting for an
@@ -1800,7 +1853,10 @@ static void __smb_break_all_levII_oplock(struct ksmbd_work *work,
 
 		if (!brk_op->is_lease && !send_oplock_break) {
 			brk_op->level = SMB2_OPLOCK_LEVEL_NONE;
-			brk_op->op_state = OPLOCK_STATE_NONE;
+			spin_lock(&brk_op->state_lock);
+			if (brk_op->op_state != OPLOCK_CLOSING)
+				brk_op->op_state = OPLOCK_STATE_NONE;
+			spin_unlock(&brk_op->state_lock);
 		} else {
 			oplock_break(brk_op, ci,
 				     brk_op->is_lease && !is_trunc ?
fs/smb/server/oplock.h +1 -0
index 0ba93d54caca5..54785df84525e 100644
@@ -66,6 +66,7 @@ struct oplock_info {
 	struct ksmbd_file	*o_fp;
 	int                     level;
 	int                     op_state;
+	spinlock_t		state_lock;
 	unsigned long		pending_break;
 	u64			fid;
 	atomic_t		breaking_cnt;
fs/smb/server/smb2pdu.c +9 -3
index 194c948d3e251..dabf0a72a237a 100644
@@ -9975,7 +9975,10 @@ static void smb20_oplock_break_ack(struct ksmbd_work *work)
 	smb2_set_err_rsp(work);
 
 out:
-	opinfo->op_state = OPLOCK_STATE_NONE;
+	spin_lock(&opinfo->state_lock);
+	if (opinfo->op_state != OPLOCK_CLOSING)
+		opinfo->op_state = OPLOCK_STATE_NONE;
+	spin_unlock(&opinfo->state_lock);
 	wake_up_interruptible_all(&opinfo->oplock_q);
 out_no_state_change:
 	opinfo_put(opinfo);
@@ -10066,9 +10069,12 @@ static void smb21_lease_break_ack(struct ksmbd_work *work)
 	if (ret)
 		goto err_out;
 
-	opinfo->op_state = OPLOCK_STATE_NONE;
+	spin_lock(&opinfo->state_lock);
+	if (opinfo->op_state != OPLOCK_CLOSING)
+		opinfo->op_state = OPLOCK_STATE_NONE;
+	spin_unlock(&opinfo->state_lock);
 	wake_up_interruptible_all(&opinfo->oplock_q);
-	atomic_dec(&opinfo->breaking_cnt);
+	atomic_dec_if_positive(&opinfo->breaking_cnt);
 	wake_up_interruptible_all(&opinfo->oplock_brk);
 	opinfo_put(opinfo);
 	return;
Signature · 1 line
2.53.0
author maintainer
#1531 lore raw

PATCH 1515/1815 smb/server: fix null-ptr-deref in ksmbd_ipc_tree_connect_request()

In reply to Greg Kroah-Hartman

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

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

From: ZhangGuoDong <[email protected]>

[ Upstream commit d2ccf905f47d2344270749f4dfa905afcd3edeb0 ]

See the procedure below:

ksmbd_tree_conn_connect

    ksmbd_share_config_get
      share->name = kstrdup() // fail
      if (!test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) // false
      // do not check `share->name`
    ksmbd_ipc_tree_connect_request
      strlen(share->name) // null-ptr-deref
Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/mgmt/share_config.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
fs/smb/server/mgmt/share_config.c +6 -1
index 6f97f8d39657c..b4f56e7338659 100644
@@ -158,6 +158,11 @@ static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work,
 	atomic_set(&share->refcount, 1);
 	INIT_LIST_HEAD(&share->veto_list);
 	share->name = kstrdup(name, KSMBD_DEFAULT_GFP);
+	if (!share->name) {
+		kill_share(share);
+		share = NULL;
+		goto out;
+	}
 
 	if (!test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
 		int path_len = PATH_MAX;
@@ -203,7 +208,7 @@ static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work,
 				share->path = NULL;
 			}
 		}
-		if (ret || !share->name) {
+		if (ret) {
 			kill_share(share);
 			share = NULL;
 			goto out;
Signature · 1 line
2.53.0
author maintainer
#1532 lore raw

PATCH 1516/1815 smb/server: fix invalid pointer dereference in ksmbd_stop_durable_scavenger()

In reply to Greg Kroah-Hartman

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

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

From: ZhangGuoDong <[email protected]>

[ Upstream commit bef46b604732d83f8da29f782868de4d25bf972c ]

See the procedure below:

ksmbd_launch_ksmbd_durable_scavenger
durable_scavenger_running = true
server_conf.dh_task = kthread_run() // fail, dh_task is an ERR_PTR()

server_ctrl_handle_reset
ksmbd_stop_durable_scavenger kthread_stop(server_conf.dh_task) // invalid pointer

Fixes d484d621d40f ("ksmbd: add durable scavenger timer")
---
 fs/smb/server/vfs_cache.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/smb/server/vfs_cache.c +4 -1
index 0efef8c8176c2..460684624678f 100644
@@ -1499,9 +1499,12 @@ void ksmbd_launch_ksmbd_durable_scavenger(void)
 
 	server_conf.dh_task = kthread_run(ksmbd_durable_scavenger,
 				     (void *)NULL, "ksmbd-durable-scavenger");
-	if (IS_ERR(server_conf.dh_task))
+	if (IS_ERR(server_conf.dh_task)) {
 		pr_err("cannot start conn thread, err : %ld\n",
 		       PTR_ERR(server_conf.dh_task));
+		server_conf.dh_task = NULL;
+		durable_scavenger_running = false;
+	}
 	mutex_unlock(&durable_scavenger_lock);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1533 lore raw

PATCH 1517/1815 smb/server: abort initialization when proc setup fails

In reply to Greg Kroah-Hartman

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

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

From: ZhangGuoDong <[email protected]>

[ Upstream commit db97f3763727d652112ae70038d4e17b3ce277bb ]

ksmbd_server_init() calls ksmbd_proc_init() before creating the remaining proc entries and server subsystems. ksmbd_proc_init() tears down partial state on a procfs or percpu_counter allocation failure, but returns void, so ksmbd_server_init() continues as if the counters were usable.

Once userspace starts the server, server_ctrl_handle_init() calls ksmbd_proc_reset(), which reaches percpu_counter_set() with a NULL per-CPU counters pointer on SMP systems. The later ksmbd_proc_create() calls also receive a NULL parent and may create entries in the /proc root; ksmbd_proc_cleanup() cannot remove those entries because ksmbd_proc_fs is NULL.

Fixes b38f99c1217a ("ksmbd: add procfs interface for runtime monitoring and statistics")
---
 fs/smb/server/misc.h   |  4 ++--
 fs/smb/server/proc.c   | 13 ++++++++-----
 fs/smb/server/server.c |  4 +++-
 3 files changed, 13 insertions(+), 8 deletions(-)
fs/smb/server/misc.h +2 -2
index 3909104e18ad4..c7b063f571a7a 100644
@@ -43,7 +43,7 @@ struct ksmbd_const_name {
 	const char *name;
 };
 
-void ksmbd_proc_init(void);
+int ksmbd_proc_init(void);
 void ksmbd_proc_cleanup(void);
 void ksmbd_proc_reset(void);
 struct proc_dir_entry *ksmbd_proc_create(const char *name,
@@ -59,7 +59,7 @@ void ksmbd_proc_show_const_name(struct seq_file *m,
 				int count,
 				unsigned int const_value);
 #else
-static inline void ksmbd_proc_init(void) {}
+static inline int ksmbd_proc_init(void) { return 0; }
 static inline void ksmbd_proc_cleanup(void) {}
 static inline void ksmbd_proc_reset(void) {}
 #endif
fs/smb/server/proc.c +8 -5
index 101a2cc45a447..5c9f3f314dbe1 100644
@@ -106,14 +106,14 @@ void ksmbd_proc_reset(void)
 		percpu_counter_set(&ksmbd_counters.counters[i], 0);
 }
 
-void ksmbd_proc_init(void)
+int ksmbd_proc_init(void)
 {
 	int i;
-	int retval;
+	int retval = -ENOMEM;
 
 	ksmbd_proc_fs = proc_mkdir("fs/ksmbd", NULL);
 	if (!ksmbd_proc_fs)
-		return;
+		return retval;
 
 	if (!proc_mkdir_mode("sessions", 0400, ksmbd_proc_fs))
 		goto err_out;
@@ -124,11 +124,14 @@ void ksmbd_proc_init(void)
 			goto err_out;
 	}
 
-	if (!ksmbd_proc_create("server", proc_show_ksmbd_stats, NULL))
+	if (!ksmbd_proc_create("server", proc_show_ksmbd_stats, NULL)) {
+		retval = -ENOMEM;
 		goto err_out;
+	}
 
 	ksmbd_proc_reset();
-	return;
+	return 0;
 err_out:
 	ksmbd_proc_cleanup();
+	return retval;
 }
fs/smb/server/server.c +3 -1
index 95be17b797147..a67ecd765e5d2 100644
@@ -610,7 +610,9 @@ static int __init ksmbd_server_init(void)
 		return ret;
 	}
 
-	ksmbd_proc_init();
+	ret = ksmbd_proc_init();
+	if (ret)
+		goto err_unregister;
 	create_proc_sessions();
 
 	ksmbd_server_tcp_callbacks_init();
Signature · 1 line
2.53.0
author maintainer
#1534 lore raw

PATCH 1518/1815 smb/server: call ksmbd_proc_cleanup() on module init failure

In reply to Greg Kroah-Hartman

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

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

From: ZhangGuoDong <[email protected]>

[ Upstream commit f43cbe3b58ce989ce420c3bc875d48e7754c8aba ]

When a later initializer fails, the unwind chain releases resources created after procfs and then jumps directly to class_unregister(). Returning an error from module_init() leaves the proc tree and its per-CPU counters allocated.

Fixes b38f99c1217a ("ksmbd: add procfs interface for runtime monitoring and statistics")
---
 fs/smb/server/server.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
fs/smb/server/server.c +4 -2
index a67ecd765e5d2..c629a33bfa4a8 100644
@@ -619,11 +619,11 @@ static int __init ksmbd_server_init(void)
 
 	ret = server_conf_init();
 	if (ret)
-		goto err_unregister;
+		goto err_proc_cleanup;
 
 	ret = ksmbd_work_pool_init();
 	if (ret)
-		goto err_unregister;
+		goto err_proc_cleanup;
 
 	ret = ksmbd_init_file_cache();
 	if (ret)
@@ -669,6 +669,8 @@ static int __init ksmbd_server_init(void)
 	ksmbd_exit_file_cache();
 err_destroy_work_pools:
 	ksmbd_work_pool_destroy();
+err_proc_cleanup:
+	ksmbd_proc_cleanup();
 err_unregister:
 	class_unregister(&ksmbd_control_class);
 
Signature · 1 line
2.53.0
author maintainer
#1535 lore raw

PATCH 1519/1815 smb/server: preserve error status in smb2_handle_negotiate()

In reply to Greg Kroah-Hartman

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

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

From: ZhangGuoDong <[email protected]>

[ Upstream commit 73541bd2bab77e7e8e89b1edb5d342f4190dd4d0 ]

smb2_handle_negotiate() records specific failures such as STATUS_INVALID_PARAMETER or STATUS_NOT_SUPPORTED.

Fixes e2b76ab8b5c9 ("ksmbd: add support for read compound")
---
 fs/smb/server/smb2pdu.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/smb/server/smb2pdu.c +2 -2
index dabf0a72a237a..843a353b4f882 100644
@@ -1576,7 +1576,7 @@ int smb2_handle_negotiate(struct ksmbd_work *work)
 				    KSMBD_DEFAULT_GFP);
 		if (!conn->preauth_info) {
 			rc = -ENOMEM;
-			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
+			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
 			goto err_out;
 		}
 
@@ -1673,7 +1673,7 @@ int smb2_handle_negotiate(struct ksmbd_work *work)
 	ksmbd_conn_set_need_setup(conn);
 
 err_out:
-	if (rc)
+	if (rc && rsp->hdr.Status == STATUS_SUCCESS)
 		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
 
 	if (!rc)
Signature · 1 line
2.53.0
author maintainer
#1536 lore raw

PATCH 1520/1815 ksmbd: recognize replayed SMB2 lock sequences

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 5ce5227cd60b7213359e91837727ed1b6d457d49 ]

A server returns success without processing a lock request when a valid LockSequenceArray entry contains the same sequence number. The current verifier only invalidates mismatched entries, so matching requests are submitted to the VFS again and recorded as duplicate locks.

Make the verifier report matching sequences and skip lock processing for those replays. Also correct the field comment to describe the sequence and index bit layout used by the implementation and the protocol. Use the capabilities advertised by the server when deciding whether lock sequence verification applies to a multichannel connection.

Stable-dep-of: 29f74f0f2e6d ("ksmbd: defer publishing granted locks to prevent UAF/double-free race")

---
 fs/smb/common/smb2pdu.h |  4 ++--
 fs/smb/server/smb2pdu.c | 34 +++++++++++++++++++++++-----------
 2 files changed, 25 insertions(+), 13 deletions(-)
fs/smb/common/smb2pdu.h +2 -2
index e7ff52b8aba5f..37b660b2047b0 100644
@@ -847,8 +847,8 @@ struct smb2_lock_req {
 	__le16 StructureSize; /* Must be 48 */
 	__le16 LockCount;
 	/*
-	 * The least significant four bits are the index, the other 28 bits are
-	 * the lock sequence number (0 to 64). See MS-SMB2 2.2.26
+	 * The least significant four bits are the lock sequence number. The
+	 * other 28 bits are the index (0 to 64). See MS-SMB2 2.2.26.
 	 */
 	__le32 LockSequenceNumber;
 	__u64  PersistentFileId;
fs/smb/server/smb2pdu.c +23 -11
index 843a353b4f882..b8714628e1fc5 100644
@@ -786,31 +786,38 @@ static bool smb2_lock_sequence_applicable(struct ksmbd_work *work,
 {
 	return fp->is_resilient || fp->is_durable || fp->is_persistent ||
 	       (work->conn->dialect >= SMB30_PROT_ID &&
-		(work->conn->cli_cap & SMB2_GLOBAL_CAP_MULTI_CHANNEL));
+		(work->conn->vals->req_capabilities &
+		 SMB2_GLOBAL_CAP_MULTI_CHANNEL));
 }
 
-static void smb2_verify_lock_sequence(struct ksmbd_work *work,
-				      struct ksmbd_file *fp,
-				      struct smb2_lock_req *req)
+static bool smb2_verify_lock_sequence(struct ksmbd_work *work,
+				       struct ksmbd_file *fp,
+				       struct smb2_lock_req *req)
 {
 	u32 val, index;
 	u8 sequence;
+	bool replay = false;
 
 	if (work->conn->dialect == SMB20_PROT_ID ||
 	    !smb2_lock_sequence_applicable(work, fp))
-		return;
+		return false;
 
 	val = le32_to_cpu(req->LockSequenceNumber);
 	sequence = val & 0xf;
 	index = val >> 4;
 	if (!index || index > KSMBD_LOCK_SEQ_ARRAY_SIZE)
-		return;
+		return false;
 
 	spin_lock(&fp->f_lock);
-	if (fp->lock_seq[index - 1].valid &&
-	    fp->lock_seq[index - 1].sequence != sequence)
-		fp->lock_seq[index - 1].valid = false;
+	if (fp->lock_seq[index - 1].valid) {
+		if (fp->lock_seq[index - 1].sequence == sequence)
+			replay = true;
+		else
+			fp->lock_seq[index - 1].valid = false;
+	}
 	spin_unlock(&fp->f_lock);
+
+	return replay;
 }
 
 static void smb2_update_lock_sequence(struct ksmbd_work *work,
@@ -8547,6 +8554,7 @@ int smb2_lock(struct ksmbd_work *work)
 	LIST_HEAD(rollback_list);
 	int prior_lock = 0, bkt;
 	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
+	bool lock_replayed;
 
 	WORK_BUFFERS(work, req, rsp);
 
@@ -8579,7 +8587,9 @@ int smb2_lock(struct ksmbd_work *work)
 	if (err)
 		goto out2;
 
-	smb2_verify_lock_sequence(work, fp, req);
+	lock_replayed = smb2_verify_lock_sequence(work, fp, req);
+	if (lock_replayed)
+		goto lock_success;
 
 	filp = fp->filp;
 	lock_count = le16_to_cpu(req->LockCount);
@@ -8858,6 +8868,7 @@ int smb2_lock(struct ksmbd_work *work)
 	if (atomic_read(&fp->f_ci->op_count) > 1)
 		smb_break_all_oplock(work, fp);
 
+lock_success:
 	rsp->StructureSize = cpu_to_le16(4);
 	ksmbd_debug(SMB, "successful in taking lock\n");
 	rsp->hdr.Status = STATUS_SUCCESS;
@@ -8865,7 +8876,8 @@ int smb2_lock(struct ksmbd_work *work)
 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
 	if (err)
 		goto out;
-	smb2_update_lock_sequence(work, fp, req);
+	if (!lock_replayed)
+		smb2_update_lock_sequence(work, fp, req);
 
 	ksmbd_fd_put(work, fp);
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#1537 lore raw

PATCH 1521/1815 ksmbd: defer publishing granted locks to prevent UAF/double-free race

In reply to Greg Kroah-Hartman

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

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

From: Ilan Dudnik <[email protected]>

[ Upstream commit 29f74f0f2e6df3b393b7b66e810136d0c64e3c59 ]

In smb2_lock(), mid-batch granted locks are published to connection-wide (conn->lock_list) and file-wide (fp->lock_list) lists immediately upon vfs_lock_file() success, while also remaining tracked on the stack-local rollback_list.

If a subsequent element in the same SMB2_LOCK request array fails validation or execution, the thread jumps to out: and walks rollback_list to undo previously granted locks. However, because the granted lock was already published to conn->lock_list, a concurrent UNLOCK request on the same connection can find the lock object and kfree() it before the rollback loop executes.

When the granting thread subsequently walks rollback_list, it dereferences and frees the already-freed ksmbd_lock structure, resulting in a Use-After-Free and Double-Free (on both ksmbd_lock and struct file_lock).

Fix this by deferring the publication of granted locks to conn->lock_list and fp->lock_list until after the entire array of lock elements has been processed without error. Mid-batch grants remain tracked exclusively on the request-local rollback_list until the whole batch succeeds, eliminating the race window.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smb2pdu.c | 33 ++++++++++++++++-----------------
 1 file changed, 16 insertions(+), 17 deletions(-)
fs/smb/server/smb2pdu.c +16 -17
index b8714628e1fc5..5e99c48fa0dc4 100644
@@ -8845,16 +8845,10 @@ int smb2_lock(struct ksmbd_work *work)
 				rsp->hdr.Status =
 					STATUS_RANGE_NOT_LOCKED;
 				kfree(smb_lock);
-				goto out2;
+				/* rollback_list may still hold earlier grants */
+				goto out;
 			} else if (!rc) {
 				list_add(&smb_lock->llist, &rollback_list);
-				smb_lock->conn = ksmbd_conn_get(work->conn);
-				spin_lock(&work->conn->llist_lock);
-				list_add_tail(&smb_lock->clist,
-					      &work->conn->lock_list);
-				list_add_tail(&smb_lock->flist,
-					      &fp->lock_list);
-				spin_unlock(&work->conn->llist_lock);
 				ksmbd_debug(SMB, "successful in taking lock\n");
 			} else {
 				locks_free_lock(flock);
@@ -8876,6 +8870,20 @@ int smb2_lock(struct ksmbd_work *work)
 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
 	if (err)
 		goto out;
+
+	/* publish only once the whole batch has committed */
+	if (!list_empty(&rollback_list)) {
+		spin_lock(&work->conn->llist_lock);
+		list_for_each_entry(smb_lock, &rollback_list, llist) {
+			smb_lock->conn = ksmbd_conn_get(work->conn);
+			list_add_tail(&smb_lock->clist,
+				      &work->conn->lock_list);
+			list_add_tail(&smb_lock->flist,
+				      &fp->lock_list);
+		}
+		spin_unlock(&work->conn->llist_lock);
+	}
+
 	if (!lock_replayed)
 		smb2_update_lock_sequence(work, fp, req);
 
@@ -8906,15 +8914,6 @@ int smb2_lock(struct ksmbd_work *work)
 		}
 
 		list_del(&smb_lock->llist);
-		conn = smb_lock->conn;
-		spin_lock(&conn->llist_lock);
-		if (!list_empty(&smb_lock->flist))
-			list_del(&smb_lock->flist);
-		list_del(&smb_lock->clist);
-		smb_lock->conn = NULL;
-		spin_unlock(&conn->llist_lock);
-		ksmbd_conn_put(conn);
-
 		locks_free_lock(smb_lock->fl);
 		if (rlock)
 			locks_free_lock(rlock);
Signature · 1 line
2.53.0
author maintainer
#1538 lore raw

PATCH 1522/1815 erofs: fix interlaced ztailpacking pclusters

In reply to Greg Kroah-Hartman

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

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

From: Gao Xiang <[email protected]>

[ Upstream commit 862427ebb81d1f6abbf74d799790e1694b37b187 ]

On-disk sizes of interlaced pclusters should be block-aligned, and ztailpacking interlaced pclusters should be invalid at all.

Currently, mkfs.erofs won't generate any interlaced pcluster with ztailpacking enabled, so this doesn't affect any existing valid filesystems.

However, crafted images can contain invalid interlaced ztailpacking pclusters, resulting in an out-of-bounds read from a kmap'd page and copying irrelevant kernel memory into userspace-visible page cache.

Fixes fdffc091e6f9 ("erofs: support interlaced uncompressed data for compressed files")
---
 fs/erofs/decompressor.c | 1 +
 fs/erofs/zmap.c         | 3 ++-
 2 files changed, 3 insertions(+), 1 deletion(-)
fs/erofs/decompressor.c +1 -0
index 3c54e95964c9f..27caf4bebddc3 100644
@@ -299,6 +299,7 @@ static const char *z_erofs_transform_plain(struct z_erofs_decompress_req *rq,
 		return ERR_PTR(-EOPNOTSUPP);
 	if (rq->alg == Z_EROFS_COMPRESSION_INTERLACED) {
 		cur = bs - (rq->pageofs_out & (bs - 1));
+		DBG_BUGON(rq->pageofs_in & (bs - 1));
 		pi = (rq->pageofs_in + rq->inputsize - cur) & ~PAGE_MASK;
 		cur = min(cur, rq->outputsize);
 		if (cur && rq->out[0]) {
fs/erofs/zmap.c +2 -1
index 5811556a7b71f..b5411b579fd90 100644
@@ -483,7 +483,8 @@ static int z_erofs_map_blocks_fo(struct inode *inode,
 	}
 
 	if (m.headtype == Z_EROFS_LCLUSTER_TYPE_PLAIN) {
-		if (vi->z_advise & Z_EROFS_ADVISE_INTERLACED_PCLUSTER)
+		if ((vi->z_advise & Z_EROFS_ADVISE_INTERLACED_PCLUSTER) &&
+		    !(map->m_flags & EROFS_MAP_META))
 			map->m_algorithmformat = Z_EROFS_COMPRESSION_INTERLACED;
 		else
 			map->m_algorithmformat = Z_EROFS_COMPRESSION_SHIFTED;
Signature · 1 line
2.53.0
author maintainer
#1539 lore raw

PATCH 1523/1815 erofs: guard on-disk algorithm IDs against Z_EROFS_COMPRESSION_MAX

In reply to Greg Kroah-Hartman

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

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

From: Gao Xiang <[email protected]>

[ Upstream commit 6847d4d1a24a686ca6c8a0f68501a984f9a0d059 ]

All on-disk algorithm IDs should be validated against supported Z_EROFS_COMPRESSION_MAX.

This includes a partial revert of a previous commit and also adds validation for encoded extents.

Fixes 131897c65e2b ("erofs: fix invalid algorithm for encoded extents")
---
 fs/erofs/internal.h |  2 +-
 fs/erofs/zmap.c     | 35 +++++++++++++++++++++--------------
 2 files changed, 22 insertions(+), 15 deletions(-)
fs/erofs/internal.h +1 -1
index 57bd21859c65d..bee2f50c8488f 100644
@@ -269,7 +269,7 @@ struct erofs_inode {
 #ifdef CONFIG_EROFS_FS_ZIP
 		struct {
 			unsigned short z_advise;
-			unsigned char  z_algorithmtype[2];
+			unsigned char  z_algofmt[2];
 			unsigned char  z_lclusterbits;
 			union {
 				u64    z_tailextent_headlcn;
fs/erofs/zmap.c +21 -14
index b5411b579fd90..b316a50efe383 100644
@@ -488,10 +488,9 @@ static int z_erofs_map_blocks_fo(struct inode *inode,
 			map->m_algorithmformat = Z_EROFS_COMPRESSION_INTERLACED;
 		else
 			map->m_algorithmformat = Z_EROFS_COMPRESSION_SHIFTED;
-	} else if (m.headtype == Z_EROFS_LCLUSTER_TYPE_HEAD2) {
-		map->m_algorithmformat = vi->z_algorithmtype[1];
 	} else {
-		map->m_algorithmformat = vi->z_algorithmtype[0];
+		map->m_algorithmformat =
+			vi->z_algofmt[m.headtype == Z_EROFS_LCLUSTER_TYPE_HEAD2];
 	}
 
 	if ((flags & EROFS_GET_BLOCKS_FIEMAP) ||
@@ -605,9 +604,14 @@ static int z_erofs_map_blocks_ext(struct inode *inode,
 			if (map->m_plen & Z_EROFS_EXTENT_PLEN_PARTIAL)
 				map->m_flags |= EROFS_MAP_PARTIAL_REF;
 			map->m_plen &= Z_EROFS_EXTENT_PLEN_MASK;
-			if (fmt)
-				map->m_algorithmformat = fmt - 1;
-			else if (interlaced && !((map->m_pa | map->m_plen) & bmask))
+			if (fmt) {
+				map->m_algorithmformat = --fmt;
+				if (fmt >= Z_EROFS_COMPRESSION_MAX) {
+					erofs_err(sb, "unknown algorithm %d @ pos %llu for nid %llu, please upgrade kernel",
+						  fmt, map->m_la, vi->nid);
+					return -EOPNOTSUPP;
+				}
+			} else if (interlaced && !((map->m_pa | map->m_plen) & bmask))
 				map->m_algorithmformat =
 					Z_EROFS_COMPRESSION_INTERLACED;
 			else
@@ -625,7 +629,7 @@ static int z_erofs_fill_inode(struct inode *inode, struct erofs_map_blocks *map)
 	struct super_block *const sb = inode->i_sb;
 	struct z_erofs_map_header *h;
 	erofs_off_t pos;
-	int err = 0;
+	int err = 0, nr;
 
 	if (test_bit(EROFS_I_Z_INITED_BIT, &vi->flags)) {
 		/*
@@ -668,12 +672,19 @@ static int z_erofs_fill_inode(struct inode *inode, struct erofs_map_blocks *map)
 		goto done;
 	}
 
-	vi->z_algorithmtype[0] = h->h_algorithmtype & 15;
-	vi->z_algorithmtype[1] = h->h_algorithmtype >> 4;
 	if (vi->z_advise & Z_EROFS_ADVISE_FRAGMENT_PCLUSTER)
 		vi->z_fragmentoff = le32_to_cpu(h->h_fragmentoff);
 	else if (vi->z_advise & Z_EROFS_ADVISE_INLINE_PCLUSTER)
 		vi->z_idata_size = le16_to_cpu(h->h_idata_size);
+	for (nr = 0; nr < 2; ++nr) {
+		vi->z_algofmt[nr] = (h->h_algorithmtype >> (4 * nr)) & 15;
+		if (vi->z_algofmt[nr] >= Z_EROFS_COMPRESSION_MAX) {
+			erofs_err(sb, "unknown HEAD%u format %u for nid %llu, please upgrade kernel",
+				  nr + 1, vi->z_algofmt[nr], vi->nid);
+			err = -EOPNOTSUPP;
+			goto out_unlock;
+		}
+	}
 
 	if (!erofs_sb_has_big_pcluster(EROFS_SB(sb)) &&
 	    vi->z_advise & (Z_EROFS_ADVISE_BIG_PCLUSTER_1 |
@@ -721,12 +732,8 @@ static int z_erofs_map_sanity_check(struct inode *inode,
 
 	if (!(map->m_flags & EROFS_MAP_MAPPED))
 		return 0;
-	if (unlikely(map->m_algorithmformat >= Z_EROFS_COMPRESSION_RUNTIME_MAX)) {
-		erofs_err(inode->i_sb, "unknown algorithm %d @ pos %llu for nid %llu, please upgrade kernel",
-			  map->m_algorithmformat, map->m_la, EROFS_I(inode)->nid);
-		return -EOPNOTSUPP;
-	}
 
+	DBG_BUGON(map->m_algorithmformat >= Z_EROFS_COMPRESSION_RUNTIME_MAX);
 	if (map->m_algorithmformat < Z_EROFS_COMPRESSION_MAX) {
 		if (!(sbi->available_compr_algs & BIT(map->m_algorithmformat))) {
 			erofs_err(inode->i_sb, "inconsistent algorithmtype %u for nid %llu",
Signature · 1 line
2.53.0
author maintainer
#1540 lore raw

PATCH 1524/1815 objtool/klp: Fix vmlinux klp relocations for EXPORT_SYMBOL_FOR_MODULES()

In reply to Greg Kroah-Hartman

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

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

From: Josh Poimboeuf <[email protected]>

[ Upstream commit d8a2860b4a366bfa8acb3d64da2c546ea26d2091 ]

When a module function references a vmlinux symbol which is exported with EXPORT_SYMBOL_FOR_MODULES(), a patch to that function needs to use a klp reloc.

Currently, livepatch fails to load such a module:

livepatch: invalid access to vmlinux symbol 'get_task_policy' from module-specific livepatch relocation section
livepatch: failed to initialize patch 'livepatch_test' for module 'testmod' (-22)
livepatch: patch 'livepatch_test' failed for module 'testmod', refusing to load module 'testmod'

klp diff puts all klp relocs in __klp_relocs.<patched object>, so post-link names the section .klp.rela.<patched object>.<secname>, which the kernel rejects for vmlinux symbols.

Commit 07f14d6af9d77 ("objtool/klp: Fix cross-module klp relocation section naming") changed the meaning of objname in the klp rela section name to be where the referenced symbol is referenced rather than where it lives. That premise only holds for symbols in a module: the relocs get applied when the patched module gets patched, and the module dependency guarantees the referenced module is loaded by then.

A vmlinux symbol needs the opposite. It's always resolvable, and it has to be applied when the patch module loads, before the module loader initializes the patch module's special sections, which may reference it. That's why livepatch rejects vmlinux symbols in module-specific sections.

Use "vmlinux" as the section objname when the referenced symbol lives in vmlinux. This moves such klp relocs from .klp.rela.kvm..text to .klp.rela.vmlinux..text.

---
 tools/objtool/include/objtool/klp.h |  5 +++--
 tools/objtool/klp-diff.c            | 31 +++++++++++++++++++----------
 2 files changed, 23 insertions(+), 13 deletions(-)
tools/objtool/include/objtool/klp.h +3 -2
index 646d8e1f12eff..c57775d78c71e 100644
@@ -20,8 +20,9 @@
  * SHF_RELA_LIVEPATCH, nor does it support having two RELA sections for a
  * single PROGBITS section.
  *
- * "objname" is the name of the object being patched ("vmlinux" or a module
- * name).  post-link uses it to name the resulting
+ * "objname" is the object whose loading gates the relocation: "vmlinux" for
+ * references to vmlinux symbols, otherwise the name of the module being
+ * patched.  post-link uses it to name the resulting
  * .klp.rela.objname.section_name sections.
  */
 #define KLP_RELOCS_SEC	"__klp_relocs"
tools/objtool/klp-diff.c +20 -11
index ec2e7ae41767f..291ada0aa288d 100644
@@ -1320,13 +1320,14 @@ static int clone_reloc_klp(struct elfs *e, struct reloc *patched_reloc,
 			   struct section *sec, unsigned long offset,
 			   struct export *export)
 {
+	const char *sym_modname, *sym_orig_name, *sec_objname;
 	struct symbol *patched_sym = patched_reloc->sym;
 	s64 addend = reloc_addend(patched_reloc);
-	const char *sym_modname, *sym_orig_name;
-	static struct section *klp_relocs;
 	char tombstone_name[SYM_NAME_LEN];
 	struct symbol *sym, *klp_sym;
 	unsigned long klp_reloc_off;
+	struct section *klp_relocs;
+	char sec_name[SEC_NAME_LEN];
 	char sym_name[SYM_NAME_LEN];
 	struct klp_reloc klp_reloc;
 	unsigned long sympos;
@@ -1408,20 +1409,28 @@ static int clone_reloc_klp(struct elfs *e, struct reloc *patched_reloc,
 	 * This intermediate step is necessary to prevent corruption by the
 	 * linker, which doesn't know how to properly handle two rela sections
 	 * applying to the same base section.
+	 *
+	 * The objname decides when the reloc gets applied.  A reference to a
+	 * vmlinux symbol goes in the vmlinux section so it gets applied when
+	 * the patch module loads.  Everything else goes in the patched
+	 * object's section, applied when the patched module is loaded.
 	 */
 
-	if (!klp_relocs) {
-		const char *objname = find_modname(e);
-		char sec_name[SEC_NAME_LEN];
-
-		if (!objname)
+	if (!strcmp(sym_modname, "vmlinux")) {
+		sec_objname = "vmlinux";
+	} else {
+		sec_objname = find_modname(e);
+		if (!sec_objname)
 			return -1;
+	}
 
-		/* section format: __klp_relocs.objname */
-		if (snprintf_check(sec_name, SEC_NAME_LEN,
-				   KLP_RELOCS_SEC ".%s", objname))
-			return -1;
+	/* section format: __klp_relocs.objname */
+	if (snprintf_check(sec_name, SEC_NAME_LEN,
+			   KLP_RELOCS_SEC ".%s", sec_objname))
+		return -1;
 
+	klp_relocs = find_section_by_name(e->out, sec_name);
+	if (!klp_relocs) {
 		klp_relocs = elf_create_section(e->out, sec_name, 0,
 						0, SHT_PROGBITS, 8, SHF_ALLOC);
 		if (!klp_relocs)
Signature · 1 line
2.53.0
author maintainer
#1541 lore raw

PATCH 1525/1815 lwt_bpf: Restore reserved headroom after xmit program

In reply to Greg Kroah-Hartman

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

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

From: Junseo Lim <[email protected]>

[ Upstream commit 5fe7007aed9ad069b2bd77e5d0c875c64f5c0269 ]

ip_finish_output2() expands an skb to LL_RESERVED_SPACE(dev) before LWT xmit. An LWT_XMIT BPF program can then modify the skb head and still return BPF_OK, so bpf_xmit() rechecks the remaining headroom before the skb continues to neighbour output.

That recheck uses dst->dev->hard_header_len. This is not enough for the neighbour cached-header path: neigh_hh_output() copies the cached hardware header using the aligned hh_cache size, HH_DATA_MOD for short headers or HH_DATA_ALIGN(hh_len) otherwise.

On Ethernet, hard_header_len is 14 but the cached copy needs 16 bytes. If an LWT_XMIT BPF program calls bpf_skb_change_head(skb, 1, 0), the skb can still have 15 bytes of headroom after the program. The existing check accepts that, after which neigh_hh_output() hits its headroom warning and drops the skb.

Use LL_RESERVED_SPACE(dst->dev) in the post-BPF headroom check to match the reservation made before LWT xmit.

---
 net/core/lwt_bpf.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
net/core/lwt_bpf.c +9 -6
index 652952d416f23..da49364ec63de 100644
@@ -167,10 +167,10 @@ static int bpf_output(struct net *net, struct sock *sk, struct sk_buff *skb)
 	return dst->lwtstate->orig_output(net, sk, skb);
 }
 
-static int xmit_check_hhlen(struct sk_buff *skb, int hh_len)
+static int xmit_check_headroom(struct sk_buff *skb, int hroom)
 {
-	if (skb_headroom(skb) < hh_len) {
-		int nhead = HH_DATA_ALIGN(hh_len - skb_headroom(skb));
+	if (skb_headroom(skb) < hroom) {
+		int nhead = hroom - skb_headroom(skb);
 
 		if (pskb_expand_head(skb, nhead, 0, GFP_ATOMIC))
 			return -ENOMEM;
@@ -282,7 +282,7 @@ static int bpf_xmit(struct sk_buff *skb)
 
 	bpf = bpf_lwt_lwtunnel(dst->lwtstate);
 	if (bpf->xmit.prog) {
-		int hh_len = dst->dev->hard_header_len;
+		int hroom = LL_RESERVED_SPACE(dst->dev);
 		__be16 proto = skb->protocol;
 		int ret;
 
@@ -298,9 +298,12 @@ static int bpf_xmit(struct sk_buff *skb)
 				return -EINVAL;
 			}
 			/* If the header was expanded, headroom might be too
-			 * small for L2 header to come, expand as needed.
+			 * small for the L2 header to come, expand as needed.
+			 * neigh_hh_output() copies the cached header in
+			 * HH_DATA_MOD aligned chunks, so match the reservation
+			 * made before LWT xmit.
 			 */
-			ret = xmit_check_hhlen(skb, hh_len);
+			ret = xmit_check_headroom(skb, hroom);
 			if (unlikely(ret))
 				return ret;
 
Signature · 1 line
2.53.0
author maintainer
#1542 lore raw

PATCH 1526/1815 erofs: fix unused pcluster_pools for higher page sizes

In reply to Greg Kroah-Hartman

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

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

From: Ojaswin Mujoo <[email protected]>

[ Upstream commit 988c3c186c730590a71df8adc1424c5578ef8bae ]

pcluster_pool[] hardcodes {1,4,16,64,128,Z_EROFS_PCLUSTER_MAX_PAGES+1}, but the assumption of Z_EROFS_PCLUSTER_MAX_PAGES == 256 is only right for 4k page sizes. For higher page sizes like 16k or 64k, This results in us ending up with clusters bigger than what we will ever use, since we only support upto 1MB of compressed data. For example, on 64k page size we will only ever use clusters with nrpages= 1, 4 and 17.

This patch fixes the allocation for such higher pages sizes by adding some compile time checks.

Below are the clusters created right after boot on a 64KB page size machine

$cat /proc/slabinfo | grep pcluster | cut -d" " -f1:

Before the patch:

erofs_pcluster-1
erofs_pcluster-4
erofs_pcluster-16
erofs_pcluster-17
erofs_pcluster-64
erofs_pcluster-128

After the patch:

erofs_pcluster-1
erofs_pcluster-4
erofs_pcluster-17

Fixes 9f6cc76e6ff0 ("erofs: introduce physical cluster slab pools")
---
 fs/erofs/zdata.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
fs/erofs/zdata.c +11 -1
index 74520e9102596..0e9cac8ee12d3 100644
@@ -128,7 +128,17 @@ struct z_erofs_pcluster_slab {
 #define _PCLP(n) { .maxpages = n }
 
 static struct z_erofs_pcluster_slab pcluster_pool[] __read_mostly = {
-	_PCLP(1), _PCLP(4), _PCLP(16), _PCLP(64), _PCLP(128),
+	_PCLP(1),
+	_PCLP(4),
+#if Z_EROFS_PCLUSTER_MAX_PAGES > 16
+	_PCLP(16),
+#endif
+#if Z_EROFS_PCLUSTER_MAX_PAGES > 64
+	_PCLP(64),
+#endif
+#if Z_EROFS_PCLUSTER_MAX_PAGES > 128
+	_PCLP(128),
+#endif
 	_PCLP(Z_EROFS_PCLUSTER_MAX_PAGES + 1)
 };
 
Signature · 1 line
2.53.0
author maintainer
#1543 lore raw

PATCH 1527/1815 bpf: Disallow bpf_{g,s}etsockopt() in cgroup UNIX getname hooks

In reply to Greg Kroah-Hartman

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

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

From: Junseo Lim <[email protected]>

[ Upstream commit 84473a7e1813a2da7b759ab1d098a84998c8d3f5 ]

_bpf_setsockopt() and _bpf_getsockopt() call sock_owned_by_me() for full sockets, so these helpers expect the socket lock to be held.

BPF_CGROUP_UNIX_GETPEERNAME and BPF_CGROUP_UNIX_GETSOCKNAME run BPF programs without acquiring the socket lock. A program attached to either hook can therefore trigger the sock_owned_by_me() warning by calling bpf_setsockopt() or bpf_getsockopt().

Disallow bpf_setsockopt() and bpf_getsockopt() for CGROUP_UNIX_GETPEERNAME and CGROUP_UNIX_GETSOCKNAME.

---
 net/core/filter.c | 4 ----
 1 file changed, 4 deletions(-)
net/core/filter.c +0 -4
index 16845987b2449..1e80a52ef86d0 100644
@@ -8350,10 +8350,8 @@ sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
 		case BPF_CGROUP_UNIX_SENDMSG:
 		case BPF_CGROUP_INET4_GETPEERNAME:
 		case BPF_CGROUP_INET6_GETPEERNAME:
-		case BPF_CGROUP_UNIX_GETPEERNAME:
 		case BPF_CGROUP_INET4_GETSOCKNAME:
 		case BPF_CGROUP_INET6_GETSOCKNAME:
-		case BPF_CGROUP_UNIX_GETSOCKNAME:
 			return &bpf_sock_addr_setsockopt_proto;
 		default:
 			return NULL;
@@ -8373,10 +8371,8 @@ sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
 		case BPF_CGROUP_UNIX_SENDMSG:
 		case BPF_CGROUP_INET4_GETPEERNAME:
 		case BPF_CGROUP_INET6_GETPEERNAME:
-		case BPF_CGROUP_UNIX_GETPEERNAME:
 		case BPF_CGROUP_INET4_GETSOCKNAME:
 		case BPF_CGROUP_INET6_GETSOCKNAME:
-		case BPF_CGROUP_UNIX_GETSOCKNAME:
 			return &bpf_sock_addr_getsockopt_proto;
 		default:
 			return NULL;
Signature · 1 line
2.53.0
author maintainer
#1544 lore raw

PATCH 1528/1815 m68k: nfcon: Do not call console_is_registered() in nfcon_device()

In reply to Greg Kroah-Hartman

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

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

From: Andreas Schwab <[email protected]>

[ Upstream commit 2f8e3cad53b5c36ab0ed5d3195bfc55c59ea61a5 ]

Since 7c2af0f634f1 ("tty: tty_io: use console_list_lock for list synchronization") show_cons_active() calls the .device() method under the console_list_lock, but console_is_registered() tries to acquire console_list_lock as well, causing a deadlock. It should not be necessary to check console_is_registered() here since the function should not be called in the fist place when the console is not registered.

Fixes 7c2af0f634f1 ("tty: tty_io: use console_list_lock for list synchronization")
---
 arch/m68k/emu/nfcon.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/m68k/emu/nfcon.c +1 -1
index d41260672e24b..f4657d9f4f153 100644
@@ -49,7 +49,7 @@ static void nfcon_write(struct console *con, const char *str,
 static struct tty_driver *nfcon_device(struct console *con, int *index)
 {
 	*index = 0;
-	return console_is_registered(con) ? nfcon_tty_driver : NULL;
+	return nfcon_tty_driver;
 }
 
 static struct console nf_console = {
Signature · 1 line
2.53.0
author maintainer
#1545 lore raw

PATCH 1529/1815 bpf: Reject negative optlen in cgroup getsockopt hook

In reply to Greg Kroah-Hartman

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

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

From: Junseo Lim <[email protected]>

[ Upstream commit 1b5aacd5b2419b0790e955e466d389a61c79b4b1 ]

A cgroup getsockopt BPF program can shrink ctx->optlen after the kernel getsockopt handler has run. The kernel-buffer variant, used by TCP_ZEROCOPY_RECEIVE, only rejects values larger than the original length.

If BPF writes a negative optlen, that value is accepted and propagated back to the TCP getsockopt code. It can then be passed to copy_to_sockptr() as a size_t and trigger the hardened usercopy bytes > INT_MAX warning.

Reject negative ctx.optlen in __cgroup_bpf_run_filter_getsockopt_kern(), matching the lower-bound validation already present in the sockptr-based getsockopt hook.

---
 kernel/bpf/cgroup.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/bpf/cgroup.c +1 -1
index 31c63ff276fa7..44068bdd4f759 100644
@@ -2260,7 +2260,7 @@ int __cgroup_bpf_run_filter_getsockopt_kern(struct sock *sk, int level,
 	if (ret < 0)
 		return ret;
 
-	if (ctx.optlen > *optlen)
+	if (ctx.optlen > *optlen || ctx.optlen < 0)
 		return -EFAULT;
 
 	/* BPF programs can shrink the buffer, export the modifications.
Signature · 1 line
2.53.0
author maintainer
#1546 lore raw

PATCH 1530/1815 ksmbd: safely discard unregistered deferred locks

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 054bcca4cd9f00719b01f7108b51a2168fb94f15 ]

When vfs_lock_file() defers a lock, smb2_lock() puts its ksmbd_lock on rollback_list before allocating and registering the asynchronous work. If either operation fails, rollback assumes that smb_lock->conn is initialized and dereferences NULL. The deferred file_lock also remains linked into the VFS blocked-lock state while it is freed.

Keep the lock off rollback_list until async setup succeeds. On setup failures, explicitly unblock and wake the deferred lock before freeing it and its ksmbd wrapper.

Stable-dep-of: 215e8816b1ac ("ksmbd: detach blocked lock requests before freeing")

---
 fs/smb/server/smb2pdu.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +12 -1
index 5e99c48fa0dc4..42ca6125a510c 100644
@@ -8522,6 +8522,13 @@ static void smb2_remove_blocked_lock(void **argv)
 	locks_wake_up(flock);
 }
 
+static void smb2_free_blocked_lock(struct file_lock *flock)
+{
+	ksmbd_vfs_posix_lock_unblock(flock);
+	locks_wake_up(flock);
+	locks_free_lock(flock);
+}
+
 static inline bool lock_defer_pending(struct file_lock *fl)
 {
 	/* check pending lock waiters */
@@ -8796,11 +8803,12 @@ int smb2_lock(struct ksmbd_work *work)
 
 				ksmbd_debug(SMB,
 					    "would have to wait for getting lock\n");
-				list_add(&smb_lock->llist, &rollback_list);
 
 				argv = kmalloc(sizeof(void *), KSMBD_DEFAULT_GFP);
 				if (!argv) {
 					err = -ENOMEM;
+					smb2_free_blocked_lock(flock);
+					kfree(smb_lock);
 					goto out;
 				}
 				argv[0] = flock;
@@ -8811,8 +8819,11 @@ int smb2_lock(struct ksmbd_work *work)
 				if (rc) {
 					kfree(argv);
 					err = -ENOMEM;
+					smb2_free_blocked_lock(flock);
+					kfree(smb_lock);
 					goto out;
 				}
+				list_add(&smb_lock->llist, &rollback_list);
 				spin_lock(&fp->f_lock);
 				list_add(&work->fp_entry, &fp->blocked_works);
 				spin_unlock(&fp->f_lock);
Signature · 1 line
2.53.0
author maintainer
#1547 lore raw

PATCH 1531/1815 ksmbd: detach blocked lock requests before freeing

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 215e8816b1ac25176d911abb8704390413ccee4b ]

A file_lock retained by ksmbd for byte-range lock bookkeeping can still be part of the VFS blocked-request graph. In particular, the VFS can chain a new waiter below an already blocked request through flc_blocked_requests. The ksmbd_file reference count does not cover that graph.

Both __ksmbd_close_fd() and the cross-request unlock path free these retained file_lock objects directly. If a dependent waiter is still attached, locks_release_private() hits BUG_ON(!list_empty(&flc->flc_blocked_requests)). The same lifetime mismatch can leave a freed ksmbd_lock reachable through its request-local llist.

Detach the file_lock from the blocked-request graph before freeing it in the close, cross-request unlock, and rollback paths. locks_delete_block() also wakes requests chained below the object. Remove llist when a completed lock is published so a globally visible ksmbd_lock no longer points into the submitting worker's stack.

Fixes d63528eb0d43 ("ksmbd: free ksmbd_lock when file is closed")
---
 fs/smb/server/smb2pdu.c   | 17 ++++++++++++-----
 fs/smb/server/vfs_cache.c |  8 +++++---
 2 files changed, 17 insertions(+), 8 deletions(-)
fs/smb/server/smb2pdu.c +12 -5
index 42ca6125a510c..534416e2b599c 100644
@@ -8522,6 +8522,12 @@ static void smb2_remove_blocked_lock(void **argv)
 	locks_wake_up(flock);
 }
 
+static void smb2_free_lock(struct file_lock *flock)
+{
+	ksmbd_vfs_posix_lock_unblock(flock);
+	locks_free_lock(flock);
+}
+
 static void smb2_free_blocked_lock(struct file_lock *flock)
 {
 	ksmbd_vfs_posix_lock_unblock(flock);
@@ -8714,14 +8720,14 @@ int smb2_lock(struct ksmbd_work *work)
 					    cmp_lock->end == smb_lock->end &&
 					    !lock_defer_pending(cmp_lock->fl)) {
 						nolock = 0;
-						list_del(&cmp_lock->flist);
-						list_del(&cmp_lock->clist);
+						list_del_init(&cmp_lock->flist);
+						list_del_init(&cmp_lock->clist);
 						cmp_lock->conn = NULL;
 						spin_unlock(&conn->llist_lock);
 						up_read(&conn_list_lock);
 
 						ksmbd_conn_put(conn);
-						locks_free_lock(cmp_lock->fl);
+						smb2_free_lock(cmp_lock->fl);
 						kfree(cmp_lock);
 						goto out_check_cl;
 					}
@@ -8885,7 +8891,8 @@ int smb2_lock(struct ksmbd_work *work)
 	/* publish only once the whole batch has committed */
 	if (!list_empty(&rollback_list)) {
 		spin_lock(&work->conn->llist_lock);
-		list_for_each_entry(smb_lock, &rollback_list, llist) {
+		list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
+			list_del_init(&smb_lock->llist);
 			smb_lock->conn = ksmbd_conn_get(work->conn);
 			list_add_tail(&smb_lock->clist,
 				      &work->conn->lock_list);
@@ -8925,7 +8932,7 @@ int smb2_lock(struct ksmbd_work *work)
 		}
 
 		list_del(&smb_lock->llist);
-		locks_free_lock(smb_lock->fl);
+		smb2_free_lock(smb_lock->fl);
 		if (rlock)
 			locks_free_lock(rlock);
 		kfree(smb_lock);
fs/smb/server/vfs_cache.c +5 -3
index 460684624678f..9e5a3bfaefaf8 100644
@@ -511,8 +511,9 @@ static void __ksmbd_close_fd(struct ksmbd_file_table *ft, struct ksmbd_file *fp)
 	if (!IS_ERR_OR_NULL(filp))
 		fput(filp);
 
-	/* because the reference count of fp is 0, it is guaranteed that
-	 * there are not accesses to fp->lock_list.
+	/*
+	 * The zero fp reference count serializes access to fp->lock_list, but
+	 * the VFS may still have blocked requests chained below these locks.
 	 */
 	list_for_each_entry_safe(smb_lock, tmp_lock, &fp->lock_list, flist) {
 		struct ksmbd_conn *conn = smb_lock->conn;
@@ -525,7 +526,8 @@ static void __ksmbd_close_fd(struct ksmbd_file_table *ft, struct ksmbd_file *fp)
 			ksmbd_conn_put(conn);
 		}
 
-		list_del(&smb_lock->flist);
+		list_del_init(&smb_lock->flist);
+		ksmbd_vfs_posix_lock_unblock(smb_lock->fl);
 		locks_free_lock(smb_lock->fl);
 		kfree(smb_lock);
 	}
Signature · 1 line
2.53.0
author maintainer
#1548 lore raw

PATCH 1532/1815 ksmbd: validate SMB2 write offsets

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit df35438ba9d5687335a405418772b6cd30383687 ]

An SMB2 WRITE request with a negative offset returns -EINVAL directly from smb2_write(). This bypasses the common error response path, leaving the client waiting until the request times out.

ksmbd also allows nonempty writes at or beyond MAXFILESIZE as defined by [MS-FSA]. Writes beyond the limit must fail with STATUS_INVALID_PARAMETER. Writes ending at the limit fail with STATUS_DISK_FULL, while a zero-length write remains valid.

Route negative offsets through the common error path and validate the end offset of nonempty writes against MAXFILESIZE.

This fixes smb2.rw.invalid.

Stable-dep-of: 2cbd4a8bf460 ("ksmbd: fix encrypted request lookup on bound channels")

---
 fs/smb/server/smb2pdu.c | 22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)
fs/smb/server/smb2pdu.c +20 -2
index 534416e2b599c..acf664a5183da 100644
@@ -64,6 +64,9 @@ static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
 /* Windows reports automatic write-time updates at roughly 15 ms resolution. */
 #define KSMBD_WRITE_TIME_RESOLUTION	(15ULL * 10000)
 
+/* MAXFILESIZE in [MS-FSA] 2.1.5.3 Server Requests a Write. */
+#define SMB2_MAX_FILE_SIZE		0xfffffff0000ULL
+
 /**
  * check_session_id() - check for valid session id in smb header
  * @conn:	connection instance
@@ -8159,8 +8162,10 @@ int smb2_write(struct ksmbd_work *work)
 	}
 
 	offset = le64_to_cpu(req->Offset);
-	if (offset < 0)
-		return -EINVAL;
+	if (offset < 0) {
+		err = -EINVAL;
+		goto out;
+	}
 	length = le32_to_cpu(req->Length);
 
 	if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
@@ -8174,6 +8179,19 @@ int smb2_write(struct ksmbd_work *work)
 		length = le32_to_cpu(req->RemainingBytes);
 	}
 
+	if (length) {
+		u64 end = (u64)offset + length;
+
+		if (end > SMB2_MAX_FILE_SIZE) {
+			err = -EINVAL;
+			goto out;
+		}
+		if (end == SMB2_MAX_FILE_SIZE) {
+			err = -EFBIG;
+			goto out;
+		}
+	}
+
 	if (is_rdma_channel == true) {
 		unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
 
Signature · 1 line
2.53.0
author maintainer
#1549 lore raw

PATCH 1533/1815 ksmbd: expire SMB sessions when Kerberos tickets expire

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit a47634cd729b42dfe372048b056d98ba4e128eaa ]

Store the expiry time from the Kerberos authentication response in the session and reject requests after that time with STATUS_NETWORK_SESSION_EXPIRED.

Allow an expired Kerberos session to be reauthenticated. Keep the old SMB signing key until its SESSION_SETUP response has been signed, then install the new session key and regenerate the SMB3 keys.

Stable-dep-of: 2cbd4a8bf460 ("ksmbd: fix encrypted request lookup on bound channels")

---
 fs/smb/server/auth.c              |  18 +-
 fs/smb/server/ksmbd_netlink.h     |   1 +
 fs/smb/server/ksmbd_work.h        |   1 +
 fs/smb/server/mgmt/user_session.c |  14 +-
 fs/smb/server/mgmt/user_session.h |   3 +
 fs/smb/server/server.c            |   9 +-
 fs/smb/server/smb2pdu.c           | 270 +++++++++++++++++++++---------
 7 files changed, 236 insertions(+), 80 deletions(-)
fs/smb/server/auth.c +16 -2
index f2100e3ec54c9..d51f32095adad 100644
@@ -463,6 +463,7 @@ int ksmbd_krb5_authenticate(struct ksmbd_session *sess, char *in_blob,
 	memcpy(out_blob, resp->payload + resp->session_key_len,
 	       resp->spnego_blob_len);
 	*out_len = resp->spnego_blob_len;
+	sess->kerberos_expiry = resp->session_expiry;
 	retval = 0;
 out:
 	kvfree(resp);
@@ -717,8 +718,21 @@ static int ksmbd_get_encryption_key(struct ksmbd_work *work, __u64 ses_id,
 
 	if (enc)
 		sess = work->sess;
-	else
-		sess = ksmbd_session_lookup_all(work->conn, ses_id);
+	else {
+		/*
+		 * An encrypted SESSION_SETUP request may reauthenticate an expired
+		 * Kerberos session.  Keep using the established decryption key so
+		 * that the command can reach the session setup handler. Other
+		 * commands are rejected there with STATUS_NETWORK_SESSION_EXPIRED.
+		 */
+		sess = ksmbd_session_lookup(work->conn, ses_id);
+		if (sess && sess->state != SMB2_SESSION_VALID &&
+		    (sess->state != SMB2_SESSION_EXPIRED ||
+		     !sess->kerberos_expiry)) {
+			ksmbd_user_session_put(sess);
+			sess = NULL;
+		}
+	}
 	if (!sess)
 		return -EINVAL;
 
fs/smb/server/ksmbd_netlink.h +1 -0
index 1ea0a367b3969..af1e760453d9c 100644
@@ -286,6 +286,7 @@ struct ksmbd_spnego_authen_response {
 				  * stored in SecurityBuffer of SMB2 SESSION
 				  * SETUP response
 				  */
+	__u64	session_expiry;	/* Kerberos ticket expiry time */
 	__u8	payload[]; /* session key + AP_REP */
 };
 
fs/smb/server/ksmbd_work.h +1 -0
index 52d0c4dee65c9..5f1d3ebab4fb5 100644
@@ -95,6 +95,7 @@ struct ksmbd_work {
 	bool				owns_conn_ref:1;
 	bool                            need_invalidate_rkey:1;
 	bool				request_open_chseq_tracked:1;
+	bool				session_setup_reauth:1;
 
 	unsigned int                    remote_key;
 	/* cancel works */
fs/smb/server/mgmt/user_session.c +12 -2
index b5d79924439ff..01c8bfb2606bb 100644
@@ -531,8 +531,8 @@ struct ksmbd_session *ksmbd_session_lookup_slowpath(unsigned long long id)
 	return sess;
 }
 
-struct ksmbd_session *ksmbd_session_lookup_all(struct ksmbd_conn *conn,
-					       unsigned long long id)
+struct ksmbd_session *ksmbd_session_lookup_all_states(struct ksmbd_conn *conn,
+						      unsigned long long id)
 {
 	struct ksmbd_session *sess;
 
@@ -544,6 +544,15 @@ struct ksmbd_session *ksmbd_session_lookup_all(struct ksmbd_conn *conn,
 			sess = NULL;
 		}
 	}
+	return sess;
+}
+
+struct ksmbd_session *ksmbd_session_lookup_all(struct ksmbd_conn *conn,
+					       unsigned long long id)
+{
+	struct ksmbd_session *sess;
+
+	sess = ksmbd_session_lookup_all_states(conn, id);
 	if (sess && sess->state != SMB2_SESSION_VALID) {
 		ksmbd_user_session_put(sess);
 		sess = NULL;
@@ -623,6 +632,7 @@ void destroy_previous_session(struct ksmbd_conn *conn,
 	}
 
 	ksmbd_destroy_file_table(prev_sess);
+	prev_sess->kerberos_expiry = 0;
 	prev_sess->state = SMB2_SESSION_EXPIRED;
 	ksmbd_all_conn_set_status(id, KSMBD_SESS_NEED_SETUP);
 	ksmbd_launch_ksmbd_durable_scavenger();
fs/smb/server/mgmt/user_session.h +3 -0
index 2a0168e083286..f8a24c33f7fe4 100644
@@ -47,6 +47,7 @@ struct ksmbd_session {
 	__u8				*Preauth_HashValue;
 
 	char				sess_key[CIFS_KEY_SIZE];
+	u64				kerberos_expiry;
 
 	struct hlist_node		hlist;
 	struct rw_semaphore		chann_lock;
@@ -100,6 +101,8 @@ void ksmbd_sessions_deregister(struct ksmbd_conn *conn);
 struct ksmbd_session *__session_lookup(unsigned long long id);
 struct ksmbd_session *ksmbd_session_lookup_all(struct ksmbd_conn *conn,
 					       unsigned long long id);
+struct ksmbd_session *ksmbd_session_lookup_all_states(struct ksmbd_conn *conn,
+						      unsigned long long id);
 void destroy_previous_session(struct ksmbd_conn *conn,
 			      struct ksmbd_user *user, u64 id);
 struct preauth_session *ksmbd_preauth_session_alloc(struct ksmbd_conn *conn,
fs/smb/server/server.c +8 -1
index c629a33bfa4a8..943c619cbf848 100644
@@ -205,6 +205,9 @@ static void __handle_ksmbd_work(struct ksmbd_work *work,
 				if (rc == -EINVAL)
 					conn->ops->set_rsp_status(work,
 						STATUS_INVALID_PARAMETER);
+				else if (rc == -EKEYEXPIRED)
+					conn->ops->set_rsp_status(work,
+						STATUS_NETWORK_SESSION_EXPIRED);
 				else
 					conn->ops->set_rsp_status(work,
 						STATUS_USER_SESSION_DELETED);
@@ -212,7 +215,11 @@ static void __handle_ksmbd_work(struct ksmbd_work *work,
 					struct smb2_hdr *rsp_hdr;
 
 					rsp_hdr = ksmbd_resp_buf_curr(work);
-					rsp_hdr->Flags |= SMB2_FLAGS_SIGNED;
+					if (rc == -EKEYEXPIRED && work->sess &&
+					    conn->ops->set_sign_rsp)
+						conn->ops->set_sign_rsp(work);
+					else
+						rsp_hdr->Flags |= SMB2_FLAGS_SIGNED;
 				}
 				goto send;
 			} else if (rc > 0) {
fs/smb/server/smb2pdu.c +195 -75

464 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#1550 lore raw

PATCH 1534/1815 ksmbd: fix encrypted request lookup on bound channels

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 2cbd4a8bf460cdf414a2d7e4912c5bcfe3d0fdc2 ]

An SMB3 multichannel binding registers the secondary connection in the session channel list, but does not insert the session into the secondary connection's session xarray.

The decryption path only searches the connection-local xarray. As a result, every encrypted request received on a bound channel fails with "Could not get decryption key".

Use the channel-aware session lookup for decryption. Also stop using the temporary conn->binding flag to decide whether the global lookup is allowed. Validate the permanent channel association under chann_lock instead.

Fixes f5a544e3bab7 ("ksmbd: add support for SMB3 multichannel")
---
 fs/smb/server/auth.c              |  2 +-
 fs/smb/server/mgmt/user_session.c | 11 +++++++++--
 2 files changed, 10 insertions(+), 3 deletions(-)
fs/smb/server/auth.c +1 -1
index d51f32095adad..8bcd2a8a574e3 100644
@@ -725,7 +725,7 @@ static int ksmbd_get_encryption_key(struct ksmbd_work *work, __u64 ses_id,
 		 * that the command can reach the session setup handler. Other
 		 * commands are rejected there with STATUS_NETWORK_SESSION_EXPIRED.
 		 */
-		sess = ksmbd_session_lookup(work->conn, ses_id);
+		sess = ksmbd_session_lookup_all_states(work->conn, ses_id);
 		if (sess && sess->state != SMB2_SESSION_VALID &&
 		    (sess->state != SMB2_SESSION_EXPIRED ||
 		     !sess->kerberos_expiry)) {
fs/smb/server/mgmt/user_session.c +9 -2
index 01c8bfb2606bb..25220371775cf 100644
@@ -535,11 +535,18 @@ struct ksmbd_session *ksmbd_session_lookup_all_states(struct ksmbd_conn *conn,
 						      unsigned long long id)
 {
 	struct ksmbd_session *sess;
+	bool channel_found;
 
 	sess = ksmbd_session_lookup(conn, id);
-	if (!sess && conn->binding) {
+	if (!sess) {
 		sess = ksmbd_session_lookup_slowpath(id);
-		if (sess && !xa_load(&sess->ksmbd_chann_list, (long)conn)) {
+		if (!sess)
+			return NULL;
+
+		down_read(&sess->chann_lock);
+		channel_found = xa_load(&sess->ksmbd_chann_list, (long)conn);
+		up_read(&sess->chann_lock);
+		if (!channel_found) {
 			ksmbd_user_session_put(sess);
 			sess = NULL;
 		}
Signature · 1 line
2.53.0
author maintainer
#1551 lore raw

PATCH 1535/1815 ksmbd: scope session state changes to bound connections

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit c50e628122aed077695669e25b842e778511a43d ]

ksmbd_all_conn_set_status() treats every connection whose transient binding flag is set as belonging to the target SessionId. A logoff or session replacement can consequently move an unrelated connection to NEED_RECONNECT or NEED_SETUP.

Pass the target session itself and select connections using either the connection-local session xarray or the session's permanent channel list. Use the same association test while waiting for requests to drain.

Serialize session-wide status changes under request_lock and do not overwrite EXITING or RELEASING. Protect the shutdown transition with the same lock so a concurrent session update cannot revive a closing connection.

Fixes f5a544e3bab7 ("ksmbd: add support for SMB3 multichannel")
Fixes abcc506a9a71 ("ksmbd: fix racy issue from smb2 close and logoff with multichannel")
Fixes c444139cb747 ("ksmbd: rewrite stop_sessions() with restartable iteration")
---
 fs/smb/server/connection.c        | 37 ++++++++++++++++++++++++++-----
 fs/smb/server/connection.h        |  6 +++--
 fs/smb/server/mgmt/user_session.c |  8 +++----
 fs/smb/server/smb2pdu.c           |  6 ++---
 4 files changed, 41 insertions(+), 16 deletions(-)
fs/smb/server/connection.c +31 -6
index 636d6ce3386b2..37d9ab7e937ad 100644
@@ -304,15 +304,37 @@ void ksmbd_conn_unlock(struct ksmbd_conn *conn)
 	mutex_unlock(&conn->srv_mutex);
 }
 
-void ksmbd_all_conn_set_status(u64 sess_id, u32 status)
+static bool ksmbd_session_is_bound_to_conn(struct ksmbd_session *sess,
+					   struct ksmbd_conn *conn)
+{
+	bool found;
+
+	rcu_read_lock();
+	found = xa_load(&conn->sessions, sess->id) == sess;
+	rcu_read_unlock();
+	if (found)
+		return true;
+
+	down_read(&sess->chann_lock);
+	found = xa_load(&sess->ksmbd_chann_list, (long)conn);
+	up_read(&sess->chann_lock);
+	return found;
+}
+
+void ksmbd_all_conn_set_status(struct ksmbd_session *sess, u32 status)
 {
 	struct ksmbd_conn *conn;
 	int bkt;
 
 	down_read(&conn_list_lock);
 	hash_for_each(conn_list, bkt, conn, hlist) {
-		if (conn->binding || xa_load(&conn->sessions, sess_id))
-			WRITE_ONCE(conn->status, status);
+		if (ksmbd_session_is_bound_to_conn(sess, conn)) {
+			spin_lock(&conn->request_lock);
+			if (!ksmbd_conn_exiting(conn) &&
+			    !ksmbd_conn_releasing(conn))
+				WRITE_ONCE(conn->status, status);
+			spin_unlock(&conn->request_lock);
+		}
 	}
 	up_read(&conn_list_lock);
 }
@@ -322,7 +344,8 @@ void ksmbd_conn_wait_idle(struct ksmbd_conn *conn)
 	wait_event(conn->req_running_q, atomic_read(&conn->req_running) < 2);
 }
 
-int ksmbd_conn_wait_idle_sess_id(struct ksmbd_conn *curr_conn, u64 sess_id)
+int ksmbd_conn_wait_idle_sess(struct ksmbd_conn *curr_conn,
+			      struct ksmbd_session *sess)
 {
 	struct ksmbd_conn *conn;
 	int rc, retry_count = 0, max_timeout = 120;
@@ -334,7 +357,7 @@ int ksmbd_conn_wait_idle_sess_id(struct ksmbd_conn *curr_conn, u64 sess_id)
 
 	down_read(&conn_list_lock);
 	hash_for_each(conn_list, bkt, conn, hlist) {
-		if (conn->binding || xa_load(&conn->sessions, sess_id)) {
+		if (ksmbd_session_is_bound_to_conn(sess, conn)) {
 			rcount = (conn == curr_conn) ? 2 : 1;
 			if (atomic_read(&conn->req_running) >= rcount) {
 				rc = wait_event_timeout(conn->req_running_q,
@@ -660,8 +683,10 @@ static void stop_sessions(void)
 		 * handler exited its receive loop for an unrelated
 		 * reason).
 		 */
-		if (READ_ONCE(conn->status) != KSMBD_SESS_RELEASING)
+		spin_lock(&conn->request_lock);
+		if (!ksmbd_conn_releasing(conn))
 			ksmbd_conn_set_exiting(conn);
+		spin_unlock(&conn->request_lock);
 		target = conn;
 		break;
 	}
fs/smb/server/connection.h +4 -2
index 158feb019142f..7f7bc1f24a63d 100644
@@ -22,6 +22,7 @@
 #include "ksmbd_work.h"
 
 struct smbdirect_buffer_descriptor_v1;
+struct ksmbd_session;
 
 #define KSMBD_SOCKET_BACKLOG		16
 
@@ -167,7 +168,8 @@ extern struct rw_semaphore conn_list_lock;
 
 bool ksmbd_conn_alive(struct ksmbd_conn *conn);
 void ksmbd_conn_wait_idle(struct ksmbd_conn *conn);
-int ksmbd_conn_wait_idle_sess_id(struct ksmbd_conn *curr_conn, u64 sess_id);
+int ksmbd_conn_wait_idle_sess(struct ksmbd_conn *curr_conn,
+			      struct ksmbd_session *sess);
 struct ksmbd_conn *ksmbd_conn_alloc(void);
 void ksmbd_conn_free(struct ksmbd_conn *conn);
 struct ksmbd_conn *ksmbd_conn_get(struct ksmbd_conn *conn);
@@ -280,5 +282,5 @@ static inline void ksmbd_conn_set_releasing(struct ksmbd_conn *conn)
 	WRITE_ONCE(conn->status, KSMBD_SESS_RELEASING);
 }
 
-void ksmbd_all_conn_set_status(u64 sess_id, u32 status);
+void ksmbd_all_conn_set_status(struct ksmbd_session *sess, u32 status);
 #endif /* __CONNECTION_H__ */
fs/smb/server/mgmt/user_session.c +4 -4
index 25220371775cf..3273c500eff44 100644
@@ -631,17 +631,17 @@ void destroy_previous_session(struct ksmbd_conn *conn,
 	    memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
 		goto out;
 
-	ksmbd_all_conn_set_status(id, KSMBD_SESS_NEED_RECONNECT);
-	err = ksmbd_conn_wait_idle_sess_id(conn, id);
+	ksmbd_all_conn_set_status(prev_sess, KSMBD_SESS_NEED_RECONNECT);
+	err = ksmbd_conn_wait_idle_sess(conn, prev_sess);
 	if (err) {
-		ksmbd_all_conn_set_status(id, KSMBD_SESS_NEED_SETUP);
+		ksmbd_all_conn_set_status(prev_sess, KSMBD_SESS_NEED_SETUP);
 		goto out;
 	}
 
 	ksmbd_destroy_file_table(prev_sess);
 	prev_sess->kerberos_expiry = 0;
 	prev_sess->state = SMB2_SESSION_EXPIRED;
-	ksmbd_all_conn_set_status(id, KSMBD_SESS_NEED_SETUP);
+	ksmbd_all_conn_set_status(prev_sess, KSMBD_SESS_NEED_SETUP);
 	ksmbd_launch_ksmbd_durable_scavenger();
 out:
 	up_write(&conn->session_lock);
fs/smb/server/smb2pdu.c +2 -4
index 9492bdb99d59d..9c9af31b8d1ec 100644
@@ -2791,7 +2791,6 @@ int smb2_session_logoff(struct ksmbd_work *work)
 	struct ksmbd_session *sess = work->sess;
 	struct smb2_logoff_req *req;
 	struct smb2_logoff_rsp *rsp;
-	u64 sess_id;
 	int err;
 
 	WORK_BUFFERS(work, req, rsp);
@@ -2805,8 +2804,7 @@ int smb2_session_logoff(struct ksmbd_work *work)
 		smb2_set_err_rsp(work);
 		return -ENOENT;
 	}
-	sess_id = le64_to_cpu(req->hdr.SessionId);
-	ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
+	ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_RECONNECT);
 	ksmbd_conn_unlock(conn);
 
 	ksmbd_close_session_fds(work);
@@ -2824,7 +2822,7 @@ int smb2_session_logoff(struct ksmbd_work *work)
 	sess->state = SMB2_SESSION_EXPIRED;
 	up_write(&conn->session_lock);
 
-	ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_SETUP);
+	ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_SETUP);
 
 	rsp->StructureSize = cpu_to_le16(4);
 	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
Signature · 1 line
2.53.0
author maintainer
#1552 lore raw

PATCH 1536/1815 ksmbd: disconnect on SMB3 decryption failure

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 12a6680ce59bcd431730c9f049caddb017964c64 ]

MS-SMB2 requires the server to disconnect a connection when an encrypted transform cannot be associated with a session or fails authenticated decryption. This includes an encrypted request that still carries a SessionId invalidated through PreviousSessionId.

Move the connection to EXITING and shut down its transport when decrypt_req() fails. Add the missing TCP shutdown callback so a receive blocked in kernel_recvmsg() is released; SMB Direct already provides the corresponding callback.

Plaintext requests using an invalidated SessionId do not take this path and continue to receive STATUS_USER_SESSION_DELETED.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/connection.c    | 16 ++++++++++++++++
 fs/smb/server/connection.h    |  1 +
 fs/smb/server/server.c        |  4 +++-
 fs/smb/server/transport_tcp.c |  6 ++++++
 4 files changed, 26 insertions(+), 1 deletion(-)
fs/smb/server/connection.c +16 -0
index 37d9ab7e937ad..49ee4f281a1f2 100644
@@ -339,6 +339,22 @@ void ksmbd_all_conn_set_status(struct ksmbd_session *sess, u32 status)
 	up_read(&conn_list_lock);
 }
 
+void ksmbd_conn_abort(struct ksmbd_conn *conn)
+{
+	bool shutdown = false;
+
+	spin_lock(&conn->request_lock);
+	if (!ksmbd_conn_exiting(conn) && !ksmbd_conn_releasing(conn)) {
+		ksmbd_conn_set_exiting(conn);
+		shutdown = true;
+	}
+	spin_unlock(&conn->request_lock);
+	wake_up_all(&conn->req_running_q);
+
+	if (shutdown && conn->transport->ops->shutdown)
+		conn->transport->ops->shutdown(conn->transport);
+}
+
 void ksmbd_conn_wait_idle(struct ksmbd_conn *conn)
 {
 	wait_event(conn->req_running_q, atomic_read(&conn->req_running) < 2);
fs/smb/server/connection.h +1 -0
index 7f7bc1f24a63d..242a9757eb0db 100644
@@ -174,6 +174,7 @@ struct ksmbd_conn *ksmbd_conn_alloc(void);
 void ksmbd_conn_free(struct ksmbd_conn *conn);
 struct ksmbd_conn *ksmbd_conn_get(struct ksmbd_conn *conn);
 void ksmbd_conn_put(struct ksmbd_conn *conn);
+void ksmbd_conn_abort(struct ksmbd_conn *conn);
 int ksmbd_conn_wq_init(void);
 void ksmbd_conn_wq_destroy(void);
 bool ksmbd_conn_lookup_dialect(struct ksmbd_conn *c);
fs/smb/server/server.c +3 -1
index 943c619cbf848..0425ef045db0b 100644
@@ -183,8 +183,10 @@ static void __handle_ksmbd_work(struct ksmbd_work *work,
 	if (conn->ops->is_transform_hdr &&
 	    conn->ops->is_transform_hdr(work->request_buf)) {
 		rc = conn->ops->decrypt_req(work);
-		if (rc < 0)
+		if (rc < 0) {
+			ksmbd_conn_abort(conn);
 			return;
+		}
 		work->encrypted = true;
 	}
 
fs/smb/server/transport_tcp.c +6 -0
index 13b711ea575d8..990b14e5d3ea2 100644
@@ -434,6 +434,11 @@ static void ksmbd_tcp_disconnect(struct ksmbd_transport *t)
 		atomic_dec(&active_num_conn);
 }
 
+static void ksmbd_tcp_shutdown(struct ksmbd_transport *t)
+{
+	kernel_sock_shutdown(TCP_TRANS(t)->sock, SHUT_RDWR);
+}
+
 static void tcp_destroy_socket(struct socket *ksmbd_socket)
 {
 	int ret;
@@ -680,5 +685,6 @@ static const struct ksmbd_transport_ops ksmbd_tcp_transport_ops = {
 	.read		= ksmbd_tcp_read,
 	.writev		= ksmbd_tcp_writev,
 	.disconnect	= ksmbd_tcp_disconnect,
+	.shutdown	= ksmbd_tcp_shutdown,
 	.free_transport = ksmbd_tcp_free_transport,
 };
Signature · 1 line
2.53.0
author maintainer
#1553 lore raw

PATCH 1537/1815 ksmbd: decrypt requests from expired encrypted sessions

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit d8fc4fc7e57fc2bfd45699a10ee0df8ab9dccfa5 ]

Previous-session replacement marks the old session expired but retains its SMB3 encryption key. An in-flight encrypted request can still arrive on that connection. Rejecting the expired session before decryption made ksmbd treat the request as a key failure and abort the transport, causing reconnect failures.

Allow key lookup for expired sessions that have encryption enabled. Keep the session reference during validation so the normal STATUS_USER_SESSION_DELETED response is encrypted with the old key. The session remains expired and no command is executed.

Fixes fa9415d4024f ("ksmbd: mark SMB2_SESSION_EXPIRED to session when destroying previous session")
---
 fs/smb/server/auth.c    | 12 ++++++------
 fs/smb/server/smb2pdu.c |  8 ++++++++
 2 files changed, 14 insertions(+), 6 deletions(-)
fs/smb/server/auth.c +6 -6
index 8bcd2a8a574e3..2d116d60f7f6c 100644
@@ -720,15 +720,15 @@ static int ksmbd_get_encryption_key(struct ksmbd_work *work, __u64 ses_id,
 		sess = work->sess;
 	else {
 		/*
-		 * An encrypted SESSION_SETUP request may reauthenticate an expired
-		 * Kerberos session.  Keep using the established decryption key so
-		 * that the command can reach the session setup handler. Other
-		 * commands are rejected there with STATUS_NETWORK_SESSION_EXPIRED.
+		 * A previous-session replacement leaves the old encryption key in
+		 * place.  Use it to authenticate an encrypted request, then let
+		 * session validation reject the expired session.  This preserves the
+		 * encrypted STATUS_USER_SESSION_DELETED response without reviving
+		 * the session.
 		 */
 		sess = ksmbd_session_lookup_all_states(work->conn, ses_id);
 		if (sess && sess->state != SMB2_SESSION_VALID &&
-		    (sess->state != SMB2_SESSION_EXPIRED ||
-		     !sess->kerberos_expiry)) {
+		    (sess->state != SMB2_SESSION_EXPIRED || !sess->enc)) {
 			ksmbd_user_session_put(sess);
 			sess = NULL;
 		}
fs/smb/server/smb2pdu.c +8 -0
index 9c9af31b8d1ec..6e1fb37452b42 100644
@@ -995,6 +995,14 @@ int smb2_check_user_session(struct ksmbd_work *work)
 				1 : -EKEYEXPIRED;
 		}
 		if (work->sess->state != SMB2_SESSION_VALID) {
+			/*
+			 * Keep the reference for an encrypted request so the caller can
+			 * return STATUS_USER_SESSION_DELETED encrypted with the old key.
+			 */
+			if (work->encrypted &&
+			    work->sess->state == SMB2_SESSION_EXPIRED &&
+			    work->sess->enc)
+				return -ENOENT;
 			ksmbd_user_session_put(work->sess);
 			work->sess = NULL;
 			return -ENOENT;
Signature · 1 line
2.53.0
author maintainer
#1554 lore raw

PATCH 1538/1815 ksmbd: handle encrypted compressed requests

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 6639b6928ba22dd6750ff3c6f6de77715cf46d50 ]

SMB3 permits a message to be compressed before it is encrypted. After decrypting such a request, ksmbd must trim the AEAD tag using OriginalMessageSize, decompress the nested compression transform, and validate the resulting SMB2 PDU.

Share the decompression helper between the connection receive path and the post-decryption work path so unencrypted and encrypted compressed requests follow the same validation.

Fixes a08de24c2b85 ("ksmbd: negotiate and decode SMB2 compression")
---
 fs/smb/server/compress.c | 76 ++++++++++++++++++++++++++++++----------
 fs/smb/server/compress.h |  1 +
 fs/smb/server/server.c   | 22 ++++++++++++
 fs/smb/server/smb2pdu.c  | 22 ++++++++----
 4 files changed, 97 insertions(+), 24 deletions(-)
fs/smb/server/compress.c +58 -18
index 01d1771ff6636..5162fb84c755a 100644
@@ -14,24 +14,14 @@
 
 #define SMB_COMPRESS_MIN_LEN	PAGE_SIZE
 
-/**
- * ksmbd_decompress_request() - replace a compressed request with its SMB2 PDU
- * @conn: connection which owns the current RFC1002 request buffer
- *
- * Derive the uncompressed size from the transform variant, enforce ksmbd's
- * normal message limits, and ask the common decoder to validate every payload.
- * On success, replace conn->request_buf with a regular RFC1002-framed SMB2
- * message so the rest of the request path needs no compression awareness.
- *
- * Return: 0 on success, otherwise a negative errno.
- */
-int ksmbd_decompress_request(struct ksmbd_conn *conn)
+static int __ksmbd_decompress_request(struct ksmbd_conn *conn,
+					     void *request_buf, void **out_buf)
 {
 	struct smb2_compression_hdr *hdr;
-	unsigned int pdu_size = get_rfc1002_len(conn->request_buf);
+	unsigned int pdu_size = get_rfc1002_len(request_buf);
 	u32 orig_size, offset, out_size;
 	u32 max_allowed_pdu_size;
-	char *buf, *out;
+	char *out;
 	int rc;
 
 	if (pdu_size < sizeof(struct smb2_compression_hdr))
@@ -41,7 +31,7 @@ int ksmbd_decompress_request(struct ksmbd_conn *conn)
 	    conn->compress_algorithm == SMB3_COMPRESS_NONE)
 		return -EINVAL;
 
-	hdr = smb_get_msg(conn->request_buf);
+	hdr = smb_get_msg(request_buf);
 	if (hdr->ProtocolId != SMB2_COMPRESSION_TRANSFORM_ID)
 		return -EINVAL;
 
@@ -74,19 +64,69 @@ int ksmbd_decompress_request(struct ksmbd_conn *conn)
 	if (!out)
 		return -ENOMEM;
 
-	buf = (char *)hdr;
 	*(__be32 *)out = cpu_to_be32(out_size);
 	rc = smb_compression_decompress(conn->compress_algorithm,
 					conn->compress_chained,
 					conn->compress_pattern,
-					buf, pdu_size, out + 4, out_size);
+					(char *)hdr, pdu_size, out + 4, out_size);
 	if (rc) {
 		kvfree(out);
 		return rc;
 	}
 
+	*out_buf = out;
+	return 0;
+}
+
+/**
+ * ksmbd_decompress_request() - replace a compressed request with its SMB2 PDU
+ * @conn: connection which owns the current RFC1002 request buffer
+ *
+ * Derive the uncompressed size from the transform variant, enforce ksmbd's
+ * normal message limits, and ask the common decoder to validate every payload.
+ * On success, replace conn->request_buf with a regular RFC1002-framed SMB2
+ * message so the rest of the request path needs no compression awareness.
+ *
+ * Return: 0 on success, otherwise a negative errno.
+ */
+int ksmbd_decompress_request(struct ksmbd_conn *conn)
+{
+	void *out_buf;
+	int rc;
+
+	rc = __ksmbd_decompress_request(conn, conn->request_buf, &out_buf);
+	if (rc)
+		return rc;
+
 	kvfree(conn->request_buf);
-	conn->request_buf = out;
+	conn->request_buf = out_buf;
+	return 0;
+}
+
+/**
+ * ksmbd_decompress_work_request() - decompress an encrypted work request
+ * @work: work item whose request buffer contains a compression transform
+ *
+ * SMB3 encrypts a compressed message by applying compression first and
+ * encryption second.  The receive loop can therefore only decode the
+ * compression transform before work allocation for an unencrypted request;
+ * an encrypted request must be decompressed after its encryption layer has
+ * been removed.
+ *
+ * Return: 0 on success, otherwise a negative errno.
+ */
+int ksmbd_decompress_work_request(struct ksmbd_work *work)
+{
+	void *out_buf;
+	int rc;
+
+	rc = __ksmbd_decompress_request(work->conn, work->request_buf,
+					&out_buf);
+	if (rc)
+		return rc;
+
+	kvfree(work->request_buf);
+	work->request_buf = out_buf;
 	return 0;
 }
 
fs/smb/server/compress.h +1 -0
index 663c6f44f09b0..13df2eb221e8c 100644
@@ -11,6 +11,7 @@
 #include "../common/compress/compress.h"
 
 int ksmbd_decompress_request(struct ksmbd_conn *conn);
+int ksmbd_decompress_work_request(struct ksmbd_work *work);
 int ksmbd_compress_response(struct ksmbd_work *work);
 
 #endif /* __KSMBD_COMPRESS_H__ */
fs/smb/server/server.c +22 -0
index 0425ef045db0b..46a67642f814e 100644
@@ -188,6 +188,28 @@ static void __handle_ksmbd_work(struct ksmbd_work *work,
 			return;
 		}
 		work->encrypted = true;
+
+		/*
+		 * SMB3 applies compression before encryption.  The receive loop
+		 * handles a plain compression transform before allocating work, but
+		 * an encrypted request exposes that transform only after decryption.
+		 */
+		if (((struct smb2_hdr *)smb_get_msg(work->request_buf))->ProtocolId ==
+		    SMB2_COMPRESSION_TRANSFORM_ID) {
+			rc = ksmbd_decompress_work_request(work);
+			if (rc < 0) {
+				ksmbd_conn_abort(conn);
+				return;
+			}
+		}
+
+		/* The decrypted payload must now be a complete SMB2 request. */
+		if (((struct smb2_hdr *)smb_get_msg(work->request_buf))->ProtocolId !=
+			SMB2_PROTO_NUMBER ||
+		    get_rfc1002_len(work->request_buf) < sizeof(struct smb2_pdu)) {
+			ksmbd_conn_abort(conn);
+			return;
+		}
 	}
 
 	if (conn->ops->allocate_rsp_buf(work))
fs/smb/server/smb2pdu.c +16 -6
index 6e1fb37452b42..4cf7083f35ccd 100644
@@ -10857,18 +10857,27 @@ int smb3_decrypt_req(struct ksmbd_work *work)
 	char *buf = work->request_buf;
 	unsigned int pdu_length = get_rfc1002_len(buf);
 	struct kvec iov[2];
-	int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
+	unsigned int buf_data_size;
 	struct smb2_transform_hdr *tr_hdr = smb_get_msg(buf);
+	unsigned int original_msg_size;
 	int rc = 0;
 
-	if (pdu_length < sizeof(struct smb2_transform_hdr) ||
-	    buf_data_size < sizeof(struct smb2_hdr)) {
+	if (pdu_length < sizeof(struct smb2_transform_hdr)) {
 		pr_err("Transform message is too small (%u)\n",
 		       pdu_length);
 		return -ECONNABORTED;
 	}
 
-	if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
+	buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
+	original_msg_size = le32_to_cpu(tr_hdr->OriginalMessageSize);
+	if (buf_data_size < sizeof(struct smb2_compression_hdr) ||
+	    original_msg_size < sizeof(struct smb2_compression_hdr)) {
+		pr_err("Transform message is too small (%u)\n",
+		       pdu_length);
+		return -ECONNABORTED;
+	}
+
+	if (buf_data_size < original_msg_size) {
 		pr_err("Transform message is broken\n");
 		return -ECONNABORTED;
 	}
@@ -10881,8 +10890,9 @@ int smb3_decrypt_req(struct ksmbd_work *work)
 	if (rc)
 		return rc;
 
-	memmove(buf + 4, iov[1].iov_base, buf_data_size);
-	*(__be32 *)buf = cpu_to_be32(buf_data_size);
+	/* Drop the AEAD authentication tag from the inner RFC1002 frame. */
+	memmove(buf + 4, iov[1].iov_base, original_msg_size);
+	*(__be32 *)buf = cpu_to_be32(original_msg_size);
 
 	return rc;
 }
Signature · 1 line
2.53.0
author maintainer
#1555 lore raw

PATCH 1539/1815 ksmbd: bound smb_check_perm_dacl() ACE walks by DACL size

In reply to Greg Kroah-Hartman

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

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

From: Hang Nan <[email protected]>

[ Upstream commit 79decd88dd3f0d42e7fb0689b1a7853bfa302459 ]

smb_check_perm_dacl() validates that the DACL fits inside the NT security descriptor, but then bounds its two ACE walks by the remaining NTSD length (acl_size) rather than the DACL's declared size (pdacl_size).

When pdacl->size is smaller than the trailing NTSD buffer, bytes after the declared DACL boundary - still inside the stored security descriptor - are parsed as ACEs during access checks. A crafted DACL can place an access-granting ACE beyond pdacl->size, and the current code accepts it during SMB2_CREATE access validation, while parse_dacl() and smb_inherit_dacl() stop at pdacl_size.

Bound both ACE walks by pdacl_size to match the DACL boundary semantics used elsewhere in the server.

Validation:
- semantic KUnit harness shows the post-boundary ACE is selected before the fix and rejected (EACCES) after it
- linux master (7.2-rc6), x86_64

Fixes 8f0541186e9a ("ksmbd: fix heap-based overflow in set_ntacl_dacl()")
---
 fs/smb/server/smbacl.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/smb/server/smbacl.c +2 -2
index 88bf7b97042f8..33825c1356b47 100644
@@ -1489,7 +1489,7 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,
 		access_bits = READ_CONTROL | WRITE_DAC | FILE_READ_ATTRIBUTES |
 			DELETE;
 		ace = (struct smb_ace *)((char *)pdacl + sizeof(struct smb_acl));
-		aces_size = acl_size - sizeof(struct smb_acl);
+		aces_size = pdacl_size - sizeof(struct smb_acl);
 		for (i = 0; i < le16_to_cpu(pdacl->num_aces); i++) {
 			if (aces_size < offsetof(struct smb_ace, sid) +
 			    CIFS_SID_BASE_SIZE)
@@ -1536,7 +1536,7 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,
 	}
 
 	ace = (struct smb_ace *)((char *)pdacl + sizeof(struct smb_acl));
-	aces_size = acl_size - sizeof(struct smb_acl);
+	aces_size = pdacl_size - sizeof(struct smb_acl);
 	for (i = 0; i < le16_to_cpu(pdacl->num_aces); i++) {
 		if (aces_size < offsetof(struct smb_ace, sid) +
 		    CIFS_SID_BASE_SIZE)
Signature · 1 line
2.53.0
author maintainer
#1556 lore raw

PATCH 1540/1815 smb/server: fix session leak in ksmbd_session_register()

In reply to Greg Kroah-Hartman

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

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

From: Ze Tan <[email protected]>

[ Upstream commit 99b25b046e47e4904373cfeb445c5483f1633d88 ]

See the procedure below:

smb2_sess_setup

    ksmbd_smb2_session_create
      __session_create
        atomic_set(&sess->refcnt, 2)
        hash_add(sessions_table, &sess->hlist, sess->id)
    ksmbd_session_register
      xa_store(&conn->sessions, sess->id, sess) // fail
    ksmbd_user_session_put
      atomic_dec(&sess->refcnt) // refcnt is 1, session is not freed

Remove the session from sessions_table and drop its table reference if xa_store() fails.

Fixes f5c779b7ddbd ("ksmbd: fix racy issue from session setup and logoff")
---
 fs/smb/server/mgmt/user_session.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
fs/smb/server/mgmt/user_session.c +12 -1
index 3273c500eff44..745db1fa566c5 100644
@@ -433,10 +433,21 @@ static void ksmbd_expire_session(struct ksmbd_conn *conn)
 int ksmbd_session_register(struct ksmbd_conn *conn,
 			   struct ksmbd_session *sess)
 {
+	int ret;
+
 	sess->dialect = conn->dialect;
 	memcpy(sess->ClientGUID, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
 	ksmbd_expire_session(conn);
-	return xa_err(xa_store(&conn->sessions, sess->id, sess, KSMBD_DEFAULT_GFP));
+	ret = xa_err(xa_store(&conn->sessions, sess->id, sess,
+			      KSMBD_DEFAULT_GFP));
+	if (ret) {
+		down_write(&sessions_table_lock);
+		hash_del(&sess->hlist);
+		up_write(&sessions_table_lock);
+		ksmbd_user_session_put(sess);
+	}
+
+	return ret;
 }
 
 static int ksmbd_chann_del(struct ksmbd_conn *conn, struct ksmbd_session *sess)
Signature · 1 line
2.53.0
author maintainer
#1557 lore raw

PATCH 1541/1815 ksmbd: add procfs monitoring for active shares

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 1248f400e0997b6e881454488baaf91f8e1828d5 ]

There is no kernel-side view of the share configurations currently cached by active tree connections.

Add a shares proc entry that reports each active share name, type, tree-connection count, create masks, and descriptive configuration flags. Maintain a per-share tree-connection counter with the existing global counter so the value can be read without walking every session.

Stable-dep-of: 492b24b5b651 ("smb/server: update session counter under sessions table lock")

---
 fs/smb/server/mgmt/share_config.c | 57 +++++++++++++++++++++++++++++++
 fs/smb/server/mgmt/share_config.h | 25 ++++++++++++++
 fs/smb/server/mgmt/tree_connect.c |  2 ++
 fs/smb/server/server.c            |  1 +
 4 files changed, 85 insertions(+)
fs/smb/server/mgmt/share_config.c +57 -0
index b4f56e7338659..53d6f71dd8718 100644
@@ -28,6 +28,62 @@ struct ksmbd_veto_pattern {
 	struct list_head	list;
 };
 
+#ifdef CONFIG_PROC_FS
+static const struct ksmbd_const_name ksmbd_share_flag_names[] = {
+	{KSMBD_SHARE_FLAG_AVAILABLE, "available"},
+	{KSMBD_SHARE_FLAG_BROWSEABLE, "browseable"},
+	{KSMBD_SHARE_FLAG_WRITEABLE, "writeable"},
+	{KSMBD_SHARE_FLAG_READONLY, "read-only"},
+	{KSMBD_SHARE_FLAG_GUEST_OK, "guest-ok"},
+	{KSMBD_SHARE_FLAG_GUEST_ONLY, "guest-only"},
+	{KSMBD_SHARE_FLAG_STORE_DOS_ATTRS, "store-dos-attrs"},
+	{KSMBD_SHARE_FLAG_OPLOCKS, "oplocks"},
+	{KSMBD_SHARE_FLAG_PIPE, "pipe"},
+	{KSMBD_SHARE_FLAG_HIDE_DOT_FILES, "hide-dot-files"},
+	{KSMBD_SHARE_FLAG_INHERIT_OWNER, "inherit-owner"},
+	{KSMBD_SHARE_FLAG_STREAMS, "streams"},
+	{KSMBD_SHARE_FLAG_FOLLOW_SYMLINKS, "follow-symlinks"},
+	{KSMBD_SHARE_FLAG_ACL_XATTR, "acl-xattr"},
+	{KSMBD_SHARE_FLAG_UPDATE, "update"},
+	{KSMBD_SHARE_FLAG_CROSSMNT, "crossmnt"},
+	{KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY, "continuous-availability"},
+};
+
+static int proc_show_shares(struct seq_file *m, void *v)
+{
+	struct ksmbd_share_config *share;
+	int i;
+
+	down_read(&shares_table_lock);
+	hash_for_each(shares_table, i, share, hlist) {
+		seq_printf(m, "name:\t%s\n", share->name);
+		seq_printf(m, "type:\t%s\n",
+			   test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE) ?
+			   "pipe" : "disk");
+		seq_printf(m, "tree_connects:\t%d\n",
+			   atomic_read(&share->tree_connections));
+		seq_printf(m, "file_mask:\t0%07o\n", share->create_mask);
+		seq_printf(m, "directory_mask:\t0%07o\n", share->directory_mask);
+		seq_puts(m, "flags:\t");
+		ksmbd_proc_show_flag_names(m, ksmbd_share_flag_names,
+					   ARRAY_SIZE(ksmbd_share_flag_names),
+					   share->flags);
+		seq_puts(m, "\n\n");
+	}
+	up_read(&shares_table_lock);
+	return 0;
+}
+
+int create_proc_shares(void)
+{
+	if (!ksmbd_proc_create("shares", proc_show_shares, NULL))
+		return -ENOMEM;
+	return 0;
+}
+#else
+int create_proc_shares(void) { return 0; }
+#endif
+
 static unsigned int share_name_hash(const char *name)
 {
 	return jhash(name, strlen(name), 0);
@@ -156,6 +212,7 @@ static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work,
 
 	share->flags = resp->flags;
 	atomic_set(&share->refcount, 1);
+	ksmbd_share_tree_conn_init(share);
 	INIT_LIST_HEAD(&share->veto_list);
 	share->name = kstrdup(name, KSMBD_DEFAULT_GFP);
 	if (!share->name) {
fs/smb/server/mgmt/share_config.h +25 -0
index d4ac2dd4de204..d157545fe7d1d 100644
@@ -24,6 +24,9 @@ struct ksmbd_share_config {
 	struct path		vfs_path;
 
 	atomic_t		refcount;
+#ifdef CONFIG_PROC_FS
+	atomic_t		tree_connections;
+#endif
 	struct hlist_node	hlist;
 	unsigned short		create_mask;
 	unsigned short		directory_mask;
@@ -60,6 +63,27 @@ static inline int test_share_config_flag(struct ksmbd_share_config *share,
 	return share->flags & flag;
 }
 
+#ifdef CONFIG_PROC_FS
+static inline void ksmbd_share_tree_conn_init(struct ksmbd_share_config *share)
+{
+	atomic_set(&share->tree_connections, 0);
+}
+
+static inline void ksmbd_share_tree_conn_inc(struct ksmbd_share_config *share)
+{
+	atomic_inc(&share->tree_connections);
+}
+
+static inline void ksmbd_share_tree_conn_dec(struct ksmbd_share_config *share)
+{
+	atomic_dec(&share->tree_connections);
+}
+#else
+static inline void ksmbd_share_tree_conn_init(struct ksmbd_share_config *share) {}
+static inline void ksmbd_share_tree_conn_inc(struct ksmbd_share_config *share) {}
+static inline void ksmbd_share_tree_conn_dec(struct ksmbd_share_config *share) {}
+#endif
+
 void ksmbd_share_config_del(struct ksmbd_share_config *share);
 void __ksmbd_share_config_put(struct ksmbd_share_config *share);
 
@@ -74,4 +98,5 @@ struct ksmbd_share_config *ksmbd_share_config_get(struct ksmbd_work *work,
 						  const char *name);
 bool ksmbd_share_veto_filename(struct ksmbd_share_config *share,
 			       const char *filename);
+int create_proc_shares(void);
 #endif /* __SHARE_CONFIG_MANAGEMENT_H__ */
fs/smb/server/mgmt/tree_connect.c +2 -0
index 3d04feaf8737a..dd1db3554caed 100644
@@ -90,6 +90,7 @@ ksmbd_tree_conn_connect(struct ksmbd_work *work, const char *share_name)
 		goto out_error;
 	}
 	ksmbd_counter_inc(KSMBD_COUNTER_TREE_CONNS);
+	ksmbd_share_tree_conn_inc(sc);
 	kvfree(resp);
 	return status;
 
@@ -118,6 +119,7 @@ static int __ksmbd_tree_conn_disconnect(struct ksmbd_session *sess,
 	ret = ksmbd_ipc_tree_disconnect_request(sess->id, tree_conn->id);
 	ksmbd_release_tree_conn_id(sess, tree_conn->id);
 	ksmbd_counter_dec(KSMBD_COUNTER_TREE_CONNS);
+	ksmbd_share_tree_conn_dec(tree_conn->share_conf);
 	if (atomic_dec_and_test(&tree_conn->refcount)) {
 		ksmbd_share_config_put(tree_conn->share_conf);
 		kfree(tree_conn);
fs/smb/server/server.c +1 -0
index 46a67642f814e..7d17e2901dabb 100644
@@ -645,6 +645,7 @@ static int __init ksmbd_server_init(void)
 	if (ret)
 		goto err_unregister;
 	create_proc_sessions();
+	create_proc_shares();
 
 	ksmbd_server_tcp_callbacks_init();
 
Signature · 1 line
2.53.0
author maintainer
#1558 lore raw

PATCH 1542/1815 smb/server: warn if ksmbd_proc_create() fails

In reply to Greg Kroah-Hartman

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

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

From: Ze Tan <[email protected]>

[ Upstream commit 9a74739026fb71d1197183a067eef657bb5fba77 ]

Print a warning if the sessions procfs entry cannot be created.

Stable-dep-of: 492b24b5b651 ("smb/server: update session counter under sessions table lock")

---
 fs/smb/server/connection.c        | 3 ++-
 fs/smb/server/mgmt/user_session.c | 5 ++++-
 fs/smb/server/server.c            | 8 ++++++--
 fs/smb/server/vfs_cache.c         | 6 ++++--
 4 files changed, 16 insertions(+), 6 deletions(-)
fs/smb/server/connection.c +2 -1
index 49ee4f281a1f2..af73c2ed5d249 100644
@@ -665,7 +665,8 @@ int ksmbd_conn_transport_init(void)
 	}
 out:
 	mutex_unlock(&init_lock);
-	create_proc_clients();
+	if (create_proc_clients())
+		pr_warn("Unable to create clients procfs entry\n");
 	return ret;
 }
 
fs/smb/server/mgmt/user_session.c +4 -1
index 745db1fa566c5..215f4e66deda0 100644
@@ -188,6 +188,8 @@ static int create_proc_session(struct ksmbd_session *sess)
 	snprintf(name, sizeof(name), "sessions/%llu", sess->id);
 	sess->proc_entry = ksmbd_proc_create(name,
 					     show_proc_session, sess);
+	if (!sess->proc_entry)
+		return -ENOMEM;
 	return 0;
 }
 
@@ -724,7 +726,8 @@ static struct ksmbd_session *__session_create(int protocol)
 	hash_add(sessions_table, &sess->hlist, sess->id);
 	up_write(&sessions_table_lock);
 
-	create_proc_session(sess);
+	if (create_proc_session(sess))
+		pr_warn_ratelimited("Unable to create session %llu procfs entry\n", sess->id);
 	ksmbd_counter_inc(KSMBD_COUNTER_SESSIONS);
 	return sess;
 
fs/smb/server/server.c +6 -2
index 7d17e2901dabb..0b080972e9085 100644
@@ -644,8 +644,12 @@ static int __init ksmbd_server_init(void)
 	ret = ksmbd_proc_init();
 	if (ret)
 		goto err_unregister;
-	create_proc_sessions();
-	create_proc_shares();
+
+	if (create_proc_sessions())
+		pr_warn("Unable to create sessions procfs entry\n");
+
+	if (create_proc_shares())
+		pr_warn("Unable to create shares procfs entry\n");
 
 	ksmbd_server_tcp_callbacks_init();
 
fs/smb/server/vfs_cache.c +4 -2
index 9e5a3bfaefaf8..293dab9b43be1 100644
@@ -124,7 +124,8 @@ static int proc_show_files(struct seq_file *m, void *v)
 
 static int create_proc_files(void)
 {
-	ksmbd_proc_create("files", proc_show_files, NULL);
+	if (!ksmbd_proc_create("files", proc_show_files, NULL))
+		return -ENOMEM;
 	return 0;
 }
 #else
@@ -1678,7 +1679,8 @@ void ksmbd_close_session_fds(struct ksmbd_work *work)
 
 int ksmbd_init_global_file_table(void)
 {
-	create_proc_files();
+	if (create_proc_files())
+		pr_warn("Unable to create files procfs entry\n");
 	return ksmbd_init_file_table(&global_ft);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1559 lore raw

PATCH 1543/1815 smb/server: update session counter under sessions table lock

In reply to Greg Kroah-Hartman

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

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

From: Ze Tan <[email protected]>

[ Upstream commit 492b24b5b651a72ee83a8d481f70246b36192832 ]

KSMBD_COUNTER_SESSIONS tracks sessions published in sessions_table. Increment it while holding sessions_table_lock so publishing a session and updating the counter happen together.

Fixes b38f99c1217a ("ksmbd: add procfs interface for runtime monitoring and statistics")
---
 fs/smb/server/mgmt/user_session.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/server/mgmt/user_session.c +1 -1
index 215f4e66deda0..5b734acc00736 100644
@@ -724,11 +724,11 @@ static struct ksmbd_session *__session_create(int protocol)
 
 	down_write(&sessions_table_lock);
 	hash_add(sessions_table, &sess->hlist, sess->id);
+	ksmbd_counter_inc(KSMBD_COUNTER_SESSIONS);
 	up_write(&sessions_table_lock);
 
 	if (create_proc_session(sess))
 		pr_warn_ratelimited("Unable to create session %llu procfs entry\n", sess->id);
-	ksmbd_counter_inc(KSMBD_COUNTER_SESSIONS);
 	return sess;
 
 error:
Signature · 1 line
2.53.0
author maintainer
#1560 lore raw

PATCH 1544/1815 smb/server: fix session counter on session removal

In reply to Greg Kroah-Hartman

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

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

From: Ze Tan <[email protected]>

[ Upstream commit 7de5cf9bcf96bf2ee2ea2ad1d35a7b950f71161a ]

See the procedure below:

smb2_sess_setup

    ksmbd_smb2_session_create
      __session_create
        hash_add(sessions_table, &sess->hlist, sess->id)
        ksmbd_counter_inc(KSMBD_COUNTER_SESSIONS)
  ksmbd_conn_handler_loop
    ksmbd_server_terminate_conn
      ksmbd_sessions_deregister
        hash_del(&sess->hlist)
        // do not decrement KSMBD_COUNTER_SESSIONS

KSMBD_COUNTER_SESSIONS tracks sessions published in sessions_table, but session removal does not decrement it. The value therefore keeps growing after sessions are expired, rejected during registration, or removed on the last channel disconnect.

Fixes b38f99c1217a ("ksmbd: add procfs interface for runtime monitoring and statistics")
---
 fs/smb/server/mgmt/user_session.c | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)
fs/smb/server/mgmt/user_session.c +10 -4
index 5b734acc00736..d91dde3f9e619 100644
@@ -397,6 +397,12 @@ void ksmbd_session_destroy(struct ksmbd_session *sess)
 	kfree(sess);
 }
 
+static void ksmbd_session_remove_from_table(struct ksmbd_session *sess)
+{
+	hash_del(&sess->hlist);
+	ksmbd_counter_dec(KSMBD_COUNTER_SESSIONS);
+}
+
 struct ksmbd_session *__session_lookup(unsigned long long id)
 {
 	struct ksmbd_session *sess;
@@ -423,7 +429,7 @@ static void ksmbd_expire_session(struct ksmbd_conn *conn)
 		     time_after(jiffies,
 			       sess->last_active + SMB2_SESSION_TIMEOUT))) {
 			xa_erase(&conn->sessions, sess->id);
-			hash_del(&sess->hlist);
+			ksmbd_session_remove_from_table(sess);
 			ksmbd_session_destroy(sess);
 			continue;
 		}
@@ -444,7 +450,7 @@ int ksmbd_session_register(struct ksmbd_conn *conn,
 			      KSMBD_DEFAULT_GFP));
 	if (ret) {
 		down_write(&sessions_table_lock);
-		hash_del(&sess->hlist);
+		ksmbd_session_remove_from_table(sess);
 		up_write(&sessions_table_lock);
 		ksmbd_user_session_put(sess);
 	}
@@ -477,7 +483,7 @@ void ksmbd_sessions_deregister(struct ksmbd_conn *conn)
 	hash_for_each_safe(sessions_table, bkt, tmp, sess, hlist) {
 		if (!ksmbd_chann_del(conn, sess) &&
 		    xa_empty(&sess->ksmbd_chann_list)) {
-			hash_del(&sess->hlist);
+			ksmbd_session_remove_from_table(sess);
 			down_write(&conn->session_lock);
 			xa_erase(&conn->sessions, sess->id);
 			up_write(&conn->session_lock);
@@ -491,7 +497,7 @@ void ksmbd_sessions_deregister(struct ksmbd_conn *conn)
 		ksmbd_chann_del(conn, sess);
 		if (xa_empty(&sess->ksmbd_chann_list)) {
 			xa_erase(&conn->sessions, sess->id);
-			hash_del(&sess->hlist);
+			ksmbd_session_remove_from_table(sess);
 			if (atomic_dec_and_test(&sess->refcnt))
 				ksmbd_session_destroy(sess);
 		}
Signature · 1 line
2.53.0
author maintainer
#1561 lore raw

PATCH 1545/1815 selftests/bpf: Retry stat generation in cgroup_iter_memcg

In reply to Greg Kroah-Hartman

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

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

From: Andrii Nakryiko <[email protected]>

[ Upstream commit 3d9393ff98ca9a132c7a0778436f5ed856fb3dc6 ]

Each cgroup_iter_memcg subtest touches 1024 pages and expects the matching memcg counter to be non-zero. On a host with many CPUs it reads zero instead:

test_anon:FAIL:final anon mapped val: actual 0 <= expected 0

memcg stats are cached per-cpu and only become visible once the periodic flusher runs (FLUSH_TIME, 2s), or once pending updates cross MEMCG_CHARGE_BATCH * num_online_cpus(). That threshold is 512 pages at 8 CPUs but 8192 at 128, so a single pass no longer reaches it and bpf_mem_cgroup_flush_stats() returns without flushing anything.

Retry the stat generation, sleeping in between, so that a flusher cycle is always covered. Sleep before dropping the mapping, so that a flusher cycle landing in the sleep observes the mapped state. nr_anon_mapped and nr_file_mapped are rmap gauges, and unmapping first would post a matching negative delta for the flusher to aggregate to a net zero.

test_file asserts on both nr_file_pages and nr_file_mapped, which have different lifetimes, as page cache pages outlive the mapping. Retry while either one is still zero.

Fixes 6bce6ddbe634 ("bpf: selftests: selftests for memcg stat kfuncs")
---
 .../bpf/prog_tests/cgroup_iter_memcg.c        | 43 +++++++++++++++++++
 1 file changed, 43 insertions(+)
tools/testing/selftests/bpf/prog_tests/cgroup_iter_memcg.c +43 -0
index b7c18d590b993..5a1e08d39a06b 100644
@@ -10,6 +10,17 @@
 #include "cgroup_iter_memcg.h"
 #include "cgroup_iter_memcg.skel.h"
 
+/*
+ * memcg stats are cached per-cpu and only become visible once the periodic
+ * flusher runs (FLUSH_TIME, 2s), or once pending updates cross
+ * MEMCG_CHARGE_BATCH * num_online_cpus(). That threshold grows with the CPU
+ * count, so on a large machine a single pass does not reach it and
+ * bpf_mem_cgroup_flush_stats() returns without flushing anything. Retry for
+ * long enough to cover a flusher cycle.
+ */
+#define MEMCG_STAT_RETRIES		16
+#define MEMCG_STAT_RETRY_DELAY_US	(250 * 1000)
+
 static int read_stats(struct bpf_link *link)
 {
 	int fd, ret = 0;
@@ -35,11 +46,13 @@ static int read_stats(struct bpf_link *link)
 
 static void test_anon(struct bpf_link *link, struct memcg_query *memcg_query)
 {
+	int retries = 0;
 	void *map;
 	size_t len;
 
 	len = sysconf(_SC_PAGESIZE) * 1024;
 
+retry:
 	/*
 	 * Increase memcg anon usage by mapping and writing
 	 * to a new anon region.
@@ -53,6 +66,12 @@ static void test_anon(struct bpf_link *link, struct memcg_query *memcg_query)
 	if (!ASSERT_OK(read_stats(link), "read stats"))
 		goto cleanup;
 
+	if (!memcg_query->nr_anon_mapped && ++retries < MEMCG_STAT_RETRIES) {
+		usleep(MEMCG_STAT_RETRY_DELAY_US);
+		munmap(map, len);
+		goto retry;
+	}
+
 	ASSERT_GT(memcg_query->nr_anon_mapped, 0, "final anon mapped val");
 
 cleanup:
@@ -61,6 +80,7 @@ static void test_anon(struct bpf_link *link, struct memcg_query *memcg_query)
 
 static void test_file(struct bpf_link *link, struct memcg_query *memcg_query)
 {
+	int retries = 0;
 	void *map;
 	size_t len;
 	char *path;
@@ -76,6 +96,7 @@ static void test_file(struct bpf_link *link, struct memcg_query *memcg_query)
 	fd = open(path, O_CREAT | O_RDWR, 0644);
 	if (!ASSERT_OK_FD(fd, "open fd"))
 		return;
+retry:
 	if (!ASSERT_OK(ftruncate(fd, len), "ftruncate"))
 		goto cleanup_fd;
 
@@ -88,6 +109,13 @@ static void test_file(struct bpf_link *link, struct memcg_query *memcg_query)
 	if (!ASSERT_OK(read_stats(link), "read stats"))
 		goto cleanup_map;
 
+	if ((!memcg_query->nr_file_pages || !memcg_query->nr_file_mapped) &&
+	    ++retries < MEMCG_STAT_RETRIES) {
+		usleep(MEMCG_STAT_RETRY_DELAY_US);
+		munmap(map, len);
+		goto retry;
+	}
+
 	ASSERT_GT(memcg_query->nr_file_pages, 0, "final file value");
 	ASSERT_GT(memcg_query->nr_file_mapped, 0, "final file mapped value");
 
@@ -100,6 +128,7 @@ static void test_file(struct bpf_link *link, struct memcg_query *memcg_query)
 
 static void test_shmem(struct bpf_link *link, struct memcg_query *memcg_query)
 {
+	int retries = 0;
 	size_t len;
 	int fd;
 
@@ -113,12 +142,18 @@ static void test_shmem(struct bpf_link *link, struct memcg_query *memcg_query)
 	if (!ASSERT_OK_FD(fd, "memfd_create"))
 		return;
 
+retry:
 	if (!ASSERT_OK(fallocate(fd, 0, 0, len), "fallocate"))
 		goto cleanup;
 
 	if (!ASSERT_OK(read_stats(link), "read stats"))
 		goto cleanup;
 
+	if (!memcg_query->nr_shmem && ++retries < MEMCG_STAT_RETRIES) {
+		usleep(MEMCG_STAT_RETRY_DELAY_US);
+		goto retry;
+	}
+
 	ASSERT_GT(memcg_query->nr_shmem, 0, "final shmem value");
 
 cleanup:
@@ -127,11 +162,13 @@ static void test_shmem(struct bpf_link *link, struct memcg_query *memcg_query)
 
 static void test_pgfault(struct bpf_link *link, struct memcg_query *memcg_query)
 {
+	int retries = 0;
 	void *map;
 	size_t len;
 
 	len = sysconf(_SC_PAGESIZE) * 1024;
 
+retry:
 	/* Create region to use for triggering a page fault. */
 	map = mmap(NULL, len, PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
 	if (!ASSERT_NEQ(map, MAP_FAILED, "mmap anon"))
@@ -143,6 +180,12 @@ static void test_pgfault(struct bpf_link *link, struct memcg_query *memcg_query)
 	if (!ASSERT_OK(read_stats(link), "read stats"))
 		goto cleanup;
 
+	if (!memcg_query->pgfault && ++retries < MEMCG_STAT_RETRIES) {
+		usleep(MEMCG_STAT_RETRY_DELAY_US);
+		munmap(map, len);
+		goto retry;
+	}
+
 	ASSERT_GT(memcg_query->pgfault, 0, "final pgfault val");
 
 cleanup:
Signature · 1 line
2.53.0
author maintainer
#1562 lore raw

PATCH 1546/1815 nfs: replace atomic bitops sequence with clear_and_wake_up_bit helper

In reply to Greg Kroah-Hartman

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

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

From: Arnaud Bonnet <[email protected]>

[ Upstream commit 61461050da42401b484d03e0fdac02878d235fe6 ]

Commit 8236b0ae31c83 ("bdi: wake up concurrent wb_shutdown() callers.") introduces the clear_and_wake_up_bit() helper as a wrapper for the common clear -> barrier -> wake up bitops sequence.

Use the helper in nfs_clear_invalid_mapping as inode.c already relies on functions from <linux/wait_bit.h> and to homogenize with other subsystems.

---
 fs/nfs/inode.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
fs/nfs/inode.c +1 -3
index 5bcd4027d2033..e538736bb165a 100644
@@ -1531,9 +1531,7 @@ int nfs_clear_invalid_mapping(struct address_space *mapping)
 	ret = nfs_invalidate_mapping(inode, mapping);
 	trace_nfs_invalidate_mapping_exit(inode, ret);
 
-	clear_bit_unlock(NFS_INO_INVALIDATING, bitlock);
-	smp_mb__after_atomic();
-	wake_up_bit(bitlock, NFS_INO_INVALIDATING);
+	clear_and_wake_up_bit(NFS_INO_INVALIDATING, bitlock);
 out:
 	return ret;
 }
Signature · 1 line
2.53.0
author maintainer
#1563 lore raw

PATCH 1547/1815 nfs: refactor pNFS functions using clear_and_wake_up_bit

In reply to Greg Kroah-Hartman

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

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

From: Arnaud Bonnet <[email protected]>

[ Upstream commit 187bfc974eefa9e5d88a0b4ee9d08ae8fe485df4 ]

Commit 8236b0ae31c83 ("bdi: wake up concurrent wb_shutdown() callers.") introduces the clear_and_wake_up_bit() helper as a wrapper for the common clear -> barrier -> wake up bitops sequence.

The file pnfs.c has several helpers with identical contents. Thus they are replaced with the more recent clean_and_wake_up_bit() global helper which describes accurately its effects at the call and still specifies the cleared bit. This also homogenizes the code with other subsystems.

Since the helpers are no longer used after this, they can be safely removed.

---
 fs/nfs/pnfs.c | 35 ++++++++++-------------------------
 1 file changed, 10 insertions(+), 25 deletions(-)
fs/nfs/pnfs.c +10 -25
index b1a30a16287f3..fe5af86f9c486 100644
@@ -2100,15 +2100,6 @@ static bool pnfs_is_first_layoutget(struct pnfs_layout_hdr *lo)
 	return test_bit(NFS_LAYOUT_FIRST_LAYOUTGET, &lo->plh_flags);
 }
 
-static void pnfs_clear_first_layoutget(struct pnfs_layout_hdr *lo)
-{
-	unsigned long *bitlock = &lo->plh_flags;
-
-	clear_bit_unlock(NFS_LAYOUT_FIRST_LAYOUTGET, bitlock);
-	smp_mb__after_atomic();
-	wake_up_bit(bitlock, NFS_LAYOUT_FIRST_LAYOUTGET);
-}
-
 static void _add_to_server_list(struct pnfs_layout_hdr *lo,
 				struct nfs_server *server)
 {
@@ -2284,7 +2275,8 @@ pnfs_update_layout(struct inode *ino,
 					iomode, lo, lseg,
 					PNFS_UPDATE_LAYOUT_INVALID_OPEN);
 			nfs4_schedule_stateid_recovery(server, ctx->state);
-			pnfs_clear_first_layoutget(lo);
+			clear_and_wake_up_bit(NFS_LAYOUT_FIRST_LAYOUTGET,
+				&lo->plh_flags);
 			pnfs_put_layout_hdr(lo);
 			goto lookup_again;
 		}
@@ -2353,7 +2345,8 @@ pnfs_update_layout(struct inode *ino,
 			if (!exception.retry)
 				goto out_put_layout_hdr;
 			if (first)
-				pnfs_clear_first_layoutget(lo);
+				clear_and_wake_up_bit(NFS_LAYOUT_FIRST_LAYOUTGET,
+					&lo->plh_flags);
 			trace_pnfs_update_layout(ino, pos, count,
 				iomode, lo, lseg, PNFS_UPDATE_LAYOUT_RETRY);
 			pnfs_put_layout_hdr(lo);
@@ -2365,7 +2358,7 @@ pnfs_update_layout(struct inode *ino,
 
 out_put_layout_hdr:
 	if (first)
-		pnfs_clear_first_layoutget(lo);
+		clear_and_wake_up_bit(NFS_LAYOUT_FIRST_LAYOUTGET, &lo->plh_flags);
 	trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
 				 PNFS_UPDATE_LAYOUT_EXIT);
 	pnfs_put_layout_hdr(lo);
@@ -2457,7 +2450,7 @@ static void _lgopen_prepare_attached(struct nfs4_opendata *data,
 	lgp = pnfs_alloc_init_layoutget_args(ino, ctx, &current_stateid, &rng,
 					     nfs_io_gfp_mask());
 	if (!lgp) {
-		pnfs_clear_first_layoutget(lo);
+		clear_and_wake_up_bit(NFS_LAYOUT_FIRST_LAYOUTGET, &lo->plh_flags);
 		nfs_layoutget_end(lo);
 		pnfs_put_layout_hdr(lo);
 		return;
@@ -2561,7 +2554,8 @@ void nfs4_lgopen_release(struct nfs4_layoutget *lgp)
 {
 	if (lgp != NULL) {
 		if (lgp->lo) {
-			pnfs_clear_first_layoutget(lgp->lo);
+			clear_and_wake_up_bit(NFS_LAYOUT_FIRST_LAYOUTGET,
+				&lgp->lo->plh_flags);
 			nfs_layoutget_end(lgp->lo);
 		}
 		pnfs_layoutget_free(lgp);
@@ -3274,15 +3268,6 @@ pnfs_generic_pg_readpages(struct nfs_pageio_descriptor *desc)
 }
 EXPORT_SYMBOL_GPL(pnfs_generic_pg_readpages);
 
-static void pnfs_clear_layoutcommitting(struct inode *inode)
-{
-	unsigned long *bitlock = &NFS_I(inode)->flags;
-
-	clear_bit_unlock(NFS_INO_LAYOUTCOMMITTING, bitlock);
-	smp_mb__after_atomic();
-	wake_up_bit(bitlock, NFS_INO_LAYOUTCOMMITTING);
-}
-
 /*
  * There can be multiple RW segments.
  */
@@ -3307,7 +3292,7 @@ static void pnfs_list_write_lseg_done(struct inode *inode, struct list_head *lis
 		pnfs_put_lseg(lseg);
 	}
 
-	pnfs_clear_layoutcommitting(inode);
+	clear_and_wake_up_bit(NFS_INO_LAYOUTCOMMITTING, &NFS_I(inode)->flags);
 }
 
 void pnfs_set_lo_fail(struct pnfs_layout_segment *lseg)
@@ -3447,7 +3432,7 @@ pnfs_layoutcommit_inode(struct inode *inode, bool sync)
 	spin_unlock(&inode->i_lock);
 	kfree(data);
 clear_layoutcommitting:
-	pnfs_clear_layoutcommitting(inode);
+	clear_and_wake_up_bit(NFS_INO_LAYOUTCOMMITTING, &NFS_I(inode)->flags);
 	goto out;
 }
 EXPORT_SYMBOL_GPL(pnfs_layoutcommit_inode);
Signature · 1 line
2.53.0
author maintainer
#1564 lore raw

PATCH 1548/1815 NFSv4: remove callback IDR entry on client allocation failure

In reply to Greg Kroah-Hartman

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

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

From: Ruoyu Wang <[email protected]>

[ Upstream commit d05c2007b3d84ccba11dc6e9cb3202768cc72f14 ]

nfs4_alloc_client() allocates an NFSv4.0 callback identifier before it finishes setting up the client. If any later initialization step fails, the error path frees the nfs_client directly with nfs_free_client(). That bypasses nfs_put_client(), which is where the callback IDR entry is removed during normal teardown.

A failed allocation can therefore leave cb_ident_idr pointing at a freed nfs_client. A later NFSv4.0 callback lookup by cb_ident would find the stale pointer and take a reference to it.

Make the callback IDR removal helper callable by the allocation failure path, and remove the callback identifier before freeing the client.

This was found by a local static-analysis checker for publish-before-free lifetime bugs and confirmed by manual inspection.

Fixes f4eecd5da342 ("NFS implement v4.0 callback_ident")
---
 fs/nfs/client.c     | 14 +++++++++++++-
 fs/nfs/internal.h   |  1 +
 fs/nfs/nfs4client.c |  1 +
 3 files changed, 15 insertions(+), 1 deletion(-)
fs/nfs/client.c +13 -1
index 4dcb91ab30397..60386330aeeca 100644
@@ -215,9 +215,21 @@ static void nfs_cb_idr_remove_locked(struct nfs_client *clp)
 {
 	struct nfs_net *nn = net_generic(clp->cl_net, nfs_net_id);
 
-	if (clp->cl_cb_ident)
+	if (clp->cl_cb_ident) {
 		idr_remove(&nn->cb_ident_idr, clp->cl_cb_ident);
+		clp->cl_cb_ident = 0;
+	}
+}
+
+void nfs_cb_idr_remove(struct nfs_client *clp)
+{
+	struct nfs_net *nn = net_generic(clp->cl_net, nfs_net_id);
+
+	spin_lock(&nn->nfs_client_lock);
+	nfs_cb_idr_remove_locked(clp);
+	spin_unlock(&nn->nfs_client_lock);
 }
+EXPORT_SYMBOL_GPL(nfs_cb_idr_remove);
 
 static void pnfs_init_server(struct nfs_server *server)
 {
fs/nfs/internal.h +1 -0
index e4533f5836321..864fa092bcead 100644
@@ -225,6 +225,7 @@ void nfs_server_copy_userdata(struct nfs_server *, struct nfs_server *);
 
 extern void nfs_put_client(struct nfs_client *);
 extern void nfs_free_client(struct nfs_client *);
+void nfs_cb_idr_remove(struct nfs_client *clp);
 extern struct nfs_client *nfs4_find_client_ident(struct net *, int);
 extern struct nfs_client *
 nfs4_find_client_sessionid(struct net *, const struct sockaddr *,
fs/nfs/nfs4client.c +1 -0
index 819e435c3a42b..5bc6dc9c1135a 100644
@@ -261,6 +261,7 @@ struct nfs_client *nfs4_alloc_client(const struct nfs_client_initdata *cl_init)
 	return clp;
 
 error:
+	nfs_cb_idr_remove(clp);
 	nfs_free_client(clp);
 	return ERR_PTR(err);
 }
Signature · 1 line
2.53.0
author maintainer
#1565 lore raw

PATCH 1549/1815 pnfs/blocklayout: Fix device leaks on parse failure

In reply to Greg Kroah-Hartman

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

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

From: ZhangGuoDong <[email protected]>

[ Upstream commit c056f817e4200fb18079d5052c273a22f191ff0a ]

bl_parse_concat() and bl_parse_stripe() allocate a child device array and then parse each child in turn. If parsing a child fails, the failed child is not counted in nr_children and the parent may be left with a children array that bl_free_device() will not release when nr_children is zero.

Release the failed child and the already parsed children before returning the error. Also make bl_free_device() release the child array whenever the children pointer is set, so that partially initialised concat or stripe devices are cleaned up correctly.

bl_parse_scsi() can also fail after assigning d->bdev_file and dropping the file reference. Clear the pointer after fput() so that an outer cleanup path does not put it again.

Fixes 5c83746a0cf2 ("pnfs/blocklayout: in-kernel GETDEVICEINFO XDR parsing")
---
 fs/nfs/blocklayout/dev.c | 21 +++++++++++++++------
 1 file changed, 15 insertions(+), 6 deletions(-)
fs/nfs/blocklayout/dev.c +15 -6
index bb35f88501cea..db4bb0a6283e5 100644
@@ -85,15 +85,17 @@ bl_free_device(struct pnfs_block_dev *dev)
 {
 	bl_unregister_dev(dev);
 
-	if (dev->nr_children) {
+	if (dev->children) {
 		int i;
 
 		for (i = 0; i < dev->nr_children; i++)
 			bl_free_device(&dev->children[i]);
 		kfree(dev->children);
-	} else {
-		if (dev->bdev_file)
-			fput(dev->bdev_file);
+		dev->children = NULL;
+		dev->nr_children = 0;
+	} else if (dev->bdev_file) {
+		fput(dev->bdev_file);
+		dev->bdev_file = NULL;
 	}
 }
 
@@ -437,6 +439,7 @@ bl_parse_scsi(struct nfs_server *server, struct pnfs_block_dev *d,
 
 out_blkdev_put:
 	fput(d->bdev_file);
+	d->bdev_file = NULL;
 	return error;
 }
 
@@ -472,8 +475,11 @@ bl_parse_concat(struct nfs_server *server, struct pnfs_block_dev *d,
 	for (i = 0; i < v->concat.volumes_count; i++) {
 		ret = bl_parse_deviceid(server, &d->children[i],
 				volumes, v->concat.volumes[i], gfp_mask);
-		if (ret)
+		if (ret) {
+			bl_free_device(&d->children[i]);
+			bl_free_device(d);
 			return ret;
+		}
 
 		d->nr_children++;
 		d->children[i].start += len;
@@ -501,8 +507,11 @@ bl_parse_stripe(struct nfs_server *server, struct pnfs_block_dev *d,
 	for (i = 0; i < v->stripe.volumes_count; i++) {
 		ret = bl_parse_deviceid(server, &d->children[i],
 				volumes, v->stripe.volumes[i], gfp_mask);
-		if (ret)
+		if (ret) {
+			bl_free_device(&d->children[i]);
+			bl_free_device(d);
 			return ret;
+		}
 
 		d->nr_children++;
 		len += d->children[i].len;
Signature · 1 line
2.53.0
author maintainer
#1566 lore raw

PATCH 1550/1815 NFS: Fix delayed delegation return list handling

In reply to Greg Kroah-Hartman

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

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

From: Guangshuo Li <[email protected]>

[ Upstream commit 68c03755577ac90e31e38c7ec787301cf6be5331 ]

The delayed delegation return handling added a separate delegations_delayed list to keep delegations whose return needs to be retried later. The delayed list is then spliced back to delegations_return by nfs_server_clear_delayed_delegations(), which also causes the state manager to retry the delegation return.

However, nfs_end_delegation_return() still moves delayed delegations to delegations_return instead of delegations_delayed. As a result, the new delayed list is never populated, nfs_server_clear_delayed_delegations() always returns false, and NFS4CLNT_DELEGRETURN is not set again to drive a retry.

Move delayed delegations to delegations_delayed so that the delayed return path can splice them back to delegations_return and schedule the retry as intended.

Fixes 4039fbedcbcb ("NFS: fix delayed delegation return handling")
---
 fs/nfs/delegation.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfs/delegation.c +1 -1
index 284437fa3f872..ab3e441464a66 100644
@@ -604,7 +604,7 @@ static int nfs_end_delegation_return(struct inode *inode,
 	spin_lock(&server->delegations_lock);
 	if (list_empty(&delegation->entry))
 		refcount_inc(&delegation->refcount);
-	list_move_tail(&delegation->entry, &server->delegations_return);
+	list_move_tail(&delegation->entry, &server->delegations_delayed);
 	spin_unlock(&server->delegations_lock);
 	set_bit(NFS4CLNT_DELEGRETURN_DELAYED, &server->nfs_client->cl_state);
 abort:
Signature · 1 line
2.53.0
author maintainer
#1567 lore raw

PATCH 1551/1815 NFSv4/flexfiles: fix NULL dereference for NFSv4.0 data servers

In reply to Greg Kroah-Hartman

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

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

From: Jeuk Kim <[email protected]>

[ Upstream commit 2b03ebbf8d5e8f6af4ecd6c65375232dd1ec32cc ]

flexfiles accepts NFSv4.0 data servers, but two NFSv4 code paths assume the data server client has a session. Unlike NFSv4.1+, an NFSv4.0 client has no session (clp->cl_session is NULL; it uses clp->cl_slot_tbl), so I/O to a v4.0 flexfiles DS oopses:

- nfs4_init_ds_session() dereferences clp->cl_session->session_state while seeding the DS lease. It also only seeds cl_lease_time when NFS4_SESSION_INITING is set; without a session that never happens, so cl_lease_time stays 0 and nfs4_renew_state() busy-loops, requeuing every 5 seconds. Seed the lease whenever there is no session and return before touching session state.

- ff_layout_async_handle_error_v4() dereferences

    clp->cl_session->fc_slot_table on every DS I/O error. Fall back to the
    v4.0 transport slot table (clp->cl_slot_tbl) when there is no session.
Fixes a7878ca14008 ("nfs: flexfilelayout: remove v3-only data server limitation")
---
 fs/nfs/flexfilelayout/flexfilelayout.c |  3 ++-
 fs/nfs/nfs4session.c                   | 16 +++++++++++-----
 2 files changed, 13 insertions(+), 6 deletions(-)
fs/nfs/flexfilelayout/flexfilelayout.c +2 -1
index c4aa995026f67..ef26fcab9c103 100644
@@ -1322,7 +1322,8 @@ static int ff_layout_async_handle_error_v4(struct rpc_task *task,
 	struct pnfs_layout_hdr *lo = lseg->pls_layout;
 	struct inode *inode = lo->plh_inode;
 	struct nfs4_deviceid_node *devid = FF_LAYOUT_DEVID_NODE(lseg, idx, dss_id);
-	struct nfs4_slot_table *tbl = &clp->cl_session->fc_slot_table;
+	struct nfs4_slot_table *tbl = nfs4_has_session(clp) ?
+		&clp->cl_session->fc_slot_table : clp->cl_slot_tbl;
 
 	switch (op_status) {
 	case NFS4_OK:
fs/nfs/nfs4session.c +11 -5
index 5c128957a0a41..993f0db7cf5e4 100644
@@ -632,16 +632,22 @@ int nfs4_init_ds_session(struct nfs_client *clp, unsigned long lease_time)
 	int ret;
 
 	spin_lock(&clp->cl_lock);
-	if (test_and_clear_bit(NFS4_SESSION_INITING, &session->session_state)) {
-		/*
-		 * Do not set NFS_CS_CHECK_LEASE_TIME instead set the
-		 * DS lease to be equal to the MDS lease.
-		 */
+	/*
+	 * Do not set NFS_CS_CHECK_LEASE_TIME instead set the
+	 * DS lease to be equal to the MDS lease.
+	 *
+	 * A v4.0 DS has no session, so seed the lease every time.
+	 */
+	if (!session ||
+	    test_and_clear_bit(NFS4_SESSION_INITING, &session->session_state)) {
 		clp->cl_lease_time = lease_time;
 		clp->cl_last_renewal = jiffies;
 	}
 	spin_unlock(&clp->cl_lock);
 
+	if (!session)
+		return 0;
+
 	ret = nfs41_check_session_ready(clp);
 	if (ret)
 		return ret;
Signature · 1 line
2.53.0
author maintainer
#1568 lore raw

PATCH 1552/1815 NFSv4: Fix incorrect argument passed to nfs4_delete_lease() in nfs4_add_lease()

In reply to Greg Kroah-Hartman

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

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

From: Zhansong Gao <[email protected]>

[ Upstream commit 468e458ffde907ba19acd2102ca1fbb8f6fbede2 ]

When nfs4_add_lease() races with a delegation return, it calls nfs4_delete_lease() to clean up. Previously, it passed priv, which can legitimately be NULL. Passing a NULL priv eventually leads to a NULL pointer dereference in generic_setlease().

Fixes e93a5e9306a5 ("NFSv4: Add support for application leases underpinned by a delegation")
---
 fs/nfs/nfs4proc.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/nfs/nfs4proc.c +3 -1
index 5709c6fea85bb..2edd16e4981a2 100644
@@ -7762,6 +7762,7 @@ static int nfs4_add_lease(struct file *file, int arg, struct file_lease **lease,
 {
 	struct inode *inode = file_inode(file);
 	fmode_t type = arg == F_RDLCK ? FMODE_READ : FMODE_WRITE;
+	fl_owner_t owner = (*lease)->c.flc_owner;
 	int ret;
 
 	/* No delegation, no lease */
@@ -7771,7 +7772,8 @@ static int nfs4_add_lease(struct file *file, int arg, struct file_lease **lease,
 	if (ret || nfs4_have_delegation(inode, type, 0))
 		return ret;
 	/* We raced with a delegation return */
-	nfs4_delete_lease(file, priv);
+	dprintk("%s: raced with a delegation return\n", __func__);
+	nfs4_delete_lease(file, &owner);
 	return -EAGAIN;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1569 lore raw

PATCH 1553/1815 nfs: fix ENXIO on O_CREAT open of existing symlink over NFSv3

In reply to Greg Kroah-Hartman

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

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

From: Michael Nemanov <[email protected]>

[ Upstream commit 10f307e525a1783570a39eb9ac146d45f4f16b3e ]

When open(2) is called with O_CREAT on a path that already exists as a symlink, over an NFSv3 mount with a cold dcache, the kernel returns ENXIO instead of following the symlink to its target.

Reproducer script (MNT is an NFSv3 mount, kernel is 7.1-rc6):

MNT=/mnt/export
ln -sf /tmp/target $MNT/mylink
echo 3 | sudo tee /proc/sys/vm/drop_caches # cold dcache

python3 - <<'EOF'
import os
fd = os.open('/mnt/export/mylink', os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o666) os.close(fd)
EOF

Expected: success (follow symlink, open target)
Actual:   OSError: [Errno 6] No such device or address

The bug does not trigger when the dcache is warm (e.g. after a prior stat(2)), because lookup_open() then finds a positive dentry and skips atomic_open entirely, leaving symlink resolution to the VFS.

Root cause:
nfs_atomic_open_v23(), registered as inode->i_op->atomic_open for NFSv3, handles O_CREAT by sending a CREATE UNCHECKED RPC. As implemented in nfsd3_create_file() (fs/nfsd/nfs3proc.c) and as required by RFC 1813 (3.3.8), when the name already exists as a non-regular file the server returns NFS3_OK with the existing object's file handle rather than NFS3ERR_EXIST causing nfs_do_create() to return 0 with the dentry now pointing to a symlink.
The code then unconditionally calls finish_open(), which dispatches through inode->i_fop->open(). Symlink inodes never have i_fop set — the VFS initialises it to &no_open_fops because POSIX requires open(2) to follow symlinks, never open them directly. no_open() returns -ENXIO.

Fix:
After nfs_do_create() succeeds, verify the returned inode is a regular file before calling finish_open(). If the object is not regular, return finish_no_open(file, NULL) so the VFS follows the symlink through the normal open path. NULL is passed because nfs_do_create() instantiates the inode on the dentry already owned by the caller; passing dentry back would cause atomic_open() to dput() it a second time. !S_ISREG() is used rather than S_ISLNK() to cover any other non-regular types a server might return.

Changes in v2:
- Pass NULL to finish_no_open() per Trond's feedback.

Fixes 7c6c5249f061 ("NFS: add atomic_open for NFSv3 to handle O_TRUNC correctly.")
[[email protected]: use d_is_reg() to catch negative dentries]
---
 fs/nfs/dir.c | 7 +++++++
 1 file changed, 7 insertions(+)
fs/nfs/dir.c +7 -0
index c7caffb31935c..e97ce5240c18e 100644
@@ -2319,6 +2319,13 @@ int nfs_atomic_open_v23(struct inode *dir, struct dentry *dentry,
 	if (open_flags & O_CREAT) {
 		error = nfs_do_create(dir, dentry, mode, open_flags);
 		if (!error) {
+			/* With UNCHECKED mode, a server may return NFS3_OK for
+			 * a pre-existing non-regular file (e.g. a symlink).
+			 * Let the VFS handle it; calling finish_open() would
+			 * hit no_open() and return -ENXIO.
+			 */
+			if (!d_is_reg(dentry))
+				return finish_no_open(file, NULL);
 			file->f_mode |= FMODE_CREATED;
 			return finish_open(file, dentry, NULL);
 		} else if (error != -EEXIST || open_flags & O_EXCL)
Signature · 1 line
2.53.0
author maintainer
#1570 lore raw

PATCH 1554/1815 clk: devres: fix cleanup in devm_clk_get_optional_enabled_with_rate()

In reply to Greg Kroah-Hartman

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

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

From: Onur Özkan <[email protected]>

[ Upstream commit 0d4d262c1664365e17e0a5ba2ab79f4db484b44e ]

devm_clk_get_optional_enabled_with_rate() registers its cleanup action before setting the clock rate. If setting the rate fails, it attempts to disable and unprepare a clock that was never enabled. This issue was spotted while reviewing "rust: clk: add devres-managed clks" [1].

Register the cleanup action only after successfully preparing and enabling the clock.

[1]: https://lore.kernel.org/rust-for-linux/[email protected]

Fixes 9934a1bd45b2 ("clk: provide devm_clk_get_optional_enabled_with_rate()")
---
 drivers/clk/clk-devres.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/clk/clk-devres.c +10 -2
index 994d5bc5168be..697d102449c10 100644
@@ -99,6 +99,11 @@ struct clk *devm_clk_get_optional_enabled(struct device *dev, const char *id)
 }
 EXPORT_SYMBOL_GPL(devm_clk_get_optional_enabled);
 
+static void devm_clk_disable_unprepare(void *data)
+{
+	clk_disable_unprepare(data);
+}
+
 struct clk *devm_clk_get_optional_enabled_with_rate(struct device *dev,
 						    const char *id,
 						    unsigned long rate)
@@ -106,8 +111,7 @@ struct clk *devm_clk_get_optional_enabled_with_rate(struct device *dev,
 	struct clk *clk;
 	int ret;
 
-	clk = __devm_clk_get(dev, id, clk_get_optional, NULL,
-			     clk_disable_unprepare);
+	clk = devm_clk_get_optional(dev, id);
 	if (IS_ERR(clk))
 		return ERR_CAST(clk);
 
@@ -119,6 +123,10 @@ struct clk *devm_clk_get_optional_enabled_with_rate(struct device *dev,
 	if (ret)
 		goto out_put_clk;
 
+	ret = devm_add_action_or_reset(dev, devm_clk_disable_unprepare, clk);
+	if (ret)
+		goto out_put_clk;
+
 	return clk;
 
 out_put_clk:
Signature · 1 line
2.53.0
author maintainer
#1571 lore raw

PATCH 1555/1815 clk: ti: mux: resolve parent clocks by DT index, not by name

In reply to Greg Kroah-Hartman

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

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

From: Mathieu Dubois-Briand <[email protected]>

[ Upstream commit 667f420c09f1417c9f07798e32432c901915209d ]

Resolve parent clocks by their index into the device tree "clocks" property rather than matching names as strings. Name-based matching is fragile because a clock's "clock-output-names" value in its provider node can differ from the name used to reference it in a consumer node, and because names must be globally unique across all clock providers.

On AM335x, this caused broken clock trees where some clocks failed to enable because their parents could not be found.

Replace of_clk_parent_fill() with a clk_parent_data array that sets .index to the array position.

Fixes ec7aa25fa483 ("ARM: dts: Use clock-output-names for am3")
---
 drivers/clk/ti/mux.c | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)
drivers/clk/ti/mux.c +11 -9
index d6a0ccfd81dbe..ded4432f7528c 100644
@@ -119,7 +119,7 @@ const struct clk_ops ti_clk_mux_ops = {
 };
 
 static struct clk *_register_mux(struct device_node *node, const char *name,
-				 const char * const *parent_names,
+				 const struct clk_parent_data *parent_data,
 				 u8 num_parents, unsigned long flags,
 				 struct clk_omap_reg *reg, u8 shift, u32 mask,
 				 s8 latch, u8 clk_mux_flags, u32 *table)
@@ -136,7 +136,7 @@ static struct clk *_register_mux(struct device_node *node, const char *name,
 	init.name = name;
 	init.ops = &ti_clk_mux_ops;
 	init.flags = flags;
-	init.parent_names = parent_names;
+	init.parent_data = parent_data;
 	init.num_parents = num_parents;
 
 	/* struct clk_mux assignments */
@@ -167,24 +167,26 @@ static void of_mux_clk_setup(struct device_node *node)
 	struct clk *clk;
 	struct clk_omap_reg reg;
 	unsigned int num_parents;
-	const char **parent_names;
+	struct clk_parent_data *parent_data;
 	const char *name;
 	u8 clk_mux_flags = 0;
 	u32 mask = 0;
 	u32 shift = 0;
 	s32 latch = -EINVAL;
 	u32 flags = CLK_SET_RATE_NO_REPARENT;
+	int i;
 
 	num_parents = of_clk_get_parent_count(node);
 	if (num_parents < 2) {
 		pr_err("mux-clock %pOFn must have parents\n", node);
 		return;
 	}
-	parent_names = kcalloc(num_parents, sizeof(char *), GFP_KERNEL);
-	if (!parent_names)
-		goto cleanup;
+	parent_data = kcalloc(num_parents, sizeof(*parent_data), GFP_KERNEL);
+	if (!parent_data)
+		return;
 
-	of_clk_parent_fill(node, parent_names, num_parents);
+	for (i = 0; i < num_parents; i++)
+		parent_data[i].index = i;
 
 	if (ti_clk_get_reg_addr(node, 0, &reg))
 		goto cleanup;
@@ -207,7 +209,7 @@ static void of_mux_clk_setup(struct device_node *node)
 	mask = (1 << fls(mask)) - 1;
 
 	name = ti_dt_clk_name(node);
-	clk = _register_mux(node, name, parent_names, num_parents,
+	clk = _register_mux(node, name, parent_data, num_parents,
 			    flags, &reg, shift, mask, latch, clk_mux_flags,
 			    NULL);
 
@@ -215,7 +217,7 @@ static void of_mux_clk_setup(struct device_node *node)
 		of_clk_add_provider(node, of_clk_src_simple_get, clk);
 
 cleanup:
-	kfree(parent_names);
+	kfree(parent_data);
 }
 CLK_OF_DECLARE(mux_clk, "ti,mux-clock", of_mux_clk_setup);
 
Signature · 1 line
2.53.0
author maintainer
#1572 lore raw

PATCH 1556/1815 regulator: tps65185: wait for the IC to wake before the first I2C access

In reply to Greg Kroah-Hartman

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

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

From: Mario Rugiero <[email protected]>

[ Upstream commit 44f7b876b7c6c7b3a219b7a810d3d9548df21540 ]

The probe drives WAKEUP high with GPIOD_OUT_HIGH, enables the input supply, and then issues a regmap_update_bits() on INT_EN2 with no wait anywhere in between. The TPS65185 data sheet (TI SLVSAQ8G, February 2011, revised September 2017), section 7.6 "Timing Requirements: Data Transmission", Figure 2 "Power-Up and Power-Down Timing Diagram", footnote 1, requires 1.8 ms minimum between the WAKEUP rising edge and the IC being ready to accept an I2C transaction. The driver calls no delay function anywhere, and nothing on that path is guaranteed to take that long.

On an RK3026 board the first transfer was NAKed:

tps65185 0-0068: error -ENXIO: failed to enable temp irq

-ENXIO here is rk3x_i2c reporting REG_INT_NAKRCV. Probe failed, so vposneg never registered and its consumer deferred indefinitely.

Wait after the supply rather than at the gpiod_get(). Figure 2 times that 1.8 ms from a WAKEUP edge with VIN already up, whereas this driver asserts WAKEUP before enabling vin-supply; the data sheet does not describe that order, so on a board whose vin-supply is a switched regulator that was off, a wait placed at the gpiod_get() could elapse before the part had power. Waiting from whichever of the two comes last satisfies the specified case and is the conservative choice in the other.

It also goes above the interrupt request rather than immediately before the INT_EN2 write, because that write is not necessarily the first
transfer: tps65185_irq_thread() reads INT1 and INT2, and it is requested with IRQF_TRIGGER_LOW, so it can run as soon as the handler is installed.

Tested on an ONYX BOOX C67ML (RK3026): the chip now probes, all three regulators register and the EPD controller comes up.

Fixes b0fc1e770194 ("regulator: Add TPS65185 driver")
---
 drivers/regulator/tps65185.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/regulator/tps65185.c +6 -0
index 1f13e4156cab1..6a3130177e7a3 100644
@@ -5,6 +5,7 @@
 
 #include <linux/cleanup.h>
 #include <linux/completion.h>
+#include <linux/delay.h>
 #include <linux/gpio/consumer.h>
 #include <linux/i2c.h>
 #include <linux/module.h>
@@ -375,6 +376,11 @@ static int tps65185_probe(struct i2c_client *client)
 		return dev_err_probe(&client->dev, ret,
 				     "failed to get vin regulator\n");
 
+	// TPS65185x PMIC for E Ink Vizplex Enabled Electronic Paper Display Chapter 7.6 Figure 2:
+	// "Minimum delay time between WAKEUP rising edge and IC ready to accept I2C transaction."
+	// https://www.ti.com/lit/ds/symlink/tps65185.pdf
+	usleep_range(1800, 3000);
+
 	data->dev = &client->dev;
 	i2c_set_clientdata(client, data);
 
Signature · 1 line
2.53.0
author maintainer
#1573 lore raw

PATCH 1557/1815 bpf, xdp: move offload check into dev_xdp_install()

In reply to Greg Kroah-Hartman

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

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

From: Jiayuan Chen <[email protected]>

[ Upstream commit ad27ed7d2309419a129078d781504f486b1b469a ]

bpf_xdp_link_update() calls dev_xdp_install() directly and skips dev_xdp_attach(), so the checks in dev_xdp_attach() do not run. A user can make an XDP link with a normal program and then swap in an offloaded or device-bound program with BPF_LINK_UPDATE, which puts it on the software path.

dev_xdp_install() is the one place all three paths go through:
"ip link set xdp" and BPF_LINK_CREATE reach it via dev_xdp_attach(), and BPF_LINK_UPDATE calls it directly. So move the program checks (offloaded, bound to another device, device-bound in generic mode, native vs generic, DEVMAP and CPUMAP) there, and keep only the netlink-flag check (XDP_FLAGS_UPDATE_IF_NOEXIST) in dev_xdp_attach().

Fixes 026a4c28e1db3 ("bpf, xdp: Implement LINK_UPDATE for BPF XDP link")
---
 net/core/dev.c | 59 ++++++++++++++++++++++++++------------------------
 1 file changed, 31 insertions(+), 28 deletions(-)
net/core/dev.c +31 -28
index ece6700536d9b..5ac31370df937 100644
@@ -10333,6 +10333,37 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
 
 	netdev_assert_locked_ops_compat(dev);
 
+	if (prog) {
+		enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
+					       ? XDP_MODE_DRV : XDP_MODE_SKB;
+		bool offload = mode == XDP_MODE_HW;
+
+		if (!offload && dev_xdp_prog(dev, other_mode)) {
+			NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
+			return -EEXIST;
+		}
+		if (!offload && bpf_prog_is_offloaded(prog->aux)) {
+			NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
+			return -EINVAL;
+		}
+		if (bpf_prog_is_dev_bound(prog->aux) && !bpf_offload_dev_match(prog, dev)) {
+			NL_SET_ERR_MSG(extack, "Program bound to different device");
+			return -EINVAL;
+		}
+		if (bpf_prog_is_dev_bound(prog->aux) && mode == XDP_MODE_SKB) {
+			NL_SET_ERR_MSG(extack, "Can't attach device-bound programs in generic mode");
+			return -EINVAL;
+		}
+		if (prog->expected_attach_type == BPF_XDP_DEVMAP) {
+			NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
+			return -EINVAL;
+		}
+		if (prog->expected_attach_type == BPF_XDP_CPUMAP) {
+			NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
+			return -EINVAL;
+		}
+	}
+
 	if (dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED &&
 	    prog && !prog->aux->xdp_has_frags) {
 		NL_SET_ERR_MSG(extack, "unable to install XDP to device using tcp-data-split");
@@ -10472,38 +10503,10 @@ static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack
 		new_prog = link->link.prog;
 
 	if (new_prog) {
-		bool offload = mode == XDP_MODE_HW;
-		enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
-					       ? XDP_MODE_DRV : XDP_MODE_SKB;
-
 		if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
 			NL_SET_ERR_MSG(extack, "XDP program already attached");
 			return -EBUSY;
 		}
-		if (!offload && dev_xdp_prog(dev, other_mode)) {
-			NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
-			return -EEXIST;
-		}
-		if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
-			NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
-			return -EINVAL;
-		}
-		if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
-			NL_SET_ERR_MSG(extack, "Program bound to different device");
-			return -EINVAL;
-		}
-		if (bpf_prog_is_dev_bound(new_prog->aux) && mode == XDP_MODE_SKB) {
-			NL_SET_ERR_MSG(extack, "Can't attach device-bound programs in generic mode");
-			return -EINVAL;
-		}
-		if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
-			NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
-			return -EINVAL;
-		}
-		if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
-			NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
-			return -EINVAL;
-		}
 	}
 
 	/* don't call drivers if the effective program didn't change */
Signature · 1 line
2.53.0
author maintainer
#1574 lore raw

PATCH 1558/1815 can: m_can: Use of_property_present() for wakeup-source

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 966506838a4a8f51abcac8db67e6c2980f366134 ]

The 'wakeup-source' property is declared as a phandle-array in both YAML bindings and Device Tree source files. However, the driver currently uses of_property_read_bool() to check for its existence.

According to the function's documentation, usage on non-boolean property types is deprecated. Switch to of_property_present() to comply with the recommended API for checking the presence of a property.

---
 drivers/net/can/m_can/m_can.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/can/m_can/m_can.c +1 -1
index eb856547ae7df..16f80607e150e 100644
@@ -2464,7 +2464,7 @@ struct m_can_classdev *m_can_class_allocate_dev(struct device *dev,
 		return ERR_PTR(ret);
 	}
 
-	if (dev->of_node && of_property_read_bool(dev->of_node, "wakeup-source"))
+	if (dev->of_node && of_property_present(dev->of_node, "wakeup-source"))
 		device_set_wakeup_capable(dev, true);
 
 	/* Get TX FIFO size
Signature · 1 line
2.53.0
author maintainer
#1575 lore raw

PATCH 1559/1815 octeontx2-af: initialize lmac_bmap in rvu_mcs_set_lmac_bmap()

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

[ Upstream commit 4b92a3710d4a1d850ed6421c773e735cdca69b07 ]

rvu_mcs_set_lmac_bmap() declares lmac_bmap without initializing it and only sets bits for valid lmacs with set_bit(), which ORs into the word without clearing it first. Bits for invalid or skipped ports keep whatever was on the stack, and the garbage is stored into mcs->hw->lmac_bmap.

Initialize lmac_bmap to 0 so only valid lmacs are marked.

Found with Clang's -Wconditional-uninitialized.

---
 drivers/net/ethernet/marvell/octeontx2/af/mcs_rvu_if.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/marvell/octeontx2/af/mcs_rvu_if.c +1 -1
index d98b49f47970b..fce22e314cac0 100644
@@ -856,7 +856,7 @@ int rvu_mbox_handler_mcs_ctrl_pkt_rule_write(struct rvu *rvu,
 static void rvu_mcs_set_lmac_bmap(struct rvu *rvu)
 {
 	struct mcs *mcs = mcs_get_pdata(0);
-	unsigned long lmac_bmap;
+	unsigned long lmac_bmap = 0;
 	int cgx, lmac, port;
 
 	for (port = 0; port < mcs->hw->lmac_cnt; port++) {
Signature · 1 line
2.53.0
author maintainer
#1576 lore raw

PATCH 1560/1815 hinic3: Fix skb linearization mismatch and drop skb when skb_checksum_help() failed

In reply to Greg Kroah-Hartman

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

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

From: Fan Gong <[email protected]>

[ Upstream commit d0c2bed6927cbfa2cb51f240b4812bf6916bce0e ]

Previously, hinic3_send_one_skb() cached the skb fragment count before calling hinic3_tx_offload(). If hinic3_tx_csum() falls back to skb_checksum_help() for unsupported tunnel packets, the skb may be linearized. Continuing to build the TX descriptor with the stale fragment count leads to a descriptor mismatch, which can trigger out-of-bounds DMA reads or IOMMU faults.

Furthermore, the old code ignored the return value of skb_checksum_help(), transmitting corrupted packets with incomplete checksums upon failure.

Fix this by:
1. Moving the hinic3_tx_offload() call before calculating 'num_sge' to ensure the correct fragment count is used if the SKB is linearized.
2. Propagating skb_checksum_help() errors and returning HINIC3_TX_OFFLOAD_INVALID to properly drop the skb.

---
 drivers/net/ethernet/huawei/hinic3/hinic3_tx.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/net/ethernet/huawei/hinic3/hinic3_tx.c +6 -3
index 9306bf0020caf..cc541e7a23186 100644
@@ -261,8 +261,7 @@ static int hinic3_tx_csum(struct hinic3_txq *txq, struct hinic3_sq_task *task,
 		    ((struct udphdr *)skb_transport_header(skb))->dest !=
 		    VXLAN_OFFLOAD_PORT_LE) {
 			/* Unsupported tunnel packet, disable csum offload */
-			skb_checksum_help(skb);
-			return 0;
+			return skb_checksum_help(skb);
 		}
 	}
 
@@ -412,6 +411,10 @@ static u32 hinic3_tx_offload(struct sk_buff *skb, struct hinic3_sq_task *task,
 		offload |= HINIC3_TX_OFFLOAD_TSO;
 	} else {
 		tso_cs_en = hinic3_tx_csum(txq, task, skb);
+		if (tso_cs_en < 0) {
+			offload = HINIC3_TX_OFFLOAD_INVALID;
+			return offload;
+		}
 		if (tso_cs_en)
 			offload |= HINIC3_TX_OFFLOAD_CSUM;
 	}
@@ -545,6 +548,7 @@ static netdev_tx_t hinic3_send_one_skb(struct sk_buff *skb,
 		skb->len = MIN_SKB_LEN;
 	}
 
+	offload = hinic3_tx_offload(skb, &task, &queue_info, txq);
 	num_sge = skb_shinfo(skb)->nr_frags + 1;
 	/* assume normal wqe format + 1 wqebb for task info */
 	wqebb_cnt = num_sge + 1;
@@ -560,7 +564,6 @@ static netdev_tx_t hinic3_send_one_skb(struct sk_buff *skb,
 		return NETDEV_TX_BUSY;
 	}
 
-	offload = hinic3_tx_offload(skb, &task, &queue_info, txq);
 	if (unlikely(offload == HINIC3_TX_OFFLOAD_INVALID)) {
 		goto err_drop_pkt;
 	} else if (!offload) {
Signature · 1 line
2.53.0
author maintainer
#1577 lore raw

PATCH 1561/1815 drm/xe: tests: fix error message in xe_migrate_sanity_test()

In reply to Greg Kroah-Hartman

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

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

From: Dan Carpenter <[email protected]>

[ Upstream commit 3d318fe4e99a627aa3c2980699e2e9f13ad18516 ]

This is supposed to print the error code but there is a copy and paste bug so it prints "bo" instead of "err".

Fixes dd08ebf6c352 ("drm/xe: Introduce a new DRM driver for Intel GPUs")
(cherry picked from commit 28a4198c52a1468fc1b620a9837557ea1dc1766d)
---
 drivers/gpu/drm/xe/tests/xe_migrate.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/gpu/drm/xe/tests/xe_migrate.c +1 -2
index 3c1be809be82d..f10d9513747b4 100644
@@ -198,8 +198,7 @@ static void xe_migrate_sanity_test(struct xe_migrate *m, struct kunit *test,
 
 	err = xe_bo_vmap(bo);
 	if (err) {
-		KUNIT_FAIL(test, "Failed to vmap our pagetables: %li\n",
-			   PTR_ERR(bo));
+		KUNIT_FAIL(test, "Failed to vmap our pagetables: %d\n", err);
 		return;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#1578 lore raw

PATCH 1562/1815 ptp: netc: skip PEROUT disable if channel is not enabled

In reply to Greg Kroah-Hartman

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

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

From: Wei Fang <[email protected]>

[ Upstream commit 273480bb836e515353f30a1e70b21a2382de666e ]

When userspace calls ioctl(PTP_PEROUT_REQUEST) with period = 0 to disable a PEROUT channel that is not enabled, the driver incorrectly enters the disable path. Since the channel's struct netc_pp was previously zeroed, pp->alarm_id evaluates to 0, causing priv->fs_alarm_bitmap &= ~BIT(0) to silently revoke the alarm 0 allocation from whichever channel is actively using it. This can cause two channels conflict over the same hardware alarm configuration and corrupt their periodic output signals.

Therefore, guard the disable path with a check on pp->enabled and return early if the channel is not enabled.

---
 drivers/ptp/ptp_netc.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/ptp/ptp_netc.c +3 -0
index 1c20d7efab929..59db08e189e6e 100644
@@ -482,6 +482,9 @@ static int net_timer_enable_perout(struct netc_timer *priv,
 
 		netc_timer_enable_periodic_pulse(priv, channel);
 	} else {
+		if (!pp->enabled)
+			goto unlock_spinlock;
+
 		netc_timer_disable_periodic_pulse(priv, channel);
 		priv->fs_alarm_bitmap &= ~BIT(pp->alarm_id);
 		memset(pp, 0, sizeof(*pp));
Signature · 1 line
2.53.0
author maintainer
#1579 lore raw

PATCH 1563/1815 ionic: add missing dma_rmb() after the completion publish check

In reply to Greg Kroah-Hartman

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

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

From: Eric Joyner <[email protected]>

[ Upstream commit 621f44af8c5b373de2b2e19a4a8db9e45c3c659a ]

Each completion service routine tests a device-written publish flag and then reads the rest of the descriptor with nothing ordering those loads. A control dependency does not order loads, so a weakly ordered CPU may satisfy the payload reads from a cache line state observed before the flag became valid. Add the barrier to all four completion paths.

Fixes 1d062b7b6f64 ("ionic: Add basic adminq support")
Fixes 0f3154e6bcb3 ("ionic: Add Tx and Rx handling")
Fixes 77ceb68e29cc ("ionic: Add notifyq support")
---
 drivers/net/ethernet/pensando/ionic/ionic_main.c | 4 ++++
 drivers/net/ethernet/pensando/ionic/ionic_txrx.c | 4 ++++
 2 files changed, 8 insertions(+)
drivers/net/ethernet/pensando/ionic/ionic_main.c +4 -0
index 6e6f3ed07271b..10501be9ef956 100644
@@ -269,6 +269,8 @@ bool ionic_notifyq_service(struct ionic_cq *cq)
 	if ((s64)(eid - lif->last_eid) <= 0)
 		return false;
 
+	dma_rmb();
+
 	lif->last_eid = eid;
 
 	dev_dbg(lif->ionic->dev, "notifyq event:\n");
@@ -314,6 +316,8 @@ bool ionic_adminq_service(struct ionic_cq *cq)
 	if (!color_match(comp->color, cq->done_color))
 		return false;
 
+	dma_rmb();
+
 	/* check for empty queue */
 	if (q->tail_idx == q->head_idx)
 		return false;
drivers/net/ethernet/pensando/ionic/ionic_txrx.c +4 -0
index 73998d61593a9..c3bcfdd1a1405 100644
@@ -739,6 +739,8 @@ static bool __ionic_rx_service(struct ionic_cq *cq, struct bpf_prog *xdp_prog)
 	if (!color_match(comp->pkt_type_color, cq->done_color))
 		return false;
 
+	dma_rmb();
+
 	/* check for empty queue */
 	if (q->tail_idx == q->head_idx)
 		return false;
@@ -1254,6 +1256,8 @@ static bool ionic_tx_service(struct ionic_cq *cq,
 	if (!color_match(comp->color, cq->done_color))
 		return false;
 
+	dma_rmb();
+
 	/* clean the related q entries, there could be
 	 * several q entries completed for each cq completion
 	 */
Signature · 1 line
2.53.0
author maintainer
#1580 lore raw

PATCH 1564/1815 ionic: fix completion descriptor access with 2x desc size

In reply to Greg Kroah-Hartman

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

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

From: Prabu Thayalan <[email protected]>

[ Upstream commit 5da6ec6f06f235166bd084466b3386c638e26675 ]

The old ionic_rx_service() and ionic_tx_service() used array indexing to access completion descriptors:

    comp = &((struct ionic_rxq_comp *)cq->base)[cq->tail_idx];

This assumes the stride is sizeof(struct ionic_rxq_comp) = 16 bytes. However, when the IONIC_Q_F_2X_CQ_DESC flag is set, the actual completion descriptor size is 32 bytes (2 * sizeof(comp)), and the completion itself is located at the end of that 32-byte slot. Array indexing with a 16-byte stride would access the wrong offset.

Use pointer arithmetic that accounts for the actual descriptor size from cq->desc_size:

    comp = cq->base +
           cq->desc_size * cq->tail_idx +
           cq->desc_size - sizeof(*comp);

This correctly calculates the completion location regardless of descriptor size. For the common case where desc_size equals sizeof(*comp), use array indexing in a likely() fast path to avoid performance regression.

---
 .../net/ethernet/pensando/ionic/ionic_txrx.c  | 27 ++++++++++---------
 1 file changed, 14 insertions(+), 13 deletions(-)
drivers/net/ethernet/pensando/ionic/ionic_txrx.c +14 -13
index c3bcfdd1a1405..e436e3231e864 100644
@@ -706,11 +706,7 @@ static void ionic_rx_clean(struct ionic_queue *q,
 		__le64 *cq_desc_hwstamp;
 		u64 hwstamp;
 
-		cq_desc_hwstamp =
-			(void *)comp +
-			qcq->cq.desc_size -
-			sizeof(struct ionic_rxq_comp) -
-			IONIC_HWSTAMP_CQ_NEGOFFSET;
+		cq_desc_hwstamp = (void *)comp - IONIC_HWSTAMP_CQ_NEGOFFSET;
 
 		hwstamp = le64_to_cpu(*cq_desc_hwstamp);
 
@@ -734,7 +730,12 @@ static bool __ionic_rx_service(struct ionic_cq *cq, struct bpf_prog *xdp_prog)
 	struct ionic_queue *q = cq->bound_q;
 	struct ionic_rxq_comp *comp;
 
-	comp = &((struct ionic_rxq_comp *)cq->base)[cq->tail_idx];
+	if (likely(cq->desc_size == sizeof(*comp)))
+		comp = &((struct ionic_rxq_comp *)cq->base)[cq->tail_idx];
+	else
+		comp = cq->base +
+		       cq->desc_size * cq->tail_idx +
+		       cq->desc_size - sizeof(*comp);
 
 	if (!color_match(comp->pkt_type_color, cq->done_color))
 		return false;
@@ -1187,7 +1188,6 @@ static void ionic_tx_clean(struct ionic_queue *q,
 			   bool in_napi)
 {
 	struct ionic_tx_stats *stats = q_to_tx_stats(q);
-	struct ionic_qcq *qcq = q_to_qcq(q);
 	struct sk_buff *skb;
 
 	if (desc_info->xdpf) {
@@ -1212,11 +1212,7 @@ static void ionic_tx_clean(struct ionic_queue *q,
 			__le64 *cq_desc_hwstamp;
 			u64 hwstamp;
 
-			cq_desc_hwstamp =
-				(void *)comp +
-				qcq->cq.desc_size -
-				sizeof(struct ionic_txq_comp) -
-				IONIC_HWSTAMP_CQ_NEGOFFSET;
+			cq_desc_hwstamp = (void *)comp - IONIC_HWSTAMP_CQ_NEGOFFSET;
 
 			hwstamp = le64_to_cpu(*cq_desc_hwstamp);
 
@@ -1251,7 +1247,12 @@ static bool ionic_tx_service(struct ionic_cq *cq,
 	unsigned int pkts = 0;
 	u16 index;
 
-	comp = &((struct ionic_txq_comp *)cq->base)[cq->tail_idx];
+	if (likely(cq->desc_size == sizeof(*comp)))
+		comp = &((struct ionic_txq_comp *)cq->base)[cq->tail_idx];
+	else
+		comp = cq->base +
+		       cq->desc_size * cq->tail_idx +
+		       cq->desc_size - sizeof(*comp);
 
 	if (!color_match(comp->color, cq->done_color))
 		return false;
Signature · 1 line
2.53.0
author maintainer
#1581 lore raw

PATCH 1565/1815 dpll: fix NULL deref in dpll_device_ops() during teardown race

In reply to Greg Kroah-Hartman

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

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

From: Petr Oros <[email protected]>

[ Upstream commit 33f016b23a219fe034213849b51436b8e79df251 ]

When the last owner of a dpll device unregisters while a foreign driver still holds a pin on it via dpll_pin_on_pin_register(), the dpll object stays alive with an empty registration list. A pin notification queued before the unregister (e.g. ice reacting to zl3073x_i2c removal) then walks pin->dpll_refs into dpll_device_ops(), which trips the WARN_ON and dereferences the missing registration. dpll_lock cannot help because the notification work was queued before the unregistering driver took the lock.

Treat the empty registration list as a legitimate transient state. Make dpll_priv() and dpll_device_ops() return NULL in that case and make every pin netlink path that resolves a device from a pin skip such dplls. dpll_cmd_pin_get_one() picks a ref with a live registration and returns -ENODEV when there is none, the pin dumpit skips such a pin instead of aborting the dump, dpll_msg_add_pin_dplls() and the frequency, esync, reference sync and phase adjust set paths skip dead refs, and dpll_pin_parent_device_set() validates the parent with dpll_device_get_by_id(). dpll_pin_register() is the last caller that dereferenced the device ops without a check, so move its frequency monitor validation under dpll_lock and tolerate a missing registration there as well.

The empty registration list is equivalent to a cleared DPLL_REGISTERED mark, both transitions happen under dpll_lock in dpll_device_register() and dpll_device_unregister(). A pin notification for a pin whose dplls are all gone is now dropped with -ENODEV instead of crashing, all callers in the core ignore that return value.

 WARNING: drivers/dpll/dpll_core.c:1092 at dpll_device_ops+0x24/0x40,
 CPU#83: kworker/u576:3/23471
 Modules linked in: ... ice ... zl3073x_i2c(-) ... zl3073x ...
 Workqueue: ice_dpll_wq ice_dpll_pin_notify_work [ice]
 RIP: 0010:dpll_device_ops+0x24/0x40
 Call Trace:
  <TASK>
  dpll_cmd_pin_get_one+0x336/0x520
  dpll_pin_event_send+0x82/0x140
  dpll_pin_on_pin_unregister+0xbb/0x160
  ice_dpll_pin_notify_work+0x1bc/0x1f0 [ice]
  process_one_work+0x19e/0x370
  worker_thread+0x1a6/0x310
  kthread+0xe4/0x120
  ret_from_fork+0x1a1/0x270
  ret_from_fork_asm+0x1a/0x30
  </TASK>
 ---[ end trace 0000000000000000 ]---
 BUG: kernel NULL pointer dereference, address: 0000000000000010
 #PF: supervisor read access in kernel mode
 #PF: error_code(0x0000) - not-present page
---
 drivers/dpll/dpll_core.c    | 24 +++++++++------
 drivers/dpll/dpll_netlink.c | 59 ++++++++++++++++++++++++++++++++-----
 2 files changed, 67 insertions(+), 16 deletions(-)
drivers/dpll/dpll_core.c +15 -9
index 43d51d942eadd..a320eeb829ad2 100644
@@ -876,19 +876,25 @@ int
 dpll_pin_register(struct dpll_device *dpll, struct dpll_pin *pin,
 		  const struct dpll_pin_ops *ops, void *priv)
 {
+	const struct dpll_device_ops *dev_ops;
 	int ret;
 
 	if (WARN_ON(!ops) ||
 	    WARN_ON(!ops->state_on_dpll_get) ||
 	    WARN_ON(!ops->direction_get) ||
-	    WARN_ON(ops->measured_freq_get &&
-		    (!dpll_device_ops(dpll)->freq_monitor_get ||
-		     !dpll_device_ops(dpll)->freq_monitor_set)) ||
 	    WARN_ON(ops->supported_ffo && !ops->ffo_get))
 		return -EINVAL;
 
 	mutex_lock(&dpll_lock);
 
+	dev_ops = dpll_device_ops(dpll);
+	if (WARN_ON(ops->measured_freq_get &&
+		    (!dev_ops || !dev_ops->freq_monitor_get ||
+		     !dev_ops->freq_monitor_set))) {
+		ret = -EINVAL;
+		goto out_unlock;
+	}
+
 	/*
 	 * For pins identified via firmware (pin->fwnode), allow registration
 	 * even if the pin's (module, clock_id) differs from the target DPLL.
@@ -1081,12 +1087,8 @@ EXPORT_SYMBOL_GPL(dpll_pin_ref_sync_pair_add);
 static struct dpll_device_registration *
 dpll_device_registration_first(struct dpll_device *dpll)
 {
-	struct dpll_device_registration *reg;
-
-	reg = list_first_entry_or_null((struct list_head *)&dpll->registration_list,
-				       struct dpll_device_registration, list);
-	WARN_ON(!reg);
-	return reg;
+	return list_first_entry_or_null((struct list_head *)&dpll->registration_list,
+					struct dpll_device_registration, list);
 }
 
 void *dpll_priv(struct dpll_device *dpll)
@@ -1094,6 +1096,8 @@ void *dpll_priv(struct dpll_device *dpll)
 	struct dpll_device_registration *reg;
 
 	reg = dpll_device_registration_first(dpll);
+	if (!reg)
+		return NULL;
 	return reg->priv;
 }
 
@@ -1102,6 +1106,8 @@ const struct dpll_device_ops *dpll_device_ops(struct dpll_device *dpll)
 	struct dpll_device_registration *reg;
 
 	reg = dpll_device_registration_first(dpll);
+	if (!reg)
+		return NULL;
 	return reg->ops;
 }
 
drivers/dpll/dpll_netlink.c +52 -7

180 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#1582 lore raw

PATCH 1566/1815 net: kcm: Hold RCU read lock while running BPF parser

In reply to Greg Kroah-Hartman

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

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

From: Junseo Lim <[email protected]>

[ Upstream commit b0346dd64e4905291cc9c479f2e6cf1884ced4e6 ]

kcm_parse_func_strparser() calls bpf_prog_run_pin_on_cpu() which prevents CPU migration, but does not establish an RCU read-side critical section. Consequently, BPF map operations can trigger WARN_ON_ONCE(!bpf_rcu_lock_held()) when called from the KCM strparser program.

Hold the RCU read lock while running the program.

---
 net/kcm/kcmsock.c | 3 +++
 1 file changed, 3 insertions(+)
net/kcm/kcmsock.c +3 -0
index d469abcd989b4..71af69d442f21 100644
@@ -5,6 +5,7 @@
  * Copyright (c) 2016 Tom Herbert <[email protected]>
  */
 
+#include <linux/rcupdate.h>
 #include <linux/bpf.h>
 #include <linux/errno.h>
 #include <linux/errqueue.h>
@@ -391,7 +392,9 @@ static int kcm_parse_func_strparser(struct strparser *strp, struct sk_buff *skb)
 	struct bpf_prog *prog = psock->bpf_prog;
 	int res;
 
+	rcu_read_lock();
 	res = bpf_prog_run_pin_on_cpu(prog, skb);
+	rcu_read_unlock();
 	return res;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1583 lore raw

PATCH 1567/1815 net: dsa: b53: fix error propagation from b53_fdb_dump()

In reply to Greg Kroah-Hartman

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

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

From: Vladimir Oltean <[email protected]>

[ Upstream commit 4f1d06cf8aaa9d2cb18e5ee8835aff6177256bc6 ]

The blamed commit replaced "return ret" statements in b53_fdb_dump() with "break;" which jumps to the mutex_unlock() -> return 0 section.

This is notably problematic because it swallows errors from the b53_fdb_copy() -> cb() path, and this will result in FDB dump truncation when the netlink skb overflows - see commit 21b52fed928e ("net: dsa:
sja1105: fix broken backpressure in .port_fdb_dump").

Let's go back to "return ret". We don't need to preinitialize "ret" with 0, because the "do {} while" block guarantees we cannot reach the end of the function without at least once calling b53_arl_search_wait(), which will have initialized ret to some valid value.

Fixes f7eb4a1c0864 ("net: dsa: b53: serialize access to the ARL table")
---
 drivers/net/dsa/b53/b53_common.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/dsa/b53/b53_common.c +1 -1
index 3f5b9592794da..0880310c9ce3f 100644
@@ -2219,7 +2219,7 @@ int b53_fdb_dump(struct dsa_switch *ds, int port,
 
 	mutex_unlock(&priv->arl_mutex);
 
-	return 0;
+	return ret;
 }
 EXPORT_SYMBOL(b53_fdb_dump);
 
Signature · 1 line
2.53.0
author maintainer
#1584 lore raw

PATCH 1568/1815 pppox: drain queued packets on channel handoff

In reply to Greg Kroah-Hartman

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

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

From: Qingfang Deng <[email protected]>

[ Upstream commit 92c1bf630abf0af646562398eaa36f80b5ff677d ]

PPPIOCGCHAN both returns the channel index and marks a PPPOX socket as bound to generic PPP, despite its getter semantic. Packets received before that transition are queued on sk_receive_queue, but a bound socket is no longer readable. Such packets therefore remain queued until the socket is destroyed.

After marking a socket bound, wait for receive paths that observed the old state to finish queueing packets, and then drain the queue into generic PPP.

---
 drivers/net/ppp/pppox.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
drivers/net/ppp/pppox.c +17 -0
index 5861a2f6ce3e6..a6f72c813bef9 100644
@@ -74,7 +74,9 @@ int pppox_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
 
 	switch (cmd) {
 	case PPPIOCGCHAN: {
+		struct sk_buff *skb;
 		int index;
+
 		rc = -ENOTCONN;
 		if (!(sk->sk_state & PPPOX_CONNECTED))
 			break;
@@ -85,7 +87,22 @@ int pppox_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
 			break;
 
 		rc = 0;
+		/* PPPIOCGCHAN historically marks the userspace handoff to
+		 * generic PPP; pppd then attaches the returned channel to
+		 * /dev/ppp.
+		 */
 		sk->sk_state |= PPPOX_BOUND;
+		/* Let lockless receive paths finish queueing against the old
+		 * state.
+		 */
+		synchronize_net();
+		/* Drain packets queued before the handoff because a bound
+		 * socket is no longer readable.
+		 */
+		while ((skb = skb_dequeue(&sk->sk_receive_queue))) {
+			skb_orphan(skb);
+			ppp_input(&po->chan, skb);
+		}
 		break;
 	}
 	default:
Signature · 1 line
2.53.0
author maintainer
#1585 lore raw

PATCH 1569/1815 net: hsr: free learned nodes on device setup failure

In reply to Greg Kroah-Hartman

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

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

From: Xin Xie <[email protected]>

[ Upstream commit 7f16289b91eb316f170a6bd22d32e6c632f6a5b6 ]

hsr_dev_finalize() can fail after a lower-device RX handler has already been registered (slave A is added before the failable slave B and interlink adds). RX handlers run in softirq regardless of the master's state, so frames received in that window can learn dynamic nodes into node_db, and the error unwind never releases them.

Free both owned dynamic databases in the unwind, mirroring hsr_dellink(). proxy_node_db is provably empty on every current error exit (only interlink RX feeds it, and the interlink add is the last failable step) and is freed for symmetry. The order is safe:
hsr_del_port() unregisters each RX handler with synchronize_net() before hsr_del_nodes() runs, which removes remaining entries with list_del_rcu() and defers their release with call_rcu() for readers already under RCU.

Fixes 81ba6afd6e64 ("net/hsr: Switch from dev_add_pack() to netdev_rx_handler_register()")
---
 net/hsr/hsr_device.c | 2 ++
 1 file changed, 2 insertions(+)
net/hsr/hsr_device.c +2 -0
index 5555b71ab19b5..9c3078dd38c2c 100644
@@ -820,6 +820,8 @@ int hsr_dev_finalize(struct net_device *hsr_dev, struct net_device *slave[2],
 	hsr_del_ports(hsr);
 err_add_master:
 	hsr_del_self_node(hsr);
+	hsr_del_nodes(&hsr->node_db);
+	hsr_del_nodes(&hsr->proxy_node_db);
 
 	if (unregister)
 		unregister_netdevice(hsr_dev);
Signature · 1 line
2.53.0
author maintainer
#1586 lore raw

PATCH 1570/1815 virtio_net: Fix resize of the RX ring

In reply to Greg Kroah-Hartman

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

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

From: Anton Protopopov <[email protected]>

[ Upstream commit d09c98a6da215bce2173a292e4b95c8de6ea5d51 ]

When a AF_XDP socket is attached, the virtnet_rx_resize should resize the rq->xsk_buffs XSK buffer array. Otherwise, when the size grows, the virtnet_rx_resume() causes a write past the end of the array. This is easily reproducable with

ethtool -G ens3 rx 32
./xdpsock -i eth0 -q 0 -r -z &
ethtool -G eth0 rx 256

Fixes e9f3962441c0 ("virtio_net: xsk: rx: support fill with xsk buffer")
---
 drivers/net/virtio_net.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
drivers/net/virtio_net.c +14 -0
index 3e2a5876c6c8c..e34c52d059d39 100644
@@ -3444,17 +3444,31 @@ static void virtnet_rx_resume_all(struct virtnet_info *vi)
 static int virtnet_rx_resize(struct virtnet_info *vi,
 			     struct receive_queue *rq, u32 ring_num)
 {
+	unsigned int old_ring_num = virtqueue_get_vring_size(rq->vq);
+	struct xdp_buff **tmp_xsk_buffs = NULL;
 	int err, qindex;
 
 	qindex = rq - vi->rq;
 
+	if (rq->xsk_pool && ring_num > old_ring_num) {
+		tmp_xsk_buffs = kvzalloc_objs(*tmp_xsk_buffs, ring_num);
+		if (!tmp_xsk_buffs)
+			return -ENOMEM;
+	}
+
 	virtnet_rx_pause(vi, rq);
 
 	err = virtqueue_resize(rq->vq, ring_num, virtnet_rq_unmap_free_buf, NULL);
+
+	/* virtqueue_resize may have changed the size even if err != 0 */
+	if (tmp_xsk_buffs && virtqueue_get_vring_size(rq->vq) > old_ring_num)
+		swap(rq->xsk_buffs, tmp_xsk_buffs);
+
 	if (err)
 		netdev_err(vi->dev, "resize rx fail: rx queue index: %d err: %d\n", qindex, err);
 
 	virtnet_rx_resume(vi, rq, true);
+	kvfree(tmp_xsk_buffs);
 	return err;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1587 lore raw

PATCH 1571/1815 f2fs: cleanup w/ f2fs_need_rand_{blk, seg, seg_blk}

In reply to Greg Kroah-Hartman

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

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

From: Chao Yu <[email protected]>

[ Upstream commit 6da62bbde487d4678702ef004a911cd1c7a5c746 ]

No logic changes.

Stable-dep-of: 0a1703eba237 ("f2fs: fix to avoid pinfile fragment on fragment:{block, segment} mode")

---
 fs/f2fs/f2fs.h    | 13 +++++++++++--
 fs/f2fs/gc.c      |  2 +-
 fs/f2fs/segment.c |  8 ++++----
 fs/f2fs/super.c   |  4 ++--
 4 files changed, 18 insertions(+), 9 deletions(-)
fs/f2fs/f2fs.h +11 -2
index 8011bbdf2c688..e3ff6979bae0b 100644
@@ -4123,10 +4123,19 @@ static inline struct inode *fio_inode(struct f2fs_io_info *fio)
 #define MIN_FRAGMENT_SIZE	1
 #define MAX_FRAGMENT_SIZE	512
 
+static inline bool f2fs_need_rand_blk(struct f2fs_sb_info *sbi)
+{
+	return F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK;
+}
+
 static inline bool f2fs_need_rand_seg(struct f2fs_sb_info *sbi)
 {
-	return F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_SEG ||
-		F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK;
+	return F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_SEG;
+}
+
+static inline bool f2fs_need_rand_seg_blk(struct f2fs_sb_info *sbi)
+{
+	return f2fs_need_rand_blk(sbi) || f2fs_need_rand_seg(sbi);
 }
 
 /*
fs/f2fs/gc.c +1 -1
index 1eda818619747..e243b25f683d3 100644
@@ -310,7 +310,7 @@ static void select_policy(struct f2fs_sb_info *sbi, int gc_type,
 		p->max_search = sbi->max_victim_search;
 
 	/* let's select beginning hot/small space first. */
-	if (f2fs_need_rand_seg(sbi)) {
+	if (f2fs_need_rand_seg_blk(sbi)) {
 		p->offset = get_random_u32_below(MAIN_SECS(sbi) *
 						SEGS_PER_SEC(sbi));
 		SIT_I(sbi)->last_victim[p->gc_mode] = p->offset;
fs/f2fs/segment.c +4 -4
index 091bfb170d615..a124deba1dcc9 100644
@@ -2936,7 +2936,7 @@ static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type)
 
 	sanity_check_seg_type(sbi, seg_type);
 	if (__is_large_section(sbi)) {
-		if (f2fs_need_rand_seg(sbi)) {
+		if (f2fs_need_rand_seg_blk(sbi)) {
 			unsigned int hint = GET_SEC_FROM_SEG(sbi, curseg->segno);
 
 			if (GET_SEC_FROM_SEG(sbi, curseg->segno + 1) != hint)
@@ -2945,7 +2945,7 @@ static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type)
 					GET_SEG_FROM_SEC(sbi, hint + 1) - 1);
 		}
 		return curseg->segno;
-	} else if (f2fs_need_rand_seg(sbi)) {
+	} else if (f2fs_need_rand_seg_blk(sbi)) {
 		return get_random_u32_below(MAIN_SECS(sbi) * SEGS_PER_SEC(sbi));
 	}
 
@@ -3001,7 +3001,7 @@ static int new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
 	curseg->next_segno = segno;
 	reset_curseg(sbi, type, 1);
 	curseg->alloc_type = LFS;
-	if (F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK)
+	if (f2fs_need_rand_blk(sbi))
 		curseg->fragment_remained_chunk =
 				get_random_u32_inclusive(1, sbi->max_fragment_chunk);
 	return 0;
@@ -3822,7 +3822,7 @@ int f2fs_allocate_data_block(struct f2fs_sb_info *sbi, struct folio *folio,
 		curseg->next_blkoff = f2fs_find_next_ssr_block(sbi, curseg);
 	} else {
 		curseg->next_blkoff++;
-		if (F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK)
+		if (f2fs_need_rand_blk(sbi))
 			f2fs_randomize_chunk(sbi, curseg);
 	}
 	if (curseg->next_blkoff >= f2fs_usable_blks_in_seg(sbi, curseg->segno))
fs/f2fs/super.c +2 -2
index f7e2dcb58b4db..f47cd71a85278 100644
@@ -2456,9 +2456,9 @@ static int f2fs_show_options(struct seq_file *seq, struct dentry *root)
 		seq_puts(seq, "adaptive");
 	else if (F2FS_OPTION(sbi).fs_mode == FS_MODE_LFS)
 		seq_puts(seq, "lfs");
-	else if (F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_SEG)
+	else if (f2fs_need_rand_seg(sbi))
 		seq_puts(seq, "fragment:segment");
-	else if (F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK)
+	else if (f2fs_need_rand_blk(sbi))
 		seq_puts(seq, "fragment:block");
 	seq_printf(seq, ",active_logs=%u", F2FS_OPTION(sbi).active_logs);
 	if (test_opt(sbi, RESERVE_ROOT) || test_opt(sbi, RESERVE_NODE))
Signature · 1 line
2.53.0
author maintainer
#1588 lore raw

PATCH 1572/1815 f2fs: fix to avoid pinfile fragment on fragment:{block, segment} mode

In reply to Greg Kroah-Hartman

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

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

From: Chao Yu <[email protected]>

[ Upstream commit 0a1703eba23707e3b2edfa2a2329352e7abc0ffa ]

pinfile fallocate() conflicts w/ mode=fragment:{block,segment} mount option, result in fragment blocks in pinfile, it violate semantics of pinfile introduced in commit f5a53edcf01e ("f2fs: support aligned pinned file").

mkfs.f2fs -f /dev/vdb
mount -t f2fs -o mode=fragment:block /dev/vdb /mnt/f2fs/ dd if=/dev/zero of=/mnt/f2fs/file bs=1M count=3900 sync
touch /mnt/f2fs/pinfile
f2fs_io pinfile set /mnt/f2fs/pinfile
f2fs_io fallocate 0 0 $((1024*1024*16)) /mnt/f2fs/pinfile sync
f2fs_io fiemap 0 $((1024*1024*16)) /mnt/f2fs/pinfile

[Before]
fallocate failed: No space left on device
Fiemap: offset = 0 len = 16777216
logical addr. physical addr. length flags

0       0000000000000000 00000000d7200000 0000000000004000 00001000
1       0000000000004000 00000000d7207000 0000000000001000 00001000
2       0000000000005000 00000000d720c000 0000000000002000 00001000
3       0000000000007000 00000000d7211000 0000000000001000 00001000
4       0000000000008000 00000000d7214000 0000000000001000 00001000
5       0000000000009000 00000000d7218000 0000000000001000 00001000
6       000000000000a000 00000000d721d000 0000000000001000 00001000
7       000000000000b000 00000000d721f000 0000000000004000 00001000
...
96      00000000000f1000 00000000d73e9000 0000000000004000 00001000
97      00000000000f5000 00000000d73f1000 0000000000003000 00001000
98      00000000000f8000 00000000d73f5000 0000000000004000 00001000
99      00000000000fc000 00000000d73fa000 0000000000001000 00001000
100     00000000000fd000 00000000d73ff000 0000000000001000 00001001

[After]
fallocated a file: i_size=16777216, i_blocks=32808
Fiemap: offset = 0 len = 16777216
logical addr. physical addr. length flags

0       0000000000000000 0000000018a00000 0000000000400000 00001000
1       0000000000400000 0000000019000000 0000000000400000 00001000
2       0000000000800000 0000000032400000 0000000000200000 00001000
3       0000000000a00000 0000000038000000 0000000000200000 00001000
4       0000000000c00000 0000000039c00000 0000000000200000 00001000
5       0000000000e00000 0000000044c00000 0000000000200000 00001001

Let's ignore mode=fragment:{block,segment} mount option while fallocate() on pinfile.

Fixes 6691d940b0e0 ("f2fs: introduce fragment allocation mode mount option")
---
 fs/f2fs/f2fs.h    | 15 +++++++++++----
 fs/f2fs/gc.c      |  2 +-
 fs/f2fs/segment.c |  8 ++++----
 fs/f2fs/super.c   |  4 ++--
 4 files changed, 18 insertions(+), 11 deletions(-)
fs/f2fs/f2fs.h +11 -4
index e3ff6979bae0b..bc2246abd421b 100644
@@ -4123,19 +4123,26 @@ static inline struct inode *fio_inode(struct f2fs_io_info *fio)
 #define MIN_FRAGMENT_SIZE	1
 #define MAX_FRAGMENT_SIZE	512
 
-static inline bool f2fs_need_rand_blk(struct f2fs_sb_info *sbi)
+static inline bool f2fs_need_rand_blk(struct f2fs_sb_info *sbi,
+					enum log_type type)
 {
+	if (type == CURSEG_COLD_DATA_PINNED)
+		return false;
 	return F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK;
 }
 
-static inline bool f2fs_need_rand_seg(struct f2fs_sb_info *sbi)
+static inline bool f2fs_need_rand_seg(struct f2fs_sb_info *sbi,
+					enum log_type type)
 {
+	if (type == CURSEG_COLD_DATA_PINNED)
+		return false;
 	return F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_SEG;
 }
 
-static inline bool f2fs_need_rand_seg_blk(struct f2fs_sb_info *sbi)
+static inline bool f2fs_need_rand_seg_blk(struct f2fs_sb_info *sbi,
+					enum log_type type)
 {
-	return f2fs_need_rand_blk(sbi) || f2fs_need_rand_seg(sbi);
+	return f2fs_need_rand_blk(sbi, type) || f2fs_need_rand_seg(sbi, type);
 }
 
 /*
fs/f2fs/gc.c +1 -1
index e243b25f683d3..c771adedff39c 100644
@@ -310,7 +310,7 @@ static void select_policy(struct f2fs_sb_info *sbi, int gc_type,
 		p->max_search = sbi->max_victim_search;
 
 	/* let's select beginning hot/small space first. */
-	if (f2fs_need_rand_seg_blk(sbi)) {
+	if (f2fs_need_rand_seg_blk(sbi, type)) {
 		p->offset = get_random_u32_below(MAIN_SECS(sbi) *
 						SEGS_PER_SEC(sbi));
 		SIT_I(sbi)->last_victim[p->gc_mode] = p->offset;
fs/f2fs/segment.c +4 -4
index a124deba1dcc9..8830e1892b435 100644
@@ -2936,7 +2936,7 @@ static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type)
 
 	sanity_check_seg_type(sbi, seg_type);
 	if (__is_large_section(sbi)) {
-		if (f2fs_need_rand_seg_blk(sbi)) {
+		if (f2fs_need_rand_seg_blk(sbi, type)) {
 			unsigned int hint = GET_SEC_FROM_SEG(sbi, curseg->segno);
 
 			if (GET_SEC_FROM_SEG(sbi, curseg->segno + 1) != hint)
@@ -2945,7 +2945,7 @@ static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type)
 					GET_SEG_FROM_SEC(sbi, hint + 1) - 1);
 		}
 		return curseg->segno;
-	} else if (f2fs_need_rand_seg_blk(sbi)) {
+	} else if (f2fs_need_rand_seg_blk(sbi, type)) {
 		return get_random_u32_below(MAIN_SECS(sbi) * SEGS_PER_SEC(sbi));
 	}
 
@@ -3001,7 +3001,7 @@ static int new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
 	curseg->next_segno = segno;
 	reset_curseg(sbi, type, 1);
 	curseg->alloc_type = LFS;
-	if (f2fs_need_rand_blk(sbi))
+	if (f2fs_need_rand_blk(sbi, type))
 		curseg->fragment_remained_chunk =
 				get_random_u32_inclusive(1, sbi->max_fragment_chunk);
 	return 0;
@@ -3822,7 +3822,7 @@ int f2fs_allocate_data_block(struct f2fs_sb_info *sbi, struct folio *folio,
 		curseg->next_blkoff = f2fs_find_next_ssr_block(sbi, curseg);
 	} else {
 		curseg->next_blkoff++;
-		if (f2fs_need_rand_blk(sbi))
+		if (f2fs_need_rand_blk(sbi, type))
 			f2fs_randomize_chunk(sbi, curseg);
 	}
 	if (curseg->next_blkoff >= f2fs_usable_blks_in_seg(sbi, curseg->segno))
fs/f2fs/super.c +2 -2
index f47cd71a85278..7f6c4e9d3735a 100644
@@ -2456,9 +2456,9 @@ static int f2fs_show_options(struct seq_file *seq, struct dentry *root)
 		seq_puts(seq, "adaptive");
 	else if (F2FS_OPTION(sbi).fs_mode == FS_MODE_LFS)
 		seq_puts(seq, "lfs");
-	else if (f2fs_need_rand_seg(sbi))
+	else if (f2fs_need_rand_seg(sbi, NO_CHECK_TYPE))
 		seq_puts(seq, "fragment:segment");
-	else if (f2fs_need_rand_blk(sbi))
+	else if (f2fs_need_rand_blk(sbi, NO_CHECK_TYPE))
 		seq_puts(seq, "fragment:block");
 	seq_printf(seq, ",active_logs=%u", F2FS_OPTION(sbi).active_logs);
 	if (test_opt(sbi, RESERVE_ROOT) || test_opt(sbi, RESERVE_NODE))
Signature · 1 line
2.53.0
author maintainer
#1589 lore raw

PATCH 1573/1815 netfilter: ipset: remove need to allocate memory on delete operations

In reply to Greg Kroah-Hartman

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

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

From: Florian Westphal <[email protected]>

[ Upstream commit e80456d79ec83b00a6bd44c377684b1632ccc3c7 ]

Allocating mem via GFP_ATOMIC on delete is problematic, delete operations should always succeed.

Do in-place substitution: When /cidr reaches 0 count (no more elements in the range), move ranges stored later in the array forward and keep the count 0 ones at the end.

INIT_CIDR() can then check count == 0 without a need to search next element in the array.

To avoid problems on weakly ordered architectures, pack the structure so it is only 32bit wide, then use READ/WRITE_ONCE to store both cidr and count. atomically.

Also update comments to mention the possible presence of ignored 0-count-0-cidr structures at the end and need for seqcount.

seqcount is used to restart. This avoids bogus range misses.
Given: [0]: /29 [1]: /24
cpu1 reads slot 0. then, right after, cpu2 removes /29. count drops to 0, so it updates array to: [0], /24, [1], /0 (count 0).

cpu1 then skips /28: slot 0 was already visited, but slot 1 already replaced.

Note that mtype_add() doesn't check mtype_add_cidr() return value. Doing this here is useless noise as this code is extensively rewritten in the rhashtable replacement patch.

Assisted-by Claude:claude-sonnet-5
Fixes 8e5fd2a55e24 ("netfilter: ipset: rework cidr bookkeeping")
---
 net/netfilter/ipset/ip_set_hash_gen.h        | 168 +++++++++++++------
 net/netfilter/ipset/ip_set_hash_netiface.c   |   1 -
 net/netfilter/ipset/ip_set_hash_netportnet.c |   1 -
 3 files changed, 121 insertions(+), 49 deletions(-)
net/netfilter/ipset/ip_set_hash_gen.h +121 -47
index f00c82acd7f05..80ca523f304bb 100644
@@ -8,6 +8,7 @@
 #include <linux/rcupdate_wait.h>
 #include <linux/jhash.h>
 #include <linux/types.h>
+#include <linux/seqlock.h>
 #include <linux/netfilter/nfnetlink.h>
 #include <linux/netfilter/ipset/ip_set.h>
 
@@ -98,14 +99,34 @@ struct htable {
 #define IPSET_NET_COUNT		1
 #endif
 
-/* Book-keeping of the prefixes added to the set */
+/**
+ * struct net_prefix - Representation of a network prefix.
+ * @cidr: The CIDR prefix length.
+ * @count: Number of occurrences.
+ */
 struct net_prefix {
-	u8 cidr;			/* the cidr value */
-	u32 count;			/* number of elements of this cidr */
+	u32 cidr:8;
+	u32 count:24;
 };
 
+#define CIDR_MAX_COUNT ((1 << 24) - 1)
+
+/**
+ * struct net_prefixes - A collection of network prefixes.
+ * @rcu: RCU head
+ * @seq: Sequence counter guarding in-place reordering of @nets
+ * @len: Number of entries in the array.
+ * @nets: Array of net_prefix structures (sorted by CIDR descending).
+ *
+ * @nets entries are updated in place under @set's lock. A single entry's
+ * cidr/count pair is always updated atomically via READ_ONCE()/WRITE_ONCE(),
+ * but removing an entry also shifts every following entry down by one slot.
+ * Lockless readers that scan the whole array (i.e. more than a single
+ * indexed slot) must use @seq to detect and retry across such a shift.
+ */
 struct net_prefixes {
 	struct rcu_head rcu;
+	seqcount_spinlock_t seq;
 	u8 len;
 	struct net_prefix nets[] __counted_by(len);
 };
@@ -143,8 +164,11 @@ htable_size(u8 hbits)
 #endif
 
 #define INIT_CIDR(n, host_mask) ({				\
-	const struct net_prefixes *__n = rcu_dereference(n);		\
-	DCIDR_PUT((__n)->len ? (__n)->nets[0].cidr : host_mask);\
+	const struct net_prefixes *__n = rcu_dereference(n);	\
+	struct net_prefix __p =					\
+		__n->len ? READ_ONCE(__n->nets[0])		\
+			 : (struct net_prefix){};		\
+	DCIDR_PUT(__p.count ? __p.cidr : host_mask);		\
 })
 
 #endif /* IP_SET_HASH_WITH_NETS */
@@ -318,27 +342,43 @@ struct mtype_resize_ad {
 };
 
 #ifdef IP_SET_HASH_WITH_NETS
-/* Network cidr size book keeping when the hash stores different
- * sized networks. cidr == real cidr + 1 to support /0.
+/**
+ * mtype_add_cidr - Add a CIDR entry to hash table bookkeeping
+ * @set: Pointer to the ip_set
+ * @h: Pointer to the htype
+ * @cidr: The CIDR prefix length
+ * @n: The index of the net_prefix array to add @cidr to
+ *
+ * Performs an update if @cidr is found, otherwise performs COW-style
+ * allocation and replacement via RCU.
+ *
+ * Return: 0 on success, negative error code on failure.
  */
 static int
 mtype_add_cidr(struct ip_set *set, struct htype *h, u8 cidr, u8 n)
 {
-	struct net_prefixes *nets, *tmp;
 	int i, j, found, len = 0, ret = 0;
+	struct net_prefixes *nets, *tmp;
+	struct net_prefix np;
 
 	spin_lock_bh(&set->lock);
 	nets = __ipset_dereference(h->rnets[n]);
 	/* Add in increasing prefix order, so larger cidr first */
 	for (i = 0, found = -1; i < nets->len; i++) {
-		if (nets->nets[i].count)
+		np = READ_ONCE(nets->nets[i]);
+		if (np.count)
 			len++;
 		if (found != -1) {
 			continue;
-		} else if (nets->nets[i].cidr < cidr) {
+		} else if (np.cidr < cidr) {
 			found = i;
-		} else if (nets->nets[i].cidr == cidr) {
-			nets->nets[i].count++;
+		} else if (np.cidr == cidr) {
+			if (np.count < CIDR_MAX_COUNT) {
+				np.count++;
+				WRITE_ONCE(nets->nets[i], np);
+			} else {
+				ret = -EOVERFLOW;
+			}
 			goto unlock;
 		}
 	}
@@ -350,6 +390,7 @@ mtype_add_cidr(struct ip_set *set, struct htype *h, u8 cidr, u8 n)
 	}
 
 	tmp->len = len;
+	seqcount_spinlock_init(&tmp->seq, &set->lock);
 	for (i = 0, j = 0; i < nets->len; i++) {
 		if (i == found) {
 			tmp->nets[j].cidr = cidr;
@@ -371,42 +412,60 @@ mtype_add_cidr(struct ip_set *set, struct htype *h, u8 cidr, u8 n)
 	return ret;
 }
 
+/**
+ * mtype_del_cidr - Remove CIDR entry and maintain array integrity.
+ * @set: Pointer to the ip_set.
+ * @h: Pointer to the htype.
+ * @cidr: The CIDR prefix length.
+ * @n: The index of the net_prefix array to remove @cidr from
+ *
+ * If CIDR entry count falls to 0, this function performs a "shift-left"
+ * operation on all following elements. This ensures that the array remains
+ * contiguous and maintains its descending order by CIDR. The vacated slot
+ * at the end of the array is zeroed out (cidr=0, count=0).
+ */
 static void
 mtype_del_cidr(struct ip_set *set, struct htype *h, u8 cidr, u8 n)
 {
-	struct net_prefixes *nets, *tmp;
-	u8 i, j, len = 0;
+	struct net_prefixes *nets;
+	struct net_prefix np;
 	int found;
+	u8 i, j;
+
+	BUILD_BUG_ON(sizeof(struct net_prefix) != sizeof(u32));
 
 	spin_lock_bh(&set->lock);
 	nets = __ipset_dereference(h->rnets[n]);
 	for (i = 0, found = -1; i < nets->len; i++) {
-		if (nets->nets[i].count)
-			len++;
-		if (nets->nets[i].cidr == cidr)
+		np = READ_ONCE(nets->nets[i]);
+		if (np.count && np.cidr == cidr) {
+			np.count--;
 			found = i;
+			break;
+		}
 	}
 	if (unlikely(found == -1))
 		goto unlock;
 
-	nets->nets[found].count--;
-	if (nets->nets[found].count)
-		goto unlock;
-	len--;
-	tmp = kzalloc_flex(*tmp, nets, len, GFP_ATOMIC);
-	if (!tmp)
-		/* Leave a hole */
+	if (np.count) {
+		WRITE_ONCE(nets->nets[found], np);
 		goto unlock;
+	}
 
-	tmp->len = len;
+	write_seqcount_begin(&nets->seq);
 	for (i = 0, j = 0; i < nets->len; i++) {
-		if (!nets->nets[i].count || i == found)
+		if (i == found)
 			continue;
-		tmp->nets[j].cidr = nets->nets[i].cidr;
-		tmp->nets[j++].count = nets->nets[i].count;
+
+		np = READ_ONCE(nets->nets[i]);
+		if (i != j)
+			WRITE_ONCE(nets->nets[j], np);
+		j++;
 	}
-	rcu_assign_pointer(h->rnets[n], tmp);
-	kfree_rcu(nets, rcu);
+
+	while (j < nets->len)
+		WRITE_ONCE(nets->nets[j++], (struct net_prefix){});
+	write_seqcount_end(&nets->seq);
 unlock:
 	spin_unlock_bh(&set->lock);
 }
@@ -451,7 +510,7 @@ mtype_flush(struct ip_set *set)
 {
 	struct htype *h = set->data;
 #ifdef IP_SET_HASH_WITH_NETS
-	struct net_prefixes *nets, *tmp;
+	struct net_prefixes *nets;
 #endif
 	struct htable *t;
 	struct hbucket *n;
@@ -477,17 +536,15 @@ mtype_flush(struct ip_set *set)
 	}
 #ifdef IP_SET_HASH_WITH_NETS
 	for (i = 0; i < IPSET_NET_COUNT; i++) {
-		nets = ipset_dereference_nfnl(h->rnets[i]);
-		tmp = kzalloc_obj(*tmp, GFP_ATOMIC);
-		if (!tmp) {
-			u8 j;
+		u8 j;
 
-			for (j = 0; j < nets->len; j++)
-				nets->nets[j].count = 0;
-		} else {
-			rcu_assign_pointer(h->rnets[i], tmp);
-			kfree_rcu(nets, rcu);
-		}
+		spin_lock_bh(&set->lock);
+		nets = ipset_dereference_nfnl(h->rnets[i]);
+		write_seqcount_begin(&nets->seq);
+		for (j = 0; j < nets->len; j++)
+			WRITE_ONCE(nets->nets[j], (struct net_prefix){});
+		write_seqcount_end(&nets->seq);
+		spin_unlock_bh(&set->lock);
 	}
 #endif
 }
@@ -1253,31 +1310,41 @@ mtype_test_cidrs(struct ip_set *set, struct mtype_elem *d,
 #if IPSET_NET_COUNT == 2
 	struct net_prefixes *nets1;
 	struct mtype_elem orig = *d;
+	unsigned int seq1;
 	int ret, i, j, k;
 #else
 	int ret, i, j;
 #endif
-	u32 key, multi = 0;
+	unsigned int seq0;
+	u32 key, multi;
 	u8 pos;
 
 	pr_debug("test by nets\n");
 	rcu_read_lock_bh();
+retry:
+	multi = 0;
 	nets0 = rcu_dereference_bh(h->rnets[0]);
+	seq0 = read_seqcount_begin(&nets0->seq);
 #if IPSET_NET_COUNT == 2
 	nets1 = rcu_dereference_bh(h->rnets[1]);
+	seq1 = read_seqcount_begin(&nets1->seq);
 #endif
 	for (j = 0; j < nets0->len && !multi; j++) {
-		if (!nets0->nets[j].count)
+		struct net_prefix p0 = READ_ONCE(nets0->nets[j]);
+
+		if (!p0.count)
 			continue;
 #if IPSET_NET_COUNT == 2
 		mtype_data_reset_elem(d, &orig);
-		mtype_data_netmask(d, nets0->nets[j].cidr, false);
+		mtype_data_netmask(d, p0.cidr, false);
 		for (k = 0; k < nets1->len && !multi; k++) {
-			if (!nets1->nets[k].count)
+			struct net_prefix p1 = READ_ONCE(nets1->nets[k]);
+
+			if (!p1.count)
 				continue;
-			mtype_data_netmask(d, nets1->nets[k].cidr, true);
+			mtype_data_netmask(d, p1.cidr, true);
 #else
-		mtype_data_netmask(d, nets0->nets[j].cidr);
+		mtype_data_netmask(d, p0.cidr);
 #endif
 		key = HKEY(d, h->initval, t->htable_bits);
 		n = rcu_dereference_bh(hbucket(t, key));
@@ -1304,6 +1371,12 @@ mtype_test_cidrs(struct ip_set *set, struct mtype_elem *d,
 	}
 	ret = 0;
 unlock:
+	if (read_seqcount_retry(&nets0->seq, seq0))
+		goto retry;
+#if IPSET_NET_COUNT == 2
+	if (read_seqcount_retry(&nets1->seq, seq1))
+		goto retry;
+#endif
 	rcu_read_unlock_bh();
 	return ret;
 }
@@ -1707,6 +1780,7 @@ IPSET_TOKEN(HTYPE, _create)(struct net *net, struct ip_set *set,
 				kfree(rcu_dereference_raw(h->rnets[--i]));
 			goto free_hregion;
 		}
+		seqcount_spinlock_init(&nets->seq, &set->lock);
 		RCU_INIT_POINTER(h->rnets[i], nets);
 	}
 #endif
net/netfilter/ipset/ip_set_hash_netiface.c +0 -1
index b44b95f766b7a..b602cc43565dd 100644
@@ -38,7 +38,6 @@ MODULE_ALIAS("ip_set_hash:net,iface");
 #define HTYPE		hash_netiface
 #define IP_SET_HASH_WITH_NETS
 #define IP_SET_HASH_WITH_MULTI
-#define IP_SET_HASH_WITH_NET0
 
 #define STRSCPY(a, b)	strscpy(a, b, IFNAMSIZ)
 
net/netfilter/ipset/ip_set_hash_netportnet.c +0 -1
index 6291532be7a5a..61af1ce271279 100644
@@ -36,7 +36,6 @@ MODULE_ALIAS("ip_set_hash:net,port,net");
 #define IP_SET_HASH_WITH_PROTO
 #define IP_SET_HASH_WITH_NETS
 #define IPSET_NET_COUNT 2
-#define IP_SET_HASH_WITH_NET0
 
 /* IPv4 variant */
 
Signature · 1 line
2.53.0
author maintainer
#1590 lore raw

PATCH 1574/1815 netfilter: ctnetlink: do not expose expectation DEAD flag

In reply to Greg Kroah-Hartman

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

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

From: Pablo Neira Ayuso <[email protected]>

[ Upstream commit 322371b09058ad10d0282a0e7ec8eaa764e6aaac ]

Expose expectation flags included in the NF_CT_EXPECT_MASK bitmask only. The DEAD flag is internal, do not expose it.

Fixes b8b09dc2bf35 ("netfilter: nf_conntrack_expect: use conntrack GC to reap expectations")
---
 net/netfilter/nf_conntrack_netlink.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/netfilter/nf_conntrack_netlink.c +1 -1
index 31cbb1b55b9e6..11e873a0bd149 100644
@@ -3042,7 +3042,7 @@ ctnetlink_exp_dump_expect(struct sk_buff *skb,
 #endif
 	if (nla_put_be32(skb, CTA_EXPECT_TIMEOUT, htonl(timeout)) ||
 	    nla_put_be32(skb, CTA_EXPECT_ID, nf_expect_get_id(exp)) ||
-	    nla_put_be32(skb, CTA_EXPECT_FLAGS, htonl(exp->flags)) ||
+	    nla_put_be32(skb, CTA_EXPECT_FLAGS, htonl(exp->flags & NF_CT_EXPECT_MASK)) ||
 	    nla_put_be32(skb, CTA_EXPECT_CLASS, htonl(exp->class)))
 		goto nla_put_failure;
 
Signature · 1 line
2.53.0
author maintainer
#1591 lore raw

PATCH 1575/1815 ipvs: fix integer overflow in ftp helper port/address parsing

In reply to Greg Kroah-Hartman

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

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

From: Joas Antonio dos Santos <[email protected]>

[ Upstream commit e625a9477d12baaff4025c5f9989184a907ea8fc ]

ip_vs_ftp_get_addrport() accumulates decimal digits into a __u16 (hport) and into unsigned char (p[]) without checking for overflow. A crafted FTP PASV/EPSV response with an over-long port or address octet wraps the value, so the helper configures the data connection with a truncated port/address.

The netfilter conntrack FTP helper had the same defect, fixed in commit 2b413fc689ba ("netfilter: nf_conntrack_ftp: avoid u16 overflows"). Apply the equivalent fix here: widen the port accumulator to u32 and reject values above 65535, and reject address octets above 255.

---
 net/netfilter/ipvs/ip_vs_ftp.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
net/netfilter/ipvs/ip_vs_ftp.c +8 -2
index b315c608fda43..9e3e005a82635 100644
@@ -102,7 +102,7 @@ static int ip_vs_ftp_get_addrport(char *data, char *data_limit,
 	char *s, c;
 	unsigned char p[6];
 	char edelim;
-	__u16 hport;
+	__u32 hport;
 	int i = 0;
 
 	if (data_limit - data < plen) {
@@ -144,7 +144,11 @@ static int ip_vs_ftp_get_addrport(char *data, char *data_limit,
 				return -1;
 			c = *data;
 			if (isdigit(c)) {
-				p[i] = p[i]*10 + c - '0';
+				unsigned int val = p[i] * 10 + c - '0';
+
+				if (val > 255)
+					return -1;
+				p[i] = val;
 			} else if (c == ',' && i < 5) {
 				i++;
 				p[i] = 0;
@@ -222,6 +226,8 @@ static int ip_vs_ftp_get_addrport(char *data, char *data_limit,
 		if (!isdigit(*s))
 			break;
 		hport = hport * 10 + *s - '0';
+		if (hport > 65535)
+			return -1;
 	}
 	if (s == data_limit || !hport || *s != edelim)
 		return -1;
Signature · 1 line
2.53.0
author maintainer
#1592 lore raw

PATCH 1576/1815 vxlan: vnifilter: enforce exact length of GROUP/GROUP6 attributes

In reply to Greg Kroah-Hartman

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

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

From: Xiang Mei <[email protected]>

[ Upstream commit 984f831dda31b3a18f47454cf64989f65402879e ]

The VXLAN VNI filter entry policy declares the GROUP/GROUP6 address attributes as NLA_BINARY with only a maximum length, so validate_nla() accepts a payload shorter than the address. The GROUP consumer reads it with nla_get_in_addr(), an unconditional 4-byte load, so a short attribute over-reads up to 3 bytes of uninitialised slab data, which are stored into remote_ip and echoed back via RTM_GETTUNNEL, disclosing kernel memory.

Switch both entries to NLA_POLICY_EXACT_LEN() so the validator rejects any GROUP/GROUP6 that is not exactly 4 / 16 bytes; a valid address is always sent at full width.

Fixes f9c4bb0b245c ("vxlan: vni filtering support on collect metadata device")
---
 drivers/net/vxlan/vxlan_vnifilter.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/net/vxlan/vxlan_vnifilter.c +2 -4
index 3e76f4e210944..dd94085e08865 100644
@@ -462,10 +462,8 @@ static int vxlan_vnifilter_dump(struct sk_buff *skb, struct netlink_callback *cb
 static const struct nla_policy vni_filter_entry_policy[VXLAN_VNIFILTER_ENTRY_MAX + 1] = {
 	[VXLAN_VNIFILTER_ENTRY_START] = { .type = NLA_U32 },
 	[VXLAN_VNIFILTER_ENTRY_END] = { .type = NLA_U32 },
-	[VXLAN_VNIFILTER_ENTRY_GROUP]	= { .type = NLA_BINARY,
-					    .len = sizeof_field(struct iphdr, daddr) },
-	[VXLAN_VNIFILTER_ENTRY_GROUP6]	= { .type = NLA_BINARY,
-					    .len = sizeof(struct in6_addr) },
+	[VXLAN_VNIFILTER_ENTRY_GROUP]	= NLA_POLICY_EXACT_LEN(sizeof_field(struct iphdr, daddr)),
+	[VXLAN_VNIFILTER_ENTRY_GROUP6]	= NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
 };
 
 static const struct nla_policy vni_filter_policy[VXLAN_VNIFILTER_MAX + 1] = {
Signature · 1 line
2.53.0
author maintainer
#1593 lore raw

PATCH 1577/1815 net: dsa: mv88e6xxx: Fix PCS link check on CMODE read error

In reply to Greg Kroah-Hartman

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

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

From: Ruoyu Wang <[email protected]>

[ Upstream commit 7b196e27ad58e612ad1c04b347d0c2135045aa14 ]

mv88e6352_pcs_link_check() ignores errors returned by port_get_cmode(). If the port status register read fails, mv88e6352_port_get_cmode() returns without setting cmode. The link check then compares an uninitialized value and may incorrectly treat the PCS as active.

Save the return value and fail the link check after releasing the register lock. marvell_c22_pcs_get_state() initializes the reported link state to down before calling the check, so a read failure is handled safely until a later poll succeeds.

This issue was found by a static analysis checker and confirmed by manual source review.

Fixes 85764555442f ("net: dsa: mv88e6xxx: convert 88e6352 to phylink_pcs")
---
 drivers/net/dsa/mv88e6xxx/pcs-6352.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/net/dsa/mv88e6xxx/pcs-6352.c +4 -1
index 4228ae5bb9db0..437054711a2d8 100644
@@ -305,13 +305,16 @@ static bool mv88e6352_pcs_link_check(struct marvell_c22_pcs *mpcs)
 	struct mv88e6xxx_port *port = mpcs->port;
 	struct mv88e6xxx_chip *chip = port->chip;
 	u8 cmode;
+	int err;
 
 	/* Port 4 can be in auto-media mode. Check that the port is
 	 * associated with the mpcs.
 	 */
 	mv88e6xxx_reg_lock(chip);
-	chip->info->ops->port_get_cmode(chip, port->port, &cmode);
+	err = chip->info->ops->port_get_cmode(chip, port->port, &cmode);
 	mv88e6xxx_reg_unlock(chip);
+	if (err)
+		return false;
 
 	return cmode == MV88E6XXX_PORT_STS_CMODE_100BASEX ||
 	       cmode == MV88E6XXX_PORT_STS_CMODE_1000BASEX ||
Signature · 1 line
2.53.0
author maintainer
#1594 lore raw

PATCH 1578/1815 tls: fix RX desync on overlapping skbs

In reply to Greg Kroah-Hartman

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

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

From: Maximilian Immanuel Brandtner <[email protected]>

[ Upstream commit 9466ef3ec972bee926731a766f73533dec590065 ]

The TCP receive queue can hold adjacent skbs whose sequence ranges overlap. The tls fast-path reads the record header with skb_copy_bits() by byte offset, which assumes skbs do not overlap, so a header split across the overlap is misread and the connection aborts (-EMSGSIZE/-EINVAL). tls_strp_check_queue_ok() detects such overlaps but only ran after the header was parsed, never covering the header itself.

Observed with parallel kTLS connections on:
- ConnectX-7 + IPsec crypto offload + GRO
- VirtIO (8 queues) + GRO

Fixes 84c61fe1a75b ("tls: rx: do not use the standard strparser")
---
 net/tls/tls_strp.c | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)
net/tls/tls_strp.c +11 -5
index 61b10c697eccb..6cc222008d95c 100644
@@ -430,9 +430,10 @@ static int tls_strp_read_copy(struct tls_strparser *strp, bool qshort)
 	return 0;
 }
 
-static bool tls_strp_check_queue_ok(struct tls_strparser *strp)
+static bool tls_strp_check_queue_ok(struct tls_strparser *strp,
+				    unsigned int len)
 {
-	unsigned int len = strp->stm.offset + strp->stm.full_len;
+	unsigned int remaining = strp->stm.offset + len;
 	struct sk_buff *first, *skb;
 	u32 seq;
 
@@ -443,9 +444,9 @@ static bool tls_strp_check_queue_ok(struct tls_strparser *strp)
 	/* Make sure there's no duplicate data in the queue,
 	 * and the decrypted status matches.
 	 */
-	while (skb->len < len) {
+	while (skb->len < remaining) {
 		seq += skb->len;
-		len -= skb->len;
+		remaining -= skb->len;
 		skb = skb->next;
 
 		if (TCP_SKB_CB(skb)->seq != seq)
@@ -525,6 +526,11 @@ static int tls_strp_read_sock(struct tls_strparser *strp)
 
 	tls_strp_load_anchor_with_queue(strp, inq);
 	if (!strp->stm.full_len) {
+		if (inq < TLS_HEADER_SIZE)
+			return tls_strp_read_copy(strp, true);
+		if (!tls_strp_check_queue_ok(strp, TLS_HEADER_SIZE))
+			return tls_strp_read_copy(strp, false);
+
 		sz = tls_rx_msg_size(strp, strp->anchor);
 		if (sz < 0)
 			return sz;
@@ -535,7 +541,7 @@ static int tls_strp_read_sock(struct tls_strparser *strp)
 			return tls_strp_read_copy(strp, true);
 	}
 
-	if (!tls_strp_check_queue_ok(strp))
+	if (!tls_strp_check_queue_ok(strp, strp->stm.full_len))
 		return tls_strp_read_copy(strp, false);
 
 	WRITE_ONCE(strp->msg_ready, 1);
Signature · 1 line
2.53.0
author maintainer
#1595 lore raw

PATCH 1579/1815 net: bridge: vlan: fix inverted default vlan notification

In reply to Greg Kroah-Hartman

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

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

From: Nikolay Aleksandrov <[email protected]>

[ Upstream commit 21040c7f931502070dcc66bb0f1aeed07dec032b ]

A notification should be emitted only when the vlan delete was successful and not otherwise. The proper check is if br/nbp_vlan_delete returned 0.

Fixes f545923b4a6b ("net: bridge: vlan: notify on vlan add/delete/change flags")
---
 net/bridge/br_vlan.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
net/bridge/br_vlan.c +2 -2
index 31c1b2cf75d92..1e0e436629ece 100644
@@ -1136,7 +1136,7 @@ int __br_vlan_set_default_pvid(struct net_bridge *br, u16 pvid,
 		if (err)
 			goto out;
 
-		if (br_vlan_delete(br, old_pvid))
+		if (!br_vlan_delete(br, old_pvid))
 			br_vlan_notify(br, NULL, old_pvid, 0, RTM_DELVLAN);
 		br_vlan_notify(br, NULL, pvid, 0, RTM_NEWVLAN);
 		__set_bit(0, changed);
@@ -1158,7 +1158,7 @@ int __br_vlan_set_default_pvid(struct net_bridge *br, u16 pvid,
 				   &vlchange, extack);
 		if (err)
 			goto err_port;
-		if (nbp_vlan_delete(p, old_pvid))
+		if (!nbp_vlan_delete(p, old_pvid))
 			br_vlan_notify(br, p, old_pvid, 0, RTM_DELVLAN);
 		br_vlan_notify(p->br, p, pvid, 0, RTM_NEWVLAN);
 		__set_bit(p->port_no, changed);
Signature · 1 line
2.53.0
author maintainer
#1596 lore raw

PATCH 1580/1815 cuse: wait for pending RCU callbacks on module exit

In reply to Greg Kroah-Hartman

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

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

From: Baokun Li <[email protected]>

[ Upstream commit 4deb3edead0c0e172cc7349e8855d741d3c5e162 ]

Since commit 053fc4f755ad ("fuse: fix UAF in rcu pathwalks"), fuse_conn_put() frees the fuse_conn through call_rcu() rather than synchronously. For cuse, fc->release is cuse_fc_release(), which lives in the cuse module. If the module is removed before the RCU grace period ends, the callback jumps into freed module memory:

userspace / module unload | RCU softirq
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 close(/dev/cuse)                    |
  cuse_channel_release()             |
   fuse_dev_release()                |
    fuse_conn_put(fch->conn)         |
     call_rcu(delayed_release) ------+---> callback queued
                                     |
 rmmod cuse                          |
  cuse_exit()                        |
   cuse_channel_destroy()            |
   ...                               |
   return                            |
                                     |
 <module text freed>                 |
                                     |  rcu_do_batch()
                                     |   delayed_release()
                                     |    fc->release()
                                     |     -> cuse_fc_release()
                                     |        ^^^ freed text!

The freed module text is unmapped by vfree(), so the jump into the stale callback triggers a page-fault Oops. If the virtual address is subsequently reused, the callback could execute unrelated code (undefined behaviour).

Fix this by calling rcu_barrier() in cuse_exit() so that any pending fuse_conn release callback completes before the module is removed.

Fixes 053fc4f755ad ("fuse: fix UAF in rcu pathwalks")
---
 fs/fuse/cuse.c | 5 +++++
 1 file changed, 5 insertions(+)
fs/fuse/cuse.c +5 -0
index 3c15b5ba16d71..1c71783ca5a51 100644
@@ -653,6 +653,11 @@ static void __exit cuse_exit(void)
 {
 	misc_deregister(&cuse_miscdev);
 	class_destroy(cuse_class);
+	/*
+	 * Wait for pending call_rcu() callbacks that call back into
+	 * this module via fc->release (cuse_fc_release).
+	 */
+	rcu_barrier();
 }
 
 module_init(cuse_init);
Signature · 1 line
2.53.0
author maintainer
#1597 lore raw

PATCH 1581/1815 fs/ntfs3: fix out-of-bounds read in read_log_rec_buf()

In reply to Greg Kroah-Hartman

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

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

From: Konstantin Komarov <[email protected]>

[ Upstream commit de603b9d377fab57a5e6432fa84a9f36b32c1636 ]

read_log_rec_buf() copies a log record into a caller buffer starting at

	u32 off = lsn_to_page_off(log, lsn) + log->record_header_len;

log->record_header_len (and log->data_off, used for the following pages) comes verbatim from the on-disk restart area and is only checked for 8-byte alignment in is_rst_area_valid(), so off can exceed log->page_size. "tail = log->page_size - off" then underflows and memcpy() reads past the page_size-sized buffer returned by read_log_page(), spilling adjacent slab memory into the replay buffer.

This is reachable by mounting a crafted NTFS image:

 BUG: KASAN: slab-out-of-bounds in read_log_rec_buf+0x216/0x580
 Read of size 64 at addr ffff88800a877ff8 by task exploit/127
  read_log_rec_buf fs/ntfs3/fslog.c:2299
  log_replay fs/ntfs3/fslog.c:4216
  ntfs_loadlog_and_replay fs/ntfs3/fsntfs.c:324
  ntfs_fill_super fs/ntfs3/super.c:1392
  get_tree_bdev_flags fs/super.c:1694
  __x64_sys_mount fs/namespace.c:4360
 The buggy address is located 4088 bytes to the right of
 the 4096-byte region [ffff88800a876000, ffff88800a877000)

Reject an in-page offset outside the current page before the copy.

Fixes b46acd6a6a62 ("fs/ntfs3: Add NTFS journal")
Assisted-by Claude:claude-opus-4-8
[[email protected]: replaced the >= sign with >]
---
 fs/ntfs3/fslog.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
fs/ntfs3/fslog.c +9 -1
index 1b96ee8208db5..b05e48b28625a 100644
@@ -2301,7 +2301,15 @@ static int read_log_rec_buf(struct ntfs_log *log,
 	 */
 	for (;;) {
 		bool usa_error;
-		u32 tail = log->page_size - off;
+		u32 tail;
+
+		/* off comes from the on-disk restart area; bound it. */
+		if (off > log->page_size) {
+			err = -EINVAL;
+			goto out;
+		}
+
+		tail = log->page_size - off;
 
 		if (tail >= data_len)
 			tail = data_len;
Signature · 1 line
2.53.0
author maintainer
#1598 lore raw

PATCH 1582/1815 fs/ntfs3: validate ef->size covers the records name and value

In reply to Greg Kroah-Hartman

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

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

From: Weiming Shi <[email protected]>

[ Upstream commit c22f91d82cb9a29d22bdffdce6c803467984ad0c ]

When an EA record has a non-zero ef->size, ntfs_read_ea() only checks that the record fits in the remaining buffer (ea_size > bytes), not that ef->size is large enough to hold the record's own name_len + 1 + elength.

A crafted image can pass validation with, e.g., ef->size = 24 but elength = 0xffff. ntfs_get_ea() then trusts elength and copies it out of the undersized record, reading past the kmalloc(info->size) allocation and leaking heap memory to userspace via getxattr():

 BUG: KASAN: slab-out-of-bounds in ntfs_get_ea (fs/ntfs3/xattr.c:302)
 Read of size 65535 at addr ffff888100794550 by task exploit
  __asan_memcpy (mm/kasan/shadow.c:105)
  ntfs_get_ea (fs/ntfs3/xattr.c:302)
  ntfs_getxattr (fs/ntfs3/xattr.c:848)
  __vfs_getxattr (fs/xattr.c:441)
  vfs_getxattr (fs/xattr.c:474)
  do_getxattr (fs/xattr.c:800)
  path_getxattrat (fs/xattr.c:868)
  do_syscall_64 (arch/x86/entry/syscall_64.c:94)

The buggy address is located 80 bytes inside of
allocated 84-byte region in cache kmalloc-96

Compute the size the record needs and require ef->size to cover it.

Fixes 0e8235d28f3a ("fs/ntfs3: Check fields while reading")
Assisted-by Claude:claude-opus-4-8
---
 fs/ntfs3/xattr.c | 21 ++++++++++++---------
 1 file changed, 12 insertions(+), 9 deletions(-)
fs/ntfs3/xattr.c +12 -9
index 04814dd293752..6697362e655bf 100644
@@ -146,26 +146,29 @@ static int ntfs_read_ea(struct ntfs_inode *ni, struct EA_FULL **ea,
 	for (off = 0; off < size; off += ea_size) {
 		const struct EA_FULL *ef = Add2Ptr(ea_p, off);
 		u32 bytes = size - off;
+		size_t need;
 
 		/* Check if we can use field ea->size. */
 		if (bytes < sizeof(ef->size))
 			goto out1;
 
+		/* Check if we can use fields ef->name_len and ef->elength. */
+		if (bytes < offsetof(struct EA_FULL, name))
+			goto out1;
+
+		/* Size needed to hold this record's name and value. */
+		need = struct_size(ef, name,
+				   1 + ef->name_len + le16_to_cpu(ef->elength));
+
 		if (ef->size) {
 			ea_size = le32_to_cpu(ef->size);
-			if (ea_size > bytes)
+			/* ef->size must fit the list and cover the record. */
+			if (ea_size > bytes || ea_size < need)
 				goto out1;
 			continue;
 		}
 
-		/* Check if we can use fields ef->name_len and ef->elength. */
-		if (bytes < offsetof(struct EA_FULL, name))
-			goto out1;
-
-		ea_size = ALIGN(struct_size(ef, name,
-					    1 + ef->name_len +
-						    le16_to_cpu(ef->elength)),
-				4);
+		ea_size = ALIGN(need, 4);
 		if (ea_size > bytes)
 			goto out1;
 	}
Signature · 1 line
2.53.0
author maintainer
#1599 lore raw

PATCH 1583/1815 fuse: reject a duplicate fd= mount option

In reply to Greg Kroah-Hartman

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

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

From: Baokun Li <[email protected]>

[ Upstream commit ed976994939f05ffbb6e9e5482adc788e679c0ea ]

fuse_opt_fd() stored the fuse device in ctx->fud and bumped its refcount unconditionally:

        ctx->fud = fuse_dev_grab(file);

If fd= is given twice (two fsconfig FSCONFIG_SET_FD calls), the second call overwrites ctx->fud and grabs the new device, while the reference taken on the first device is never released - a permanent refcount leak that pins the first fuse_dev until reboot.

Reject a second fd= outright. ctx is zeroed on allocation, so a non-NULL ctx->fud reliably means the option was already processed.

Fixes d42eb23b2ef9 ("fuse: don't require /dev/fuse fd to be kept open during mount")
---
 fs/fuse/inode.c | 3 +++
 1 file changed, 3 insertions(+)
fs/fuse/inode.c +3 -0
index ce4891a04a378..a51be4221a329 100644
@@ -791,6 +791,9 @@ static int fuse_opt_fd(struct fs_context *fsc, struct file *file)
 {
 	struct fuse_fs_context *ctx = fsc->fs_private;
 
+	if (ctx->fud)
+		return invalfc(fsc, "Multiple fd specified");
+
 	if (file->f_op != &fuse_dev_operations)
 		return invalfc(fsc, "fd is not a fuse device");
 	/*
Signature · 1 line
2.53.0
author maintainer
#1600 lore raw

PATCH 1584/1815 soc: qcom: ubwc: Fix missing include

In reply to Greg Kroah-Hartman

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

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

From: Daniel Baluta <[email protected]>

[ Upstream commit c6441becf4d064bb1dcbccbd3e2276833804cff5 ]

When CONFIG_QCOM_UBWC_CONFIG=n, compiler needs to know the definition of ERR_PTR otherwise there will be a compilation error:

In file included from drivers/gpu/drm/msm/disp/dpu1/dpu_hw_sspp_v13.c:7:
./include/linux/soc/qcom/ubwc.h: In function ‘qcom_ubwc_config_get_data’:
./include/linux/soc/qcom/ubwc.h:45:16: error: implicit declaration of function ‘ERR_PTR’ [-Wimplicit-function-declaration]

Fix this by including <linux/err.h>

---
 include/linux/soc/qcom/ubwc.h | 1 +
 1 file changed, 1 insertion(+)
include/linux/soc/qcom/ubwc.h +1 -0
index 83d2c2a7116c0..f35c29440f4de 100644
@@ -8,6 +8,7 @@
 #define __QCOM_UBWC_H__
 
 #include <linux/bits.h>
+#include <linux/err.h>
 #include <linux/printk.h>
 #include <linux/types.h>
 
Signature · 1 line
2.53.0