Skip to contentSkip to conversation

6.18.66-rc1 review

PATCH In review Greg Kroah-Hartman 3 participants 995 messages Nov 25 Page 6 of 9

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

PATCH 531/990 accel/amdxdna: Preallocate hardware context schedulers

In reply to Greg Kroah-Hartman

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

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

From: Lizhi Hou <[email protected]>

[ Upstream commit f7afecd54296cf7ad6fa36f692d2a7427e32f25d ]

The hardware context scheduler fence is exposed through drm_syncobj_add_point(). After a hardware context is destroyed, userspace can still call drm_sched_fence_get_timeline_name() on the fence through SYNC_IOC_FILE_INFO. This results in a use-after-free when accessing fence->sched->name.

Preallocate hardware context schedulers and free them during device teardown instead. A destroyed hardware context no longer frees its scheduler, ensuring that the scheduler remains valid while its fences are still accessible.

Fixes aac243092b70 ("accel/amdxdna: Add command execution")
[ sashal: Adapted to the older tree by using ndev->xdna, a single firmware-load failure path that unwinds the scheduler init, and dropping the duplicate ndev declaration and assignment in the hwctx functions. ]
---
 drivers/accel/amdxdna/aie2_ctx.c | 117 +++++++++++++++++++++++--------
 drivers/accel/amdxdna/aie2_pci.c |   9 ++-
 drivers/accel/amdxdna/aie2_pci.h |   6 +-
 3 files changed, 99 insertions(+), 33 deletions(-)
drivers/accel/amdxdna/aie2_ctx.c +86 -31
index a87b24654c367..fb411887b6470 100644
@@ -7,6 +7,7 @@
 #include <drm/drm_device.h>
 #include <drm/drm_gem.h>
 #include <drm/drm_gem_shmem_helper.h>
+#include <drm/drm_managed.h>
 #include <drm/drm_print.h>
 #include <drm/drm_syncobj.h>
 #include <linux/hmm.h>
@@ -62,7 +63,7 @@ static void aie2_hwctx_status_restore(struct amdxdna_hwctx *hwctx)
 static void aie2_hwctx_stop(struct amdxdna_dev *xdna, struct amdxdna_hwctx *hwctx,
 			    struct drm_sched_job *bad_job)
 {
-	drm_sched_stop(&hwctx->priv->sched, bad_job);
+	drm_sched_stop(hwctx->priv->sched, bad_job);
 	aie2_destroy_context(xdna->dev_handle, hwctx);
 }
 
@@ -96,7 +97,7 @@ static int aie2_hwctx_restart(struct amdxdna_dev *xdna, struct amdxdna_hwctx *hw
 	}
 
 out:
-	drm_sched_start(&hwctx->priv->sched, 0);
+	drm_sched_start(hwctx->priv->sched, 0);
 	XDNA_DBG(xdna, "%s restarted, ret %d", hwctx->name, ret);
 	return ret;
 }
@@ -528,10 +529,19 @@ static void aie2_ctx_syncobj_destroy(struct amdxdna_hwctx *hwctx)
 	drm_syncobj_put(hwctx->priv->syncobj);
 }
 
-int aie2_hwctx_init(struct amdxdna_hwctx *hwctx)
+void aie2_hwctx_sched_fini(struct amdxdna_dev_hdl *ndev)
 {
-	struct amdxdna_client *client = hwctx->client;
-	struct amdxdna_dev *xdna = client->xdna;
+	int i;
+
+	for (i = 0; i < ndev->priv->hwctx_limit; i++)
+		drm_sched_fini(&ndev->hwctx_sched[i]);
+
+	ida_destroy(&ndev->hwctx_sched_ida);
+}
+
+int aie2_hwctx_sched_init(struct amdxdna_dev_hdl *ndev)
+{
+	struct amdxdna_dev *xdna = ndev->xdna;
 	const struct drm_sched_init_args args = {
 		.ops = &sched_ops,
 		.num_rqs = DRM_SCHED_PRIORITY_COUNT,
@@ -540,10 +550,57 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx)
 		.name = "amdxdna_js",
 		.dev = xdna->ddev.dev,
 	};
-	struct drm_gpu_scheduler *sched;
+	int i, ret;
+
+	ndev->hwctx_sched = drmm_kcalloc(&xdna->ddev, ndev->priv->hwctx_limit,
+					 sizeof(*ndev->hwctx_sched), GFP_KERNEL);
+	if (!ndev->hwctx_sched)
+		return -ENOMEM;
+
+	for (i = 0; i < ndev->priv->hwctx_limit; i++) {
+		ret = drm_sched_init(&ndev->hwctx_sched[i], &args);
+		if (ret) {
+			XDNA_ERR(xdna, "Failed to init DRM scheduler. ret %d", ret);
+			goto fini_sched;
+		}
+	}
+
+	ida_init(&ndev->hwctx_sched_ida);
+
+	return 0;
+
+fini_sched:
+	while (--i >= 0)
+		drm_sched_fini(&ndev->hwctx_sched[i]);
+
+	return ret;
+}
+
+static struct drm_gpu_scheduler *aie2_hwctx_sched_alloc(struct amdxdna_dev_hdl *ndev)
+{
+	int ret;
+
+	ret = ida_alloc_range(&ndev->hwctx_sched_ida, 0,
+			      ndev->priv->hwctx_limit - 1, GFP_KERNEL);
+	if (ret < 0)
+		return ERR_PTR(ret);
+
+	return &ndev->hwctx_sched[ret];
+}
+
+static void aie2_hwctx_sched_free(struct amdxdna_dev_hdl *ndev,
+				  struct drm_gpu_scheduler *sched)
+{
+	ida_free(&ndev->hwctx_sched_ida, sched - ndev->hwctx_sched);
+}
+
+int aie2_hwctx_init(struct amdxdna_hwctx *hwctx)
+{
+	struct amdxdna_client *client = hwctx->client;
+	struct amdxdna_dev *xdna = client->xdna;
+	struct amdxdna_dev_hdl *ndev = xdna->dev_handle;
 	struct amdxdna_hwctx_priv *priv;
 	struct amdxdna_gem_obj *heap;
-	struct amdxdna_dev_hdl *ndev;
 	int i, ret;
 
 	priv = kzalloc(sizeof(*hwctx->priv), GFP_KERNEL);
@@ -551,13 +608,26 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx)
 		return -ENOMEM;
 	hwctx->priv = priv;
 
+	priv->sched = aie2_hwctx_sched_alloc(ndev);
+	if (IS_ERR(priv->sched)) {
+		ret = PTR_ERR(priv->sched);
+		goto free_priv;
+	}
+
+	ret = drm_sched_entity_init(&priv->entity, DRM_SCHED_PRIORITY_NORMAL,
+				    &priv->sched, 1, NULL);
+	if (ret) {
+		XDNA_ERR(xdna, "Failed to initial sched entity. ret %d", ret);
+		goto free_sched;
+	}
+
 	mutex_lock(&client->mm_lock);
 	heap = client->dev_heap;
 	if (!heap) {
 		XDNA_ERR(xdna, "The client dev heap object not exist");
 		mutex_unlock(&client->mm_lock);
 		ret = -ENOENT;
-		goto free_priv;
+		goto free_entity;
 	}
 	drm_gem_object_get(to_gobj(heap));
 	mutex_unlock(&client->mm_lock);
@@ -590,30 +660,16 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx)
 		priv->cmd_buf[i] = abo;
 	}
 
-	sched = &priv->sched;
 	mutex_init(&priv->io_lock);
 
 	fs_reclaim_acquire(GFP_KERNEL);
 	might_lock(&priv->io_lock);
 	fs_reclaim_release(GFP_KERNEL);
 
-	ret = drm_sched_init(sched, &args);
-	if (ret) {
-		XDNA_ERR(xdna, "Failed to init DRM scheduler. ret %d", ret);
-		goto free_cmd_bufs;
-	}
-
-	ret = drm_sched_entity_init(&priv->entity, DRM_SCHED_PRIORITY_NORMAL,
-				    &sched, 1, NULL);
-	if (ret) {
-		XDNA_ERR(xdna, "Failed to initial sched entiry. ret %d", ret);
-		goto free_sched;
-	}
-
 	ret = aie2_hwctx_col_list(hwctx);
 	if (ret) {
 		XDNA_ERR(xdna, "Create col list failed, ret %d", ret);
-		goto free_entity;
+		goto free_cmd_bufs;
 	}
 
 	ret = amdxdna_pm_resume_get(xdna);
@@ -641,7 +697,6 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx)
 	amdxdna_pm_suspend_put(xdna);
 
 	hwctx->status = HWCTX_STAT_INIT;
-	ndev = xdna->dev_handle;
 	ndev->hwctx_num++;
 	init_waitqueue_head(&priv->job_free_wq);
 
@@ -655,10 +710,6 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx)
 	amdxdna_pm_suspend_put(xdna);
 free_col_list:
 	kfree(hwctx->col_list);
-free_entity:
-	drm_sched_entity_destroy(&priv->entity);
-free_sched:
-	drm_sched_fini(&priv->sched);
 free_cmd_bufs:
 	for (i = 0; i < ARRAY_SIZE(priv->cmd_buf); i++) {
 		if (!priv->cmd_buf[i])
@@ -668,6 +719,10 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx)
 	amdxdna_gem_unpin(heap);
 put_heap:
 	drm_gem_object_put(to_gobj(heap));
+free_entity:
+	drm_sched_entity_destroy(&priv->entity);
+free_sched:
+	aie2_hwctx_sched_free(ndev, priv->sched);
 free_priv:
 	kfree(priv);
 	return ret;
@@ -687,10 +742,10 @@ void aie2_hwctx_fini(struct amdxdna_hwctx *hwctx)
 	aie2_hwctx_wait_for_idle(hwctx);
 
 	/* Request fw to destroy hwctx and cancel the rest pending requests */
-	drm_sched_stop(&hwctx->priv->sched, NULL);
+	drm_sched_stop(hwctx->priv->sched, NULL);
 	aie2_release_resource(hwctx);
 	hwctx->status = HWCTX_STAT_STOP;
-	drm_sched_start(&hwctx->priv->sched, 0);
+	drm_sched_start(hwctx->priv->sched, 0);
 
 	mutex_unlock(&xdna->dev_lock);
 	drm_sched_entity_destroy(&hwctx->priv->entity);
@@ -701,7 +756,7 @@ void aie2_hwctx_fini(struct amdxdna_hwctx *hwctx)
 		   atomic64_read(&hwctx->job_free_cnt));
 	mutex_lock(&xdna->dev_lock);
 
-	drm_sched_fini(&hwctx->priv->sched);
+	aie2_hwctx_sched_free(ndev, hwctx->priv->sched);
 	aie2_ctx_syncobj_destroy(hwctx);
 
 	for (idx = 0; idx < ARRAY_SIZE(hwctx->priv->cmd_buf); idx++)
drivers/accel/amdxdna/aie2_pci.c +8 -1
index 4a7d1feac6a5e..5a030da5b9d4a 100644
@@ -502,11 +502,15 @@ static int aie2_init(struct amdxdna_dev *xdna)
 	ndev->priv = xdna->dev_info->dev_priv;
 	ndev->xdna = xdna;
 
+	ret = aie2_hwctx_sched_init(ndev);
+	if (ret)
+		return ret;
+
 	ret = request_firmware(&fw, ndev->priv->fw_path, &pdev->dev);
 	if (ret) {
 		XDNA_ERR(xdna, "failed to request_firmware %s, ret %d",
 			 ndev->priv->fw_path, ret);
-		return ret;
+		goto free_hwctx_sched;
 	}
 
 	ret = pcim_enable_device(pdev);
@@ -597,6 +601,8 @@ static int aie2_init(struct amdxdna_dev *xdna)
 	aie2_hw_stop(xdna);
 release_fw:
 	release_firmware(fw);
+free_hwctx_sched:
+	aie2_hwctx_sched_fini(ndev);
 
 	return ret;
 }
@@ -605,6 +611,7 @@ static void aie2_fini(struct amdxdna_dev *xdna)
 {
 	amdxdna_pm_fini(xdna);
 	aie2_hw_stop(xdna);
+	aie2_hwctx_sched_fini(xdna->dev_handle);
 }
 
 static int aie2_get_aie_status(struct amdxdna_client *client,
drivers/accel/amdxdna/aie2_pci.h +5 -1
index 7d56f4bca3d63..a3f66e87d0a55 100644
@@ -133,7 +133,7 @@ struct amdxdna_hwctx_priv {
 	struct amdxdna_gem_obj		*heap;
 	void				*mbox_chann;
 
-	struct drm_gpu_scheduler	sched;
+	struct drm_gpu_scheduler	*sched;
 	struct drm_sched_entity		entity;
 
 	struct mutex			io_lock; /* protect seq and cmd order */
@@ -173,6 +173,8 @@ struct amdxdna_dev_hdl {
 	u32				total_col;
 	struct aie_version		version;
 	struct aie_metadata		metadata;
+	struct drm_gpu_scheduler	*hwctx_sched;
+	struct ida			hwctx_sched_ida;
 
 	/* power management and clock*/
 	enum amdxdna_power_mode_type	pw_mode;
@@ -293,6 +295,8 @@ int aie2_sync_bo(struct amdxdna_hwctx *hwctx, struct amdxdna_sched_job *job,
 /* aie2_hwctx.c */
 int aie2_hwctx_init(struct amdxdna_hwctx *hwctx);
 void aie2_hwctx_fini(struct amdxdna_hwctx *hwctx);
+int aie2_hwctx_sched_init(struct amdxdna_dev_hdl *ndev);
+void aie2_hwctx_sched_fini(struct amdxdna_dev_hdl *ndev);
 int aie2_hwctx_config(struct amdxdna_hwctx *hwctx, u32 type, u64 value, void *buf, u32 size);
 void aie2_hwctx_suspend(struct amdxdna_client *client);
 int aie2_hwctx_resume(struct amdxdna_client *client);
Signature · 1 line
2.53.0
author maintainer
#533 lore raw

PATCH 532/990 bpf: Check fastcall stack contract once for all stack accesses

In reply to Greg Kroah-Hartman

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

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

From: Kumar Kartikeya Dwivedi <[email protected]>

[ Upstream commit ec3a69e7c021cd826be8886ba6af4ee3147788fb ]

When the verifier inlines a bpf_fastcall helper or kfunc, it removes the spill/fill pairs that clang emitted around the call and lowers the subprogram's stack depth so that their slots are no longer part of the frame. This is only safe if nothing else accesses those slots or any slot below them. check_fastcall_stack_contract() enforces this: an access to that region from outside a fastcall pattern disables the rewrite for the subprogram. It is called from the four stack load and store paths, and two kinds of access escape it.

Stack buffers passed to helpers and kfuncs are validated by check_stack_range_initialized(), which does not call it. If such a buffer is the only other access to the region, the rewrite is still applied, the JIT reserves a frame that does not contain the buffer, and the helper reads or writes live kernel stack below the program's frame. For example, without CAP_PERFMON:

	*(u64 *)(r10 - 8) = r1;
	call bpf_get_smp_processor_id;
	r1 = *(u64 *)(r10 - 8);
	r2 = 0;
	r3 = r10;
	r3 += -64;
	r4 = 8;
	call bpf_skb_load_bytes;

is accepted with a stack depth of 0 instead of 64.

Some buffers got the check indirectly. For constant-sized outputs in raw mode, mark_raw_stack() marks the buffer initialized through ordinary byte stores, which call the check. Commit 5da4a9f26fca ("bpf: Preserve stack initialization for generic output buffers") limited raw mode to programs that may read uninitialized stack, so outputs of programs without CAP_PERFMON lost the check, as in the example above. Buffers that never used raw mode have lacked the check since fastcall support was added: helper inputs such as a map key whose only store is a fastcall spill, variable-sized outputs, and buffers at a variable stack offset.

check_stack_read_fixed_off() applies the check to the current frame, even when the pointer targets a caller's stack. A callee can therefore read a caller's fastcall spill slot without disabling the caller's rewrite:

	caller:
	r1 = 1;
	*(u64 *)(r10 - 8) = r1;
	call bpf_get_smp_processor_id;
	r1 = *(u64 *)(r10 - 8);
	r1 = r10;
	r1 += -8;
	call callee;

	callee:
	r0 = *(u64 *)(r1 + 0);

The caller's spill and fill are removed and its stack depth drops to 0, but the verifier still tracks the slot as holding the spilled constant. The callee's load then reads kernel stack outside the caller's frame, while the verifier assumes r0 is 1.

Every stack access first goes through check_stack_access_within_bounds():
loads and stores from check_mem_access(), helper and kfunc buffers from check_stack_range_initialized(), and the dynptr, iterator and irq flag slots that kfuncs initialize, whose handlers use check_mem_access(). It resolves the frame that owns the slots and the lowest offset the access can touch, and it is the only place where a frame's stack depth grows. Check the contract there, once for every access, and drop the calls from the stack read and write paths. Zero-sized buffers touch no stack and leave the rewrite enabled.

Fixes 5b5f51bff1b6 ("bpf: no_caller_saved_registers attribute for helper calls")
Fixes 5da4a9f26fca ("bpf: Preserve stack initialization for generic output buffers")
[ sashal: Removed the four old fastcall stack-contract calls and added the single check in check_stack_access_within_bounds(); the code matches upstream, with only hunk context adjusted for surrounding code that differs. ]
---
 kernel/bpf/verifier.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
kernel/bpf/verifier.c +9 -4
index 139671b393a05..e146b860f5692 100644
@@ -5230,7 +5230,6 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
 		bpf_mark_stack_write(env, state->frameno, BIT(spi));
 	}
 
-	check_fastcall_stack_contract(env, state, insn_idx, off);
 	mark_stack_slot_scratched(env, spi);
 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
 		bool reg_value_fits;
@@ -5349,7 +5348,6 @@ static int check_stack_write_var_off(struct bpf_verifier_env *env,
 			return err;
 	}
 
-	check_fastcall_stack_contract(env, state, insn_idx, min_off);
 	/* Variable offset writes destroy any spilled pointers in range. */
 	for (i = min_off; i < max_off; i++) {
 		u8 new_type, *stype;
@@ -5493,7 +5491,6 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
 	reg = &reg_state->stack[spi].spilled_ptr;
 
 	mark_stack_slot_scratched(env, spi);
-	check_fastcall_stack_contract(env, state, env->insn_idx, off);
 	err = bpf_mark_stack_read(env, reg_state->frameno, env->insn_idx, BIT(spi));
 	if (err)
 		return err;
@@ -5652,7 +5649,6 @@ static int check_stack_read_var_off(struct bpf_verifier_env *env,
 	min_off = reg->smin_value + off;
 	max_off = reg->smax_value + off;
 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
-	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
 	return 0;
 }
 
@@ -7688,6 +7684,15 @@ static int check_stack_access_within_bounds(
 		return err;
 	}
 
+	/*
+	 * Every stack access passes through here, including buffers passed to
+	 * helpers and kfuncs and accesses into a caller's frame, so check the
+	 * fastcall contract of the frame that owns the slots once for all of
+	 * them. Zero-sized accesses touch no stack and keep the rewrite enabled.
+	 */
+	if (access_size)
+		check_fastcall_stack_contract(env, state, env->insn_idx, min_off);
+
 	/* Note that there is no stack access with offset zero, so the needed stack
 	 * size is -min_off, not -min_off+1.
 	 */
Signature · 1 line
2.53.0
author maintainer
#534 lore raw

PATCH 533/990 bpf: Look at frame 0 when telling async callback entries apart

In reply to Greg Kroah-Hartman

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

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

From: Puranjay Mohan <[email protected]>

[ Upstream commit e55220162aae99622d9e80d4700e51c13a6f2a16 ]

push_async_cb() sets in_async_callback_fn and async_entry_cnt on the callback's own frame, which is frame 0 of the fresh state it starts, and setup_func_entry() copies neither, so a subprog called by the callback carries neither. Two places read them from the innermost frame instead.

is_state_visited() skips the infinite loop check when two states differ in async_entry_cnt, because seeing the same state on a second entry into an async callback is not a loop. A callback which re-arms itself and calls a subprog therefore compares the two entries at a loop inside that subprog, where the innermost frame is the subprog's and has no flag set, and the state is rejected:

infinite loop detected at insn 60

push_callback_call() numbers a new entry as the caller's count plus one. When the callback re-arms itself from a subprog, the caller is that subprog's frame with a count of 0, so every entry is numbered 1, the check above never sees a difference, and a loop anywhere in such a callback is rejected the same way.

Read the flag and the count from frame 0 in both places. A loop within a single entry still has a matching count and is still caught, and frame 0 of a non-async state does not have the flag set, so nothing else changes.

The two other readers are already correct: check_return_code() reads frame[0], and the one in do_check() is reached only after an early return for curframe != 0.

Fixes bfc6bb74e4f1 ("bpf: Implement verifier support for validation of async callbacks.")
[ sashal: Ported the is_state_visited() hunk into kernel/bpf/verifier.c because the state-pruning code hasn't been split out into states.c in this tree; the push_callback_call() hunk applied unchanged. ]
---
 kernel/bpf/verifier.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
kernel/bpf/verifier.c +3 -3
index e146b860f5692..8ac91e5ced84b 100644
@@ -10884,7 +10884,7 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 		if (IS_ERR(async_cb))
 			return PTR_ERR(async_cb);
 		callee = async_cb->frame[0];
-		callee->async_entry_cnt = caller->async_entry_cnt + 1;
+		callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1;
 
 		/* Convert bpf_timer_set_callback() args into timer callback args */
 		err = set_callee_state_cb(env, caller, callee, insn_idx);
@@ -20017,10 +20017,10 @@ static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
 			continue;
 
 		if (sl->state.branches) {
-			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
+			struct bpf_func_state *frame = sl->state.frame[0];
 
 			if (frame->in_async_callback_fn &&
-			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
+			    frame->async_entry_cnt != cur->frame[0]->async_entry_cnt) {
 				/* Different async_entry_cnt means that the verifier is
 				 * processing another entry into async callback.
 				 * Seeing the same state is not an indication of infinite
Signature · 1 line
2.53.0
author maintainer
#535 lore raw

PATCH 534/990 ASoC: mediatek: mt8188: fix clk leak on error in audsys_clk_register

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 6cddf6e56d2539fd13c0ee9dd817c4e06a967173 ]

devm_add_action_or_reset() is called after the loop that registers gate clocks. If kzalloc() fails mid-loop, the function returns -ENOMEM before that call, so cleanup is never registered and all previously registered clocks leak permanently.

Move devm_add_action_or_reset() before the loop so cleanup is always scheduled. The clock from the current (failing) iteration is not yet stored in afe_priv->lookup[i], so it still needs an explicit clk_unregister_gate() call.

Fixes fd67a7a1a22c ("ASoC: mediatek: mt8188: fix use-after-free in driver remove path")
[ sashal: Kept the branch's existing kzalloc(sizeof(*cl), GFP_KERNEL) in the context lines instead of upstream's kzalloc_obj(*cl), since that helper isn't available here. ]
---
 sound/soc/mediatek/mt8188/mt8188-audsys-clk.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
sound/soc/mediatek/mt8188/mt8188-audsys-clk.c +9 -3
index 40d2ab0a7677b..4d0d65e217bcf 100644
@@ -170,7 +170,7 @@ int mt8188_audsys_clk_register(struct mtk_base_afe *afe)
 	struct mt8188_afe_private *afe_priv = afe->platform_priv;
 	struct clk *clk;
 	struct clk_lookup *cl;
-	int i;
+	int i, ret;
 
 	afe_priv->lookup = devm_kcalloc(afe->dev, CLK_AUD_NR_CLK,
 					sizeof(*afe_priv->lookup),
@@ -179,6 +179,10 @@ int mt8188_audsys_clk_register(struct mtk_base_afe *afe)
 	if (!afe_priv->lookup)
 		return -ENOMEM;
 
+	ret = devm_add_action_or_reset(afe->dev, mt8188_audsys_clk_unregister, afe);
+	if (ret)
+		return ret;
+
 	for (i = 0; i < ARRAY_SIZE(aud_clks); i++) {
 		const struct afe_gate *gate = &aud_clks[i];
 
@@ -194,8 +198,10 @@ int mt8188_audsys_clk_register(struct mtk_base_afe *afe)
 
 		/* add clk_lookup for devm_clk_get(SND_SOC_DAPM_CLOCK_SUPPLY) */
 		cl = kzalloc(sizeof(*cl), GFP_KERNEL);
-		if (!cl)
+		if (!cl) {
+			clk_unregister_gate(clk);
 			return -ENOMEM;
+		}
 
 		cl->clk = clk;
 		cl->con_id = gate->name;
@@ -206,5 +212,5 @@ int mt8188_audsys_clk_register(struct mtk_base_afe *afe)
 		afe_priv->lookup[i] = cl;
 	}
 
-	return devm_add_action_or_reset(afe->dev, mt8188_audsys_clk_unregister, afe);
+	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#536 lore raw

PATCH 535/990 bpf, x86: Fix timed may_goto with private stack

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit bb83425b3cdcb7bb3c629598a4d5efad9cc80733 ]

arch_bpf_timed_may_goto() computes the address of count and timestamp as rbp + offset. When the prog uses private stack the JIT maps r10 to r9 and nothing is reserved under rbp, so bpf_check_timed_may_goto() reads and writes the timestamp in the kernel stack, where arch_bpf_timed_may_goto() has just saved r0-r5 or further down. The following loop in fentry prog with r0-r5 set to zero:

1: may_goto +2

     r6 += 1
     goto 1b

leaves r3 with ktime in it when the prog has 64 bytes of stack and ends after 65535 iterations when it has 128.

Add the frame pointer to the offset in the JIT, where rbp vs r9 is known, and pass the pointer in AX.

arm64 and powerpc JITs keep the address of private stack in BPF_REG_FP and are not affected.

Fixes 2fb761823ead ("bpf, x86: Add x86 JIT support for timed may_goto")
[ sashal: Dropped the absent kfunc-argument block from the hunk's context, so the new timed may_goto add-frame-pointer code is inserted right after the !imm32 check. ]
---
 arch/x86/net/bpf_jit_comp.c       | 12 ++++++++++++
 arch/x86/net/bpf_timed_may_goto.S | 10 ++--------
 2 files changed, 14 insertions(+), 8 deletions(-)
arch/x86/net/bpf_jit_comp.c +12 -0
index 39cf6974e11e1..86f50102f8b7d 100644
@@ -2421,6 +2421,18 @@ st:			if (is_imm8(insn->off))
 			}
 			if (!imm32)
 				return -EINVAL;
+			if (func == (u8 *)arch_bpf_timed_may_goto) {
+				u32 fp = priv_frame_ptr ? X86_REG_R9 : BPF_REG_FP;
+
+				/*
+				 * AX has the offset of count and timestamp
+				 * in the stack. Turn it into a pointer.
+				 * add r10, rbp or add r10, r9
+				 */
+				maybe_emit_mod(&prog, BPF_REG_AX, fp, true);
+				EMIT2(0x01, add_2reg(0xC0, BPF_REG_AX, fp));
+				ip += 3;
+			}
 			if (priv_frame_ptr) {
 				push_r9(&prog);
 				ip += 2;
arch/x86/net/bpf_timed_may_goto.S +2 -8
index 54c690cae1908..6c6e03f725a30 100644
@@ -11,12 +11,6 @@
 SYM_FUNC_START(arch_bpf_timed_may_goto)
 	ANNOTATE_NOENDBR
 
-	/*
-	 * r10 passes us stack depth, load the pointer to count and timestamp
-	 * into r10 by adding it to BPF frame pointer.
-	 */
-	leaq (%rbp, %r10, 1), %r10
-
 	/* Setup frame. */
 	pushq %rbp
 	movq %rsp, %rbp
@@ -30,8 +24,8 @@ SYM_FUNC_START(arch_bpf_timed_may_goto)
 	pushq %r8
 
 	/*
-	 * r10 has the pointer to count and timestamp, pass it as first
-	 * argument.
+	 * r10 has the pointer to count and timestamp. JIT added the frame
+	 * pointer to the offset. Pass it as first argument.
 	 */
 	movq %r10, %rdi
 
Signature · 1 line
2.53.0
author maintainer
#537 lore raw

PATCH 536/990 bpf: Adjust pc-relative insn copied into its own patch

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit 67a3b916a7ae7c1a6bed08555417d444de6f5838 ]

bpf_do_misc_fixups() inits may_goto count by patching the first insn of a subprog with [ST, ST, first insn]. bpf_convert_ctx_accesses() patches insn that needs a barrier with [nospec, insn]. bpf_adj_branches() doesn't adjust insns inside the patch, so when the copy is a call, ld_imm64 of a func or a jump that points backward its target is off by the number of insns in front of it:

  static int A(void)  { return 1; }
  static int A2(void) { return 2; }
  static int B(void)
  {
          int i, ret = A();
          for (i = 0; i < 10 && can_loop; i++)
                  ...
          return ret;

}

When A is placed in front of B and may_goto is timed 'call A' becomes call of A + 2. B returns 2 when A + 2 is the start of A2. Otherwise the prog is rejected with "verifier bug: No program to jit at insn".

Add bpf_adj_moved_insn() and use it for both copies.

Fixes 011832b97b31 ("bpf: Introduce may_goto instruction")
Fixes d6f1c85f2253 ("bpf: Fall back to nospec for Spectre v1")
[ sashal: Applied the changes to kernel/bpf/verifier.c instead of fixups.c, using the local function names convert_ctx_accesses() and do_misc_fixups() in place of the bpf_-prefixed upstream ones. ]
---
 kernel/bpf/verifier.c | 55 +++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 53 insertions(+), 2 deletions(-)
kernel/bpf/verifier.c +53 -2
index 8ac91e5ced84b..13864488b5a07 100644
@@ -21471,6 +21471,44 @@ static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 of
 	return new_prog;
 }
 
+/*
+ * insn was moved down by delta insns inside its own patch. Operands relative
+ * to the pc that point in front of the old position did not move with it.
+ */
+static int bpf_adj_moved_insn(struct bpf_insn *insn, u32 delta)
+{
+	u8 class = BPF_CLASS(insn->code), op = BPF_OP(insn->code);
+	s64 off = insn->imm, off_min = S32_MIN;
+	bool is_imm = true;
+
+	if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) {
+		/* subprog that started at the old position starts with the patch */
+		if (off >= 0)
+			return 0;
+	} else if ((class == BPF_JMP || class == BPF_JMP32) &&
+		   op != BPF_CALL && op != BPF_EXIT) {
+		if (insn->code != (BPF_JMP32 | BPF_JA)) {
+			off = insn->off;
+			off_min = S16_MIN;
+			is_imm = false;
+		}
+		/* jump to itself stays */
+		if (off >= -1)
+			return 0;
+	} else {
+		return 0;
+	}
+
+	off -= delta;
+	if (off < off_min)
+		return -ERANGE;
+	if (is_imm)
+		insn->imm = off;
+	else
+		insn->off = off;
+	return 0;
+}
+
 /*
  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
  * jump offset by 'delta'.
@@ -21962,7 +22000,13 @@ static int convert_ctx_accesses(struct bpf_verifier_env *env)
 			struct bpf_insn *patch = insn_buf;
 
 			*patch++ = BPF_ST_NOSPEC();
-			*patch++ = *insn;
+			*patch = *insn;
+			ret = bpf_adj_moved_insn(patch++, 1);
+			if (ret) {
+				verbose(env, "insn %d cannot be patched due to 16-bit range\n",
+					env->insn_aux_data[i + delta].orig_idx);
+				return ret;
+			}
 			cnt = patch - insn_buf;
 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
 			if (!new_prog)
@@ -23576,7 +23620,14 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
 						     BPF_MAX_LOOPS);
 		}
 		/* Copy first actual insn to preserve it */
-		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
+		insn_buf[cnt] = env->prog->insnsi[subprog_start];
+		ret = bpf_adj_moved_insn(&insn_buf[cnt], cnt);
+		if (ret) {
+			verbose(env, "insn %d cannot be patched due to 16-bit range\n",
+				env->insn_aux_data[subprog_start].orig_idx);
+			return ret;
+		}
+		cnt++;
 
 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
 		if (!new_prog)
Signature · 1 line
2.53.0
author maintainer
#538 lore raw

PATCH 537/990 bpf: Fix overflow of jump offset in may_goto expansion

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit 8a12a00f6c5dba70a6d908fe27a3c980d42b9515 ]

may_goto is expanded into 'if AX == 0 goto off + 5' when it's timed, off + 2 when it's not and off - 1 when it jumps backward. The sum is stored into 16-bit off without a range check, so may_goto +32763 turns into:

if r12 == 0x0 goto pc-32768

and the prog jumps backward when may_goto expires.

Emit 'if AX != 0 goto +1; gotol' when the offset doesn't fit and compute the offset from the number of insns in the expansion. JITs that don't support gotol will reject such prog.

Fixes 011832b97b31 ("bpf: Introduce may_goto instruction")
Fixes e723608bf428 ("bpf: Add verifier support for timed may_goto")
[ sashal: Ported the may_goto overflow fix into verifier.c, since this tree has no fixups.c, and used the older do_misc_fixups() and is_may_goto_insn() names. ]
---
 kernel/bpf/verifier.c | 68 ++++++++++++++++++++++++++++---------------
 1 file changed, 44 insertions(+), 24 deletions(-)
kernel/bpf/verifier.c +44 -24
index 13864488b5a07..407526349ccfa 100644
@@ -22735,6 +22735,30 @@ static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *pat
 	return 0;
 }
 
+/*
+ * Expand may_goto: load the count from the stack, jump to the target of
+ * may_goto when it is zero, then the tail that updates the count.
+ * Use gotol when the target is too far for 16-bit offset of a conditional jump.
+ */
+static int may_goto_expand(struct bpf_insn *insn_buf, int off, int stack_off,
+			   const struct bpf_insn *tail, int tail_cnt)
+{
+	int cnt = 0;
+
+	/* Forward jump has to step over the tail */
+	off = off >= 0 ? off + tail_cnt : off - 1;
+
+	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
+	if (off == (s16)off) {
+		insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, off);
+	} else {
+		insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 1);
+		insn_buf[cnt++] = BPF_JMP32_A(off >= 0 ? off : off - 1);
+	}
+	memcpy(insn_buf + cnt, tail, tail_cnt * sizeof(*tail));
+	return cnt + tail_cnt;
+}
+
 /* Do various post-verification rewrites in a single program pass.
  * These rewrites simplify JIT and interpreter implementations.
  */
@@ -23015,6 +23039,18 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
 
 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
 			int stack_off_cnt = -stack_depth - 16;
+			/*
+			 * AX is used as an argument to pass in stack_off_cnt
+			 * (to add to r10/fp), and also as the return value of
+			 * the call to arch_bpf_timed_may_goto.
+			 */
+			struct bpf_insn tail[] = {
+				BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1),
+				BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2),
+				BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt),
+				BPF_EMIT_CALL(arch_bpf_timed_may_goto),
+				BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt),
+			};
 
 			/*
 			 * Two 8 byte slots, depth-16 stores the count, and
@@ -23031,22 +23067,8 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
 			 * after subtraction, rinse and repeat.
 			 */
 			stack_depth_extra = 16;
-			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
-			if (insn->off >= 0)
-				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
-			else
-				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
-			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
-			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
-			/*
-			 * AX is used as an argument to pass in stack_off_cnt
-			 * (to add to r10/fp), and also as the return value of
-			 * the call to arch_bpf_timed_may_goto.
-			 */
-			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
-			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
-			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
-			cnt = 7;
+			cnt = may_goto_expand(insn_buf, insn->off, stack_off_cnt,
+					      tail, ARRAY_SIZE(tail));
 
 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
 			if (!new_prog)
@@ -23058,16 +23080,14 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
 			goto next_insn;
 		} else if (is_may_goto_insn(insn)) {
 			int stack_off = -stack_depth - 8;
+			struct bpf_insn tail[] = {
+				BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1),
+				BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off),
+			};
 
 			stack_depth_extra = 8;
-			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
-			if (insn->off >= 0)
-				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
-			else
-				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
-			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
-			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
-			cnt = 4;
+			cnt = may_goto_expand(insn_buf, insn->off, stack_off,
+					      tail, ARRAY_SIZE(tail));
 
 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
 			if (!new_prog)
Signature · 1 line
2.53.0
author maintainer
#539 lore raw

PATCH 538/990 bpf: Dont converge a loop on an iterator that was created anew

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit 6f3ee3516305da3043f1787e3890381a54151730 ]

When the verifier reaches bpf_iter_*_next() in a state that is equal to a state that is still being explored it concludes that the loop converged, since an active iterator will be drained eventually. states_equal() matches ids through idmap, so the same is concluded for an iterator that was destroyed and created again since the old state:

  bpf_iter_num_new(&it, 0, 10);
  loop:
          if (bpf_ktime_get_ns())
                  goto remake;
  next:
          if (!bpf_iter_num_next(&it))
                  goto out;
          goto loop;
  remake:
          bpf_iter_num_destroy(&it);
          bpf_iter_num_new(&it, 0, 10);
          goto next;

Such prog is accepted when the call of bpf_iter_num_next() is the first prune point after bpf_iter_num_new() and it never returns. Otherwise it's rejected with "infinite loop detected".

Require the iterator to have the same id in both states.

Fixes 06accc8779c1 ("bpf: add support for open-coded iterator loops")
[ sashal: Compares ref_obj_id instead of id for iterator identity, since iterators have no id here, and applies the check in is_state_visited() in the old verifier layout with old_frame added to the existing declaration. ]
---
 kernel/bpf/verifier.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
kernel/bpf/verifier.c +12 -2
index 407526349ccfa..2c1afef34070d 100644
@@ -20072,8 +20072,9 @@ static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
 			 */
 			if (is_iter_next_insn(env, insn_idx)) {
 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
-					struct bpf_func_state *cur_frame;
+					struct bpf_func_state *cur_frame, *old_frame;
 					struct bpf_reg_state *iter_state, *iter_reg;
+					struct bpf_reg_state *old_iter;
 					int spi;
 
 					cur_frame = cur->frame[cur->curframe];
@@ -20087,7 +20088,16 @@ static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
 					 */
 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
-					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
+					old_frame = sl->state.frame[iter_reg->frameno];
+					old_iter = &old_frame->stack[spi].spilled_ptr;
+					/*
+					 * states_equal() matches ids through idmap.
+					 * The loop converged only if it's the same
+					 * iterator. The one that was destroyed and
+					 * created again starts from the beginning.
+					 */
+					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE &&
+					    iter_state->ref_obj_id == old_iter->ref_obj_id) {
 						loop = true;
 						goto hit;
 					}
Signature · 1 line
2.53.0
author maintainer
#540 lore raw

PATCH 539/990 bpf: Fix uninit read for non-fetch atomics on partially spilled slots

In reply to Greg Kroah-Hartman

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

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

From: Hao Sun <[email protected]>

[ Upstream commit 5a84b4424db8ae07f0ac682ab031c37a91dce50b ]

check_stack_read_fixed_off() skips partial spill checks for non-fetch atomics; the following prog can be loaded:

0: (b7) r1 = 1                        ; R1=1
1: (63) *(u32 *)(r10 -8) = r1         ; R1=1 R10=fp0 fp-8=????1
2: (db) lock *(u64 *)(r10 -8) += r1   ; R1=1 R10=fp0 fp-8=mmmmmmmm
3: (79) r0 = *(u64 *)(r10 -8)         ; R0=scalar() R10=fp0 fp-8=mmmmmmmm
4: (77) r0 >>= 32                     ; R0=scalar(smin=0,smax=umax=0xffffffff,var_off=(0x0; 0xffffffff))

5: (95) exit

When test run:

	retval=4294967295

Note fp-8 is ????1 at #1, yet it becomes fp-8=mmmmmmmm after the non-fetching atomic add at #2; hence the high 32 bits are leaked.

Fix by applying the partial load check; after the patch, the prog is rejected:

Verification failed: Memory Safety: Uninitialized stack read

Reason:
This rejected read uses 8 bytes at stack offset -8, but byte 4 in that range is uninitialized on this path. Programs loaded with CAP_PERFMON can be allowed to read uninitialized stack bytes, but this program is being rejected without that allowance.

At:
...

      0 | (b7) r1 = 1
      1 | (63) *(u32 *)(r10 -8) = r1
  >>> 2 | (db) lock *(u64 *)(r10 -8) += r1
      3 | (79) r0 = *(u64 *)(r10 -8)
      4 | (77) r0 >>= 32

This affects CAP_BPF only.

Fixes 354e8f1970f8 ("bpf: Support <8-byte scalar spill and refill")
[ sashal: Context lines differ because the target tree has an older subreg_def comment block where upstream has a get_reg_width() check; the patch was applied by hand with identical added and removed lines. ]
---
 kernel/bpf/verifier.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
kernel/bpf/verifier.c +6 -3
index 2c1afef34070d..c8a72c96e227a 100644
@@ -5508,11 +5508,11 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
 				return -EACCES;
 			}
 
-			if (dst_regno < 0)
-				return 0;
-
 			if (size <= spill_size &&
 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
+				if (dst_regno < 0)
+					return 0;
+
 				/* The earlier check_reg_arg() has decided the
 				 * subreg_def for this insn.  Save it first.
 				 */
@@ -5548,6 +5548,9 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
 					return -EACCES;
 				}
 
+				if (dst_regno < 0)
+					return 0;
+
 				if (spill_cnt == size &&
 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
Signature · 1 line
2.53.0
author maintainer
#541 lore raw

PATCH 540/990 bpf: Fix uninit read for helper mem args on partially spilled slots

In reply to Greg Kroah-Hartman

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

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

From: Hao Sun <[email protected]>

[ Upstream commit b3861495d2b2f7459cddf49e63fa0758ba430583 ]

check_stack_range_initialized() takes the spilled register path when bpf_is_spilled_reg(ss) holds, which, however, only looks at the last byte of the slot. Hence, a partially spilled scalar (on the lower part) bypasses the check and the following loads:

0: (b7) r1 = 1                        ; R1=1
1: (63) *(u32 *)(r10 -8) = r1         ; R1=1 R10=fp0 fp-8=????1
2: (18) r1 = 0x0                      ; R1=map_ptr(map=rb,ks=0,vs=0)
4: (bf) r2 = r10                      ; R2=fp0 R10=fp0
5: (07) r2 += -8                      ; R2=fp-8
6: (b7) r3 = 8                        ; R3=8
7: (b7) r4 = 0                        ; R4=0

8: (85) call bpf_ringbuf_output#130
...

When executed, it dumps the uninit four bytes:

	RINGBUF: 01 00 00 00 ff ff ff ff

This is the same root cause as the non-fetch atomic case fixed in commit 5a84b4424db8 ("bpf: Fix uninit read for non-fetch atomics on partially spilled slots").

Fix by only taking the spilled register path for the bytes marked STACK_SPILL, so the rest of the slot goes through the usual checks.

Fixes 354e8f1970f8 ("bpf: Support <8-byte scalar spill and refill")

[ sashal: Context lines differ because the target tree still uses is_spilled_reg() on state->stack[spi] where upstream uses bpf_is_spilled_reg(ss); the patch was applied by hand with identical added and removed lines. ]

---
 kernel/bpf/verifier.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
kernel/bpf/verifier.c +6 -1
index c8a72c96e227a..23c1401a97bdf 100644
@@ -8318,7 +8318,12 @@ static int check_stack_range_initialized(
 			goto mark;
 		}
 
-		if (is_spilled_reg(&state->stack[spi]) &&
+		/*
+		 * Only the bytes marked STACK_SPILL hold the spilled register.
+		 * The rest of a narrowly spilled slot keeps its previous type
+		 * and must be initialized on its own.
+		 */
+		if (*stype == STACK_SPILL &&
 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
 		     env->allow_ptr_leaks)) {
 			if (clobber) {
Signature · 1 line
2.53.0
author maintainer
#542 lore raw

PATCH 541/990 fuse: zero the correct range on a short read reply

In reply to Greg Kroah-Hartman

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

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

From: Joanne Koong <[email protected]>

[ Upstream commit d0a079b5b94bf5e10f1c00bd092eda0333782037 ]

When a read reply is shorter than the requested range, fuse_copy_folio() zeroes everything in the folio outside the copied bytes. However, for folios with block sizes smaller than the folio size, this can clear blocks outside the requested range which are uptodate, or dirty and have not yet been written back.

Move the zeroing logic into fuse_copy_folios(), since descs[i].length needs to be used, and clear only the tail of the requested range that the server did not send.

The range is also no longer cleared upfront in the non cs->skip_folio_copy case. This is fine since a failed copy leaves those blocks non-uptodate, so the uncopied bytes are never visible. This also matches the pre-existing behavior in the non-short-read case (a failed copy doesn't zero out the range in the folio). This lets the zeroing logic stay the same regardless of whether the folio copy is skipped or not.

Fixes a4c9ab1d4975 ("fuse: use iomap for buffered writes")
[ sashal: Moved zeroing into fuse_copy_folios() in dev.c, kept fuse_copy_folio() static so the dev.h hunk is dropped, and omitted the skip_folio_copy/folio_zero_segments logic that isn't present here. ]
---
 fs/fuse/dev.c    | 32 ++++++++++++++++++++------------
 fs/fuse/notify.c |  2 +-
 2 files changed, 21 insertions(+), 13 deletions(-)
fs/fuse/dev.c +20 -12
index 0f9ef3ca9824f..56bc4381c2874 100644
@@ -1129,17 +1129,10 @@ static int fuse_ref_folio(struct fuse_copy_state *cs, struct folio *folio,
  * done atomically
  */
 static int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop,
-			   unsigned offset, unsigned count, int zeroing)
+			   unsigned offset, unsigned count)
 {
 	int err;
 	struct folio *folio = *foliop;
-	size_t size;
-
-	if (folio) {
-		size = folio_size(folio);
-		if (zeroing && count < size)
-			folio_zero_range(folio, 0, size);
-	}
 
 	while (count) {
 		if (cs->write && cs->pipebufs && folio) {
@@ -1156,7 +1149,7 @@ static int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop,
 			}
 		} else if (!cs->len) {
 			if (cs->move_folios && folio &&
-			    offset == 0 && count == size) {
+			    offset == 0 && count == folio_size(folio)) {
 				err = fuse_try_move_folio(cs, foliop);
 				if (err <= 0)
 					return err;
@@ -1197,10 +1190,25 @@ static int fuse_copy_folios(struct fuse_copy_state *cs, unsigned nbytes,
 
 	for (i = 0; i < ap->num_folios && (nbytes || zeroing); i++) {
 		int err;
+		struct folio *folio = ap->folios[i];
 		unsigned int offset = ap->descs[i].offset;
-		unsigned int count = min(nbytes, ap->descs[i].length);
+		unsigned int length = ap->descs[i].length;
+		unsigned int count = min(nbytes, length);
+
+		/*
+		 * The reply may be shorter than what was asked for. The full
+		 * descs[i].length is reported as read, so the tail bytes the
+		 * server did not send are about to be marked uptodate and need
+		 * to be zeroed.
+		 *
+		 * Only [offset, offset + length) can be touched since the
+		 * rest of the folio can hold blocks that are already uptodate
+		 * or dirty, and clearing those would lose data.
+		 */
+		if (folio && zeroing && count < length)
+			folio_zero_range(folio, offset + count, length - count);
 
-		err = fuse_copy_folio(cs, &ap->folios[i], offset, count, zeroing);
+		err = fuse_copy_folio(cs, &ap->folios[i], offset, count);
 		if (err)
 			return err;
 
@@ -1835,7 +1843,7 @@ static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
 		nr_bytes = min_t(unsigned, num, folio_size(folio) - folio_offset);
 		nr_pages = (offset + nr_bytes + PAGE_SIZE - 1) >> PAGE_SHIFT;
 
-		err = fuse_copy_folio(cs, &folio, folio_offset, nr_bytes, 0);
+		err = fuse_copy_folio(cs, &folio, folio_offset, nr_bytes);
 		if (!folio_test_uptodate(folio) && !err && offset == 0 &&
 		    (nr_bytes == folio_size(folio) || file_size == end)) {
 			folio_zero_segment(folio, nr_bytes, folio_size(folio));
fs/fuse/notify.c +1 -1
index 7cd63502e124b..f21ba27f0f82e 100644
@@ -184,7 +184,7 @@ static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
 		folio_offset = offset_in_folio(folio, pos);
 		nr_bytes = min(num, folio_size(folio) - folio_offset);
 
-		err = fuse_copy_folio(cs, &folio, folio_offset, nr_bytes, 0);
+		err = fuse_copy_folio(cs, &folio, folio_offset, nr_bytes);
 		if (!folio_test_uptodate(folio) && !err && folio_offset == 0 &&
 		    (nr_bytes == folio_size(folio) || file_size == end)) {
 			folio_zero_segment(folio, nr_bytes, folio_size(folio));
Signature · 1 line
2.53.0
author maintainer
#543 lore raw

PATCH 542/990 platform/x86/intel/pmt: complete pcidev to device update

In reply to Greg Kroah-Hartman

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

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

From: Michael J. Ruhl <[email protected]>

[ Upstream commit b86e5062cb881f6e5c1ddb8913c1357a9508f6db ]

The update that moved struct pci_dev usage to struct device is incomplete. Only telemetry endpoints are covered.

Other PMT features (crashlog) are now blocked from using the callback mechanism.

Change struct intel_pmt_entry pci_dev member to device.

Update callback usage to use the intel_pmt_entry rather than the telemetry endpoint.

Fixes 353042d54d82 ("platform/x86/intel/vsec: Switch exported helpers from pci_dev to device")
[ sashal: Removed the entry->pcidev = pci_dev; line from the single intel_pmt_populate_entry() here, since this tree lacks upstream's pmt_resolve_access_pci() split, and added entry->dev there. ]
---
 drivers/platform/x86/intel/pmt/class.c     | 4 ++--
 drivers/platform/x86/intel/pmt/class.h     | 3 +--
 drivers/platform/x86/intel/pmt/discovery.c | 2 +-
 3 files changed, 4 insertions(+), 5 deletions(-)
drivers/platform/x86/intel/pmt/class.c +2 -2
index 9ec843617e3c9..ebb5071334e5c 100644
@@ -99,7 +99,7 @@ intel_pmt_read(struct file *filp, struct kobject *kobj,
 	if (count > entry->size - off)
 		count = entry->size - off;
 
-	count = pmt_telem_read_mmio(entry->ep->dev, entry->cb, entry->header.guid, buf,
+	count = pmt_telem_read_mmio(entry->dev, entry->cb, entry->header.guid, buf,
 				    entry->base, off, count);
 
 	return count;
@@ -283,10 +283,10 @@ static int intel_pmt_populate_entry(struct intel_pmt_entry *entry,
 		return -EINVAL;
 	}
 
-	entry->pcidev = pci_dev;
 	entry->guid = header->guid;
 	entry->size = header->size;
 	entry->cb = ivdev->priv_data;
+	entry->dev = ivdev->dev;
 
 	return 0;
 }
drivers/platform/x86/intel/pmt/class.h +1 -2
index 1ae56a5baad23..1d66681d14722 100644
@@ -20,7 +20,6 @@
 #define GET_ADDRESS(v)		((v) & GENMASK(31, 3))
 
 struct device;
-struct pci_dev;
 extern struct class intel_pmt_class;
 
 struct telem_endpoint {
@@ -41,7 +40,7 @@ struct intel_pmt_header {
 
 struct intel_pmt_entry {
 	struct telem_endpoint	*ep;
-	struct pci_dev		*pcidev;
+	struct device		*dev;
 	struct intel_pmt_header	header;
 	struct bin_attribute	pmt_bin_attr;
 	const struct attribute_group *attr_grp;
drivers/platform/x86/intel/pmt/discovery.c +1 -1
index c482368bfaaef..f4203d240f542 100644
@@ -609,7 +609,7 @@ void intel_pmt_get_features(struct intel_pmt_entry *entry)
 
 	mutex_lock(&feature_list_lock);
 	list_for_each_entry(feature, &pmt_feature_list, list) {
-		if (feature->priv->parent != entry->ep->dev)
+		if (feature->priv->parent != entry->dev)
 			continue;
 
 		pmt_get_features(entry, feature);
Signature · 1 line
2.53.0
author maintainer
#544 lore raw

PATCH 543/990 perf machine: Add session back pointer to fix out of bounds read

In reply to Greg Kroah-Hartman

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

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

From: Ian Rogers <[email protected]>

[ Upstream commit d227b45fc162ce9134bb96f33f71e6952ec36ea5 ]

thread__e_machine_endian() decides whether a thread is live, and so whether to read /proc/pid/exe rather than fall back to the perf.data environment, by recovering the session from the machine:

	session = container_of(machine->machines, struct perf_session,
			       machines);
	is_live = !session->data;

That only holds when the struct machines is the one embedded in a struct perf_session. It is not the only one. aslr_tool keeps its own in struct aslr_tool, and hists_cumulate, hists_filter, hists_link, hists_output and thread-maps-share each put one on the stack. For those the container_of subtracts offsetof(struct perf_session, machines) from an address that was never inside a session, and the following load of session->data reads outside the object, which is what ASan reports.

Replace the derivation with an explicit link. machines__init() takes the owning session, or NULL when the machines is standalone, and thread__e_machine_endian() reads it back through machines__session().

A NULL session is treated as live. The tests use synthetic pids that have no /proc entry, so the read fails there and the e_machine falls back to EM_HOST as before, rather than being decided by whatever the out of bounds read happened to return. perf inject registers its session with the aslr tool once the session exists, before any event is processed, so that tool keeps reporting file based threads as not live.

Fixes 70351029b556 ("perf thread: Add support for reading the e_machine type for a thread")
Assisted-by Antigravity:gemini-3.1-pro
[ sashal: adapted to machines__init() returning void and dropped the ASLR hunks since that code is absent, so the test callers pass NULL as a plain statement. ]
---
 tools/perf/tests/hists_cumulate.c    |  2 +-
 tools/perf/tests/hists_filter.c      |  2 +-
 tools/perf/tests/hists_link.c        |  2 +-
 tools/perf/tests/hists_output.c      |  2 +-
 tools/perf/tests/thread-maps-share.c |  2 +-
 tools/perf/util/machine.c            |  3 ++-
 tools/perf/util/machine.h            | 10 +++++++++-
 tools/perf/util/session.c            |  2 +-
 tools/perf/util/thread.c             |  8 +++-----
 9 files changed, 20 insertions(+), 13 deletions(-)
tools/perf/tests/hists_cumulate.c +1 -1
index 3eb9ef8d7ec63..bdf4ce82612dd 100644
@@ -724,7 +724,7 @@ static int test__hists_cumulate(struct test_suite *test __maybe_unused, int subt
 		goto out;
 	err = TEST_FAIL;
 
-	machines__init(&machines);
+	machines__init(&machines, /*session=*/NULL);
 
 	/* setup threads/dso/map/symbols also */
 	machine = setup_fake_machine(&machines);
tools/perf/tests/hists_filter.c +1 -1
index 1cebd20cc91c0..4a1d45ecc03ff 100644
@@ -131,7 +131,7 @@ static int test__hists_filter(struct test_suite *test __maybe_unused, int subtes
 		goto out;
 	err = TEST_FAIL;
 
-	machines__init(&machines);
+	machines__init(&machines, /*session=*/NULL);
 
 	/* setup threads/dso/map/symbols also */
 	machine = setup_fake_machine(&machines);
tools/perf/tests/hists_link.c +1 -1
index 996f5f0b3bd17..0af2ba1ad1aa5 100644
@@ -303,7 +303,7 @@ static int test__hists_link(struct test_suite *test __maybe_unused, int subtest
 		goto out;
 
 	err = TEST_FAIL;
-	machines__init(&machines);
+	machines__init(&machines, /*session=*/NULL);
 
 	/* setup threads/dso/map/symbols also */
 	machine = setup_fake_machine(&machines);
tools/perf/tests/hists_output.c +1 -1
index ee5ec8bda60e5..a80263ab1d346 100644
@@ -611,7 +611,7 @@ static int test__hists_output(struct test_suite *test __maybe_unused, int subtes
 		goto out;
 	err = TEST_FAIL;
 
-	machines__init(&machines);
+	machines__init(&machines, /*session=*/NULL);
 
 	/* setup threads/dso/map/symbols also */
 	machine = setup_fake_machine(&machines);
tools/perf/tests/thread-maps-share.c +1 -1
index e9ecd30a5c058..cea1f92b5302c 100644
@@ -27,7 +27,7 @@ static int test__thread_maps_share(struct test_suite *test __maybe_unused, int s
 	 * other  group (pid: 4, tids: 4, 5)
 	*/
 
-	machines__init(&machines);
+	machines__init(&machines, /*session=*/NULL);
 	machine = &machines.host;
 
 	/* create process with 4 threads */
tools/perf/util/machine.c +2 -1
index 091022e9c867f..0fcbd56746f24 100644
@@ -229,9 +229,10 @@ void machine__delete(struct machine *machine)
 	}
 }
 
-void machines__init(struct machines *machines)
+void machines__init(struct machines *machines, struct perf_session *session)
 {
 	machine__init(&machines->host, "", HOST_KERNEL_ID);
+	machines->session = session;
 	machines->host.machines = machines;
 	machines->guests = RB_ROOT_CACHED;
 }
tools/perf/util/machine.h +9 -1
index 22a42c5825fab..049bbbdfa20d2 100644
@@ -15,6 +15,7 @@ struct dso;
 struct dso_id;
 struct evsel;
 struct perf_sample;
+struct perf_session;
 struct symbol;
 struct target;
 struct thread;
@@ -148,13 +149,20 @@ int machine__process_event(struct machine *machine, union perf_event *event,
 typedef void (*machine__process_t)(struct machine *machine, void *data);
 
 struct machines {
+	/** @session: back link to owning session if there is one. */
+	struct perf_session *session;
 	struct machine host;
 	struct rb_root_cached guests;
 };
 
-void machines__init(struct machines *machines);
+void machines__init(struct machines *machines, struct perf_session *session);
 void machines__exit(struct machines *machines);
 
+static inline struct perf_session *machines__session(struct machines *machines)
+{
+	return machines->session;
+}
+
 void machines__process_guests(struct machines *machines,
 			      machine__process_t process, void *data);
 
tools/perf/util/session.c +1 -1
index 0eee9d2f59d9a..f737ddb377553 100644
@@ -152,7 +152,7 @@ struct perf_session *__perf_session__new(struct perf_data *data,
 	session->decomp_data.zstd_decomp = &session->zstd_data;
 	session->active_decomp = &session->decomp_data;
 	INIT_LIST_HEAD(&session->auxtrace_index);
-	machines__init(&session->machines);
+	machines__init(&session->machines, session);
 	ordered_events__init(&session->ordered_events,
 			     ordered_events__deliver_event, NULL);
 
tools/perf/util/thread.c +3 -5
index bda001ccf571d..6e22f83ae1e1b 100644
@@ -513,12 +513,10 @@ uint16_t thread__e_machine(struct thread *thread, struct machine *machine)
 		bool is_live = machine->machines == NULL;
 
 		if (!is_live) {
-			/* Check if the session has a data file. */
-			struct perf_session *session = container_of(machine->machines,
-								    struct perf_session,
-								    machines);
+			/* Check if the session has a data file (assume no session is a test). */
+			struct perf_session *session = machines__session(machine->machines);
 
-			is_live = !session->data;
+			is_live = !session || !session->data;
 		}
 		/* Read from /proc/pid/exe if live. */
 		if (is_live)
Signature · 1 line
2.53.0
author maintainer
#545 lore raw

PATCH 544/990 arm64: dts: qcom: x1-asus-vivobook-s15: Mark the EC reset gpio as reserved

In reply to Greg Kroah-Hartman

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

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

From: Abel Vesa <[email protected]>

[ Upstream commit 94a0d3a2595821878de98d495e89691f694a2083 ]

GPIO 65 from TLMM is used by the embedded controller as its reset line.

On some devices, toggling the embedded controller reset line makes the device not power up at all, unless the battery is unplugged.

So reserve it in order to prevent Linux from requesting or reconfiguring it.

Fixes d0e2f8f62dff ("arm64: dts: qcom: Add device tree for ASUS Vivobook S 15")
[ sashal: Applied the one-line GPIO 65 reservation to the single-file Vivobook S 15 devicetree, since the upstream shared .dtsi file does not exist here. ]
---
 arch/arm64/boot/dts/qcom/x1e80100-asus-vivobook-s15.dts | 1 +
 1 file changed, 1 insertion(+)
arch/arm64/boot/dts/qcom/x1e80100-asus-vivobook-s15.dts +1 -0
index f2960953e608f..7abd519f38a4e 100644
@@ -742,6 +742,7 @@ &smb2360_1_eusb2_repeater {
 &tlmm {
 	gpio-reserved-ranges = <34 2>, /* Unused */
 			       <44 4>, /* SPI (TPM) */
+			       <65 1>, /* EC reset */
 			       <238 1>; /* UFS Reset */
 
 	edp_reg_en: edp-reg-en-state {
Signature · 1 line
2.53.0
author maintainer
#546 lore raw

PATCH 545/990 wifi: ath12k: fix skb leak on paddr mismatch in wifi7 mon RX pop

In reply to Greg Kroah-Hartman

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

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

From: Kang Yang <[email protected]>

[ Upstream commit 4dfe8e3ac731c3372b5c1f1f73b0676c301c3916 ]

When rxcb->paddr does not match the MSDU-list paddr reported by the link descriptor, ath12k_wifi7_dp_rx_mon_mpdu_pop() sets drop_mpdu = true and continues to the next MSDU. At that point the skb is still attached to the descriptor via desc_info->skb; the local msdu variable only holds a copy of that pointer. The continue skips the rest of the loop body, which would normally DMA-unmap the buffer, free the skb, clear desc_info->skb, and append the descriptor to used_list in the next_msdu block.

The descriptor therefore stays in_use with the skb attached forever. The skb is never DMA-unmapped, delivered, freed or replaced, and HW does not write into it either because the descriptor is no longer posted to any SRNG. The descriptor is also never returned to used_list, so ath12k_dp_rx_bufs_replenish() cannot allocate a fresh buffer for it and the RX refill ring gradually drains.

The skb is still reachable via dp->rxbaddr[][].skb and is reclaimed at teardown by ath12k_dp_cc_cleanup(), so this is not a kmemleak-style unreachable leak. Nevertheless, both the descriptor slot and the skb memory are wasted for the module lifetime, and under sustained mismatches monitor RX stalls.

Remove the continue so drop_mpdu remains true, execution reaches the DMA unmap and dev_kfree_skb_any() below, and the descriptor is returned to used_list via the next_msdu block for replenish.

Tested-on: WCN7850 hw2.0 PCI WLAN.HMT.1.1.c7-00108-QCAHMTSWPL_V1.0_V2.0_SILICONZ_UPSTREAM-3

Fixes 72bfbf19b7da ("wifi: ath12k: add support to reap and process mon dest ring")
[ sashal: Renamed the file path from the wifi7 split (wifi7/dp_mon.c, ath12k_wifi7_dp_rx_mon_mpdu_pop) to ath12k/dp_mon.c with ath12k_dp_rx_mon_mpdu_pop; the one-line continue removal itself is unchanged. ]
---
 drivers/net/wireless/ath/ath12k/dp_mon.c | 1 -
 1 file changed, 1 deletion(-)
drivers/net/wireless/ath/ath12k/dp_mon.c +0 -1
index 3752fa0eed30b..a7cb7ba62f2d4 100644
@@ -4173,7 +4173,6 @@ ath12k_dp_rx_mon_mpdu_pop(struct ath12k *ar, int mac_id,
 					   i, (unsigned long)rxcb->paddr,
 					   (unsigned long)msdu_list.paddr[i]);
 				drop_mpdu = true;
-				continue;
 			}
 			if (!rxcb->unmapped) {
 				dma_unmap_single(ar->ab->dev, rxcb->paddr,
Signature · 1 line
2.53.0
author maintainer
#547 lore raw

PATCH 546/990 wifi: ath12k: free pending MSDUs on duplicate mon link descriptor

In reply to Greg Kroah-Hartman

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

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

From: Kang Yang <[email protected]>

[ Upstream commit d8e8eac3fcffc114a79f7d07d7cb73cc16645381 ]

ath12k_wifi7_dp_rx_mon_mpdu_pop() aborts processing when a duplicate monitor link descriptor is detected.

Previous iterations may already have linked MSDUs onto *head_msdu and detached the corresponding RX buffers from their descriptors. Returning without completing or freeing the chain leaves those skbs orphaned, resulting in a memory leak.

kmemleak reports these skbs in field testing:
kmemleak_alloc()
__netdev_alloc_skb()
ath12k_dp_rx_bufs_replenish()
ath12k_wifi7_dp_rx_mon_dest_process()

Free the accumulated MSDU chain before returning and clear *head_msdu so callers observe a consistent state.

Tested-on: WCN7850 hw2.0 PCI WLAN.HMT.1.1.c7-00108-QCAHMTSWPL_V1.0_V2.0_SILICONZ_UPSTREAM-3

Fixes 72bfbf19b7da ("wifi: ath12k: add support to reap and process mon dest ring")
[ sashal: Applied to the pre-split monitor RX file with the function name ath12k_dp_rx_mon_mpdu_pop() instead of the wifi7 path and name; the two-line change itself is identical. ]
---
 drivers/net/wireless/ath/ath12k/dp_mon.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/net/wireless/ath/ath12k/dp_mon.c +2 -0
index a7cb7ba62f2d4..0e9b02f1140fc 100644
@@ -4130,6 +4130,8 @@ ath12k_dp_rx_mon_mpdu_pop(struct ath12k *ar, int mac_id,
 		if (pmon->mon_last_linkdesc_paddr == paddr) {
 			pmon->rx_mon_stats.dup_mon_linkdesc_cnt++;
 			spin_unlock_bh(&pmon->mon_lock);
+			kfree_skb_list(*head_msdu);
+			*head_msdu = NULL;
 			return rx_bufs_used;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#548 lore raw

PATCH 547/990 wifi: ath12k: fix stale tail_msdu pointer returned from mpdu_pop

In reply to Greg Kroah-Hartman

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

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

From: Kang Yang <[email protected]>

[ Upstream commit 1a10a558555072dba8510ded23a9174b2a00d079 ]

ath12k_wifi7_dp_rx_mon_mpdu_pop() assigns *tail_msdu from the loop cursor msdu at function exit. That cursor reflects the state of the last msdu_list entry processed, not the end of the accumulated MSDU
chain: on next_msdu paths (invalid skb, drop_mpdu, first-MSDU rx_desc invalid) it is set to NULL, and on the set_pktlen failure path it becomes a dangling pointer to a freed skb. When these occur on the final iteration, callers see head_msdu populated with a valid chain while tail_msdu is NULL or points to freed memory.

The chain end is already tracked by the local variable last, which is updated only after each MSDU has been validated and linked. Use it as the source for tail_msdu so head_msdu and tail_msdu are either both NULL or both point into the same live chain.

Tested-on: WCN7850 hw2.0 PCI WLAN.HMT.1.1.c7-00108-QCAHMTSWPL_V1.0_V2.0_SILICONZ_UPSTREAM-3

Fixes 72bfbf19b7da ("wifi: ath12k: add support to reap and process mon dest ring")
[ sashal: Applied the one-line change to the pre-split dp_mon.c, using the old function name, since the wifi7 split of ath12k does not exist here. ]
---
 drivers/net/wireless/ath/ath12k/dp_mon.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/wireless/ath/ath12k/dp_mon.c +1 -1
index 0e9b02f1140fc..a9ba30c330833 100644
@@ -4254,7 +4254,7 @@ ath12k_dp_rx_mon_mpdu_pop(struct ath12k *ar, int mac_id,
 	if (last)
 		last->next = NULL;
 
-	*tail_msdu = msdu;
+	*tail_msdu = last;
 
 	if (msdu_cnt == 0)
 		*npackets = 1;
Signature · 1 line
2.53.0
author maintainer
#549 lore raw

PATCH 548/990 wifi: ath12k: place dp_mon_mpdu on stack in mon dst reap loop

In reply to Greg Kroah-Hartman

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

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

From: Kang Yang <[email protected]>

[ Upstream commit 8b1d2f4c3805b9f1bddd5dc3bd241edd1f9ab2d9 ]

ath12k_wifi7_dp_rx_mon_dest_process() allocates a dp_mon_mpdu with kzalloc(GFP_ATOMIC) for each delivered MPDU. On allocation failure it breaks out of the reap loop without calling ath12k_hal_srng_dst_get_next_entry(), leaving the destination ring tail pointer parked on the current entry -- the same entry will be peek()ed on every subsequent NAPI schedule, stalling monitor RX until the mon_dest_ring_stuck_cnt recovery path resyncs the PPDU ID. The head_msdu chain accumulated for this iteration is also orphaned since the break bypasses both the delivery and the cleanup paths.

kmemleak reports these skbs in field testing:
kmemleak_alloc()
__netdev_alloc_skb()
ath12k_dp_rx_bufs_replenish()
ath12k_wifi7_dp_rx_mon_dest_process()

dp_mon_mpdu is used only within a single reap loop iteration and is passed synchronously to ath12k_wifi7_dp_mon_rx_deliver(); the callee does not retain the pointer. Place it on the stack instead of using kzalloc(GFP_ATOMIC). This eliminates the allocation failure path (and the ring stall it caused) and saves a kzalloc/kfree pair per delivered MPDU.

Tested-on: WCN7850 hw2.0 PCI WLAN.HMT.1.1.c7-00108-QCAHMTSWPL_V1.0_V2.0_SILICONZ_UPSTREAM-3

Fixes 72bfbf19b7da ("wifi: ath12k: add support to reap and process mon dest ring")
[ sashal: Replaced the kzalloc'd dp_mon_mpdu with a stack variable, adapted to the pre-wifi7-split file path and function names (ath12k_dp_mon_rx_deliver(ar, ...)). ]
---
 drivers/net/wireless/ath/ath12k/dp_mon.c | 19 ++++++++-----------
 1 file changed, 8 insertions(+), 11 deletions(-)
drivers/net/wireless/ath/ath12k/dp_mon.c +8 -11
index a9ba30c330833..cfd9ea83887aa 100644
@@ -4278,7 +4278,6 @@ static void ath12k_dp_rx_mon_dest_process(struct ath12k *ar, int mac_id,
 	struct ath12k_dp *dp = &ar->ab->dp;
 	struct ath12k_base *ab = ar->ab;
 	void *ring_entry, *mon_dst_srng;
-	struct dp_mon_mpdu *tmp_mpdu;
 	LIST_HEAD(rx_desc_used_list);
 	struct hal_srng *srng;
 
@@ -4341,18 +4340,16 @@ static void ath12k_dp_rx_mon_dest_process(struct ath12k *ar, int mac_id,
 		}
 
 		if (head_msdu && tail_msdu) {
-			tmp_mpdu = kzalloc(sizeof(*tmp_mpdu), GFP_ATOMIC);
-			if (!tmp_mpdu)
-				break;
-
-			tmp_mpdu->head = head_msdu;
-			tmp_mpdu->tail = tail_msdu;
-			tmp_mpdu->err_bitmap = pmon->err_bitmap;
-			tmp_mpdu->decap_format = pmon->decap_format;
-			ath12k_dp_mon_rx_deliver(ar, tmp_mpdu,
+			struct dp_mon_mpdu tmp_mpdu = {
+				.head = head_msdu,
+				.tail = tail_msdu,
+				.err_bitmap = pmon->err_bitmap,
+				.decap_format = pmon->decap_format,
+			};
+
+			ath12k_dp_mon_rx_deliver(ar, &tmp_mpdu,
 						 &pmon->mon_ppdu_info, napi);
 			rx_mon_stats->dest_mpdu_done++;
-			kfree(tmp_mpdu);
 		}
 
 		ring_entry = ath12k_hal_srng_dst_get_next_entry(ar->ab,
Signature · 1 line
2.53.0
author maintainer
#550 lore raw

PATCH 549/990 wifi: ath12k: fix skb leak on monitor PPDU ID wraparound

In reply to Greg Kroah-Hartman

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

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

From: Kang Yang <[email protected]>

[ Upstream commit 97b144b82e2388efef1f78269626d61de0480feb ]

ath12k_dp_mon_comp_ppduid() updates *ppdu_id and returns msdu_ppdu_id to indicate that a PPDU transition was detected.

When PPDU IDs wrap around, msdu_ppdu_id can be 0. In that case the function updates *ppdu_id but returns 0, causing ath12k_wifi7_dp_rx_mon_mpdu_pop() to interpret the result as "no PPDU update" and continue processing the MPDU.

The MSDUs are then linked into head_msdu while their RX descriptors have already been detached. Later, ath12k_wifi7_dp_rx_mon_dest_process() detects the PPDU mismatch and exits with the partially built MSDU chain, leaking the SKBs.

kmemleak reports the leak through:
kmemleak_alloc()
__netdev_alloc_skb()
ath12k_dp_rx_bufs_replenish()
ath12k_wifi7_dp_rx_mon_dest_process()

Fix this by returning a boolean value from ath12k_dp_mon_comp_ppduid() so the update notification is independent of the actual PPDU ID value.

Tested-on: WCN7850 hw2.0 PCI WLAN.HMT.1.1.c7-00108-QCAHMTSWPL_V1.0_V2.0_SILICONZ_UPSTREAM-3

Fixes 72bfbf19b7da ("wifi: ath12k: add support to reap and process mon dest ring")
[ sashal: Kept the function static in dp_mon.c and dropped the header hunk, since this tree has no prototype; only the return type changed to bool. ]
---
 drivers/net/wireless/ath/ath12k/dp_mon.c | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)
drivers/net/wireless/ath/ath12k/dp_mon.c +7 -8
index cfd9ea83887aa..2cb4e0bb0221a 100644
@@ -1860,24 +1860,23 @@ ath12k_dp_rx_mon_buf_done(struct ath12k_base *ab, struct hal_srng *srng,
 	return DP_MON_STATUS_REPLINISH;
 }
 
-static u32 ath12k_dp_mon_comp_ppduid(u32 msdu_ppdu_id, u32 *ppdu_id)
+static bool ath12k_dp_mon_comp_ppduid(u32 msdu_ppdu_id, u32 *ppdu_id)
 {
-	u32 ret = 0;
-
 	if ((*ppdu_id < msdu_ppdu_id) &&
 	    ((msdu_ppdu_id - *ppdu_id) < DP_NOT_PPDU_ID_WRAP_AROUND)) {
 		/* Hold on mon dest ring, and reap mon status ring. */
 		*ppdu_id = msdu_ppdu_id;
-		ret = msdu_ppdu_id;
-	} else if ((*ppdu_id > msdu_ppdu_id) &&
-		((*ppdu_id - msdu_ppdu_id) > DP_NOT_PPDU_ID_WRAP_AROUND)) {
+		return true;
+	}
+	if ((*ppdu_id > msdu_ppdu_id) &&
+	    ((*ppdu_id - msdu_ppdu_id) > DP_NOT_PPDU_ID_WRAP_AROUND)) {
 		/* PPDU ID has exceeded the maximum value and will
 		 * restart from 0.
 		 */
 		*ppdu_id = msdu_ppdu_id;
-		ret = msdu_ppdu_id;
+		return true;
 	}
-	return ret;
+	return false;
 }
 
 static
Signature · 1 line
2.53.0
author maintainer
#551 lore raw

PATCH 550/990 wifi: ath12k: fix out-of-bounds access on TX stats arrays

In reply to Greg Kroah-Hartman

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

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

From: Pardeep Kaur <[email protected]>

[ Upstream commit c8f83d3389d1d1b318ac3bd2ae3d60c2862c90b4 ]

The fw_tx_status[], tx_wbm_rel_source[], and tqm_rel_reason[] arrays are indexed directly by values read from hardware without bounds checks. Values at or beyond MAX_FW_TX_STATUS, HAL_WBM_REL_SRC_MODULE_MAX, or MAX_TQM_RELEASE_REASON respectively would write past the end of the arrays causing memory corruption.

Add likely() bounds checks before incrementing each counter. For tx_wbm_rel_source[] and tqm_rel_reason[], add WARN_ON_ONCE() on the out-of-bounds else branch. For fw_tx_status[], no WARN_ON_ONCE is added since the switch statement that follows already calls ath12k_warn() in its default: branch for unknown values, avoiding a double-warn.

Tested-on: QCN9274 hw2.0 PCI WLAN.WBE.1.6.r1-00402-QCAHKSWPL_SILICONZ-1

Fixes c5c62287e690 ("wifi: ath12k: Add device dp stats support")
[ sashal: Applied the same three bounds checks to the pre-wifi7-split dp_tx.c and used ab->device_stats instead of dp->device_stats. ]
---
 drivers/net/wireless/ath/ath12k/dp_tx.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
drivers/net/wireless/ath/ath12k/dp_tx.c +10 -3
index 92bb9fc420264..ed8c82346608b 100644
@@ -667,7 +667,8 @@ ath12k_dp_tx_process_htt_tx_complete(struct ath12k_base *ab, void *desc,
 
 	wbm_status = le32_get_bits(status_desc->info0,
 				   HTT_TX_WBM_COMP_INFO0_STATUS);
-	ab->device_stats.fw_tx_status[wbm_status]++;
+	if (likely(wbm_status < MAX_FW_TX_STATUS))
+		ab->device_stats.fw_tx_status[wbm_status]++;
 
 	switch (wbm_status) {
 	case HAL_WBM_REL_HTT_TX_COMP_STATUS_OK:
@@ -1071,11 +1072,17 @@ void ath12k_dp_tx_completion_handler(struct ath12k_base *ab, int ring_id)
 		/* Find the HAL_WBM_RELEASE_INFO0_REL_SRC_MODULE value */
 		buf_rel_source = le32_get_bits(tx_status->info0,
 					       HAL_WBM_RELEASE_INFO0_REL_SRC_MODULE);
-		ab->device_stats.tx_wbm_rel_source[buf_rel_source]++;
+		if (likely(buf_rel_source < HAL_WBM_REL_SRC_MODULE_MAX))
+			ab->device_stats.tx_wbm_rel_source[buf_rel_source]++;
+		else
+			WARN_ON_ONCE(1);
 
 		rel_status = le32_get_bits(tx_status->info0,
 					   HAL_WBM_COMPL_TX_INFO0_TQM_RELEASE_REASON);
-		ab->device_stats.tqm_rel_reason[rel_status]++;
+		if (likely(rel_status < MAX_TQM_RELEASE_REASON))
+			ab->device_stats.tqm_rel_reason[rel_status]++;
+		else
+			WARN_ON_ONCE(1);
 
 		/* Release descriptor as soon as extracting necessary info
 		 * to reduce contention
Signature · 1 line
2.53.0
author maintainer
#552 lore raw

PATCH 551/990 ACPI: PCC: Free channel on OpRegion deactivation

In reply to Greg Kroah-Hartman

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

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

From: Sudeep Holla <[email protected]>

[ Upstream commit fa9c7ee692988edddc1da74bc5257d53dd3c7130 ]

ACPICA calls the address space setup callback with ACPI_REGION_DEACTIVATE when a PCC OperationRegion is torn down.

The PCC setup callback currently allocates a fresh pcc_data and requests the mailbox channel before looking at the function argument. If ACPICA deactivates a region, this can leave the existing region context and mailbox channel unreleased, and may also request a channel during teardown.

Handle ACPI_REGION_DEACTIVATE before allocation. Free the PCC mailbox channel, release the region context and clear the context pointer.

Fixes 77e2a04745ff ("ACPI: PCC: Implement OperationRegion handler for the PCC Type 3 subtype")
[ sashal: kept the existing kzalloc(sizeof(*data), GFP_KERNEL) allocation line instead of upstream's kzalloc_obj(*data), which only affected the surrounding context. ]
---
 drivers/acpi/acpi_pcc.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
drivers/acpi/acpi_pcc.c +13 -0
index 683924a708ba0..04bb232603965 100644
@@ -55,6 +55,19 @@ acpi_pcc_address_space_setup(acpi_handle region_handle, u32 function,
 	struct pcc_mbox_chan *pcc_chan;
 	acpi_status ret;
 
+	if (function == ACPI_REGION_DEACTIVATE) {
+		data = *region_context;
+		if (data) {
+			pcc_mbox_free_channel(data->pcc_chan);
+			kfree(data);
+			*region_context = NULL;
+		}
+		return AE_OK;
+	}
+
+	if (function != ACPI_REGION_ACTIVATE)
+		return AE_BAD_PARAMETER;
+
 	data = kzalloc(sizeof(*data), GFP_KERNEL);
 	if (!data)
 		return AE_NO_MEMORY;
Signature · 1 line
2.53.0
author maintainer
#553 lore raw

PATCH 552/990 arm64: dts: qcom: lemans-evk: fix SerDes PHY regulator supplies

In reply to Greg Kroah-Hartman

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

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

From: Mohd Ayaan Anwar <[email protected]>

[ Upstream commit 457cf65a7997e398d8d6cef08601b4ea61b58e38 ]

The SerDes PHY nodes were configured with 'phy-supply = <&vreg_l5a>', which was incorrect on two counts: vreg_l5a is not a supply the PHY requires, and only one rail was described whereas the hardware needs two.

The PHY requires vdda-0p9 (vreg_l4a) and vdda-1p2 (vreg_l1c). Replace the incorrect phy-supply with these two named properties on both the base EVK node and the IFP mezzanine overlay.

Fixes 71ee90ed1756 ("arm64: dts: qcom: lemans-evk: Enable 2.5G Ethernet interface")
[ sashal: dropped the lemans-evk-ifp-mezzanine.dtso hunk (&serdes1) because that overlay file doesn't exist in this tree; the &serdes0 hunk in lemans-evk.dts applies with adjusted context. ]
---
 arch/arm64/boot/dts/qcom/lemans-evk.dts | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/arm64/boot/dts/qcom/lemans-evk.dts +2 -1
index c7dc9b8f44578..5cac85b782d6e 100644
@@ -646,7 +646,8 @@ &sdhc {
 };
 
 &serdes0 {
-	phy-supply = <&vreg_l5a>;
+	vdda-0p9-supply = <&vreg_l4a>;
+	vdda-1p2-supply = <&vreg_l1c>;
 
 	status = "okay";
 };
Signature · 1 line
2.53.0
author maintainer
#554 lore raw

PATCH 553/990 bpf: Rebase the exception callback subprog when dead subprogs are removed

In reply to Greg Kroah-Hartman

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

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

From: Daniel Borkmann <[email protected]>

[ Upstream commit 8608ec8e981974b18834e2d67ed39638a9ec2e63 ]

adjust_subprog_starts_after_remove() compacts subprog_info[] and the func_info when whole subprograms are removed as dead code, but leaves env->exception_callback_subprog alone, so an exception callback declared through the exception_callback decl tag which sits behind a removed subprogram keeps its old index. jit_subprogs() then takes the exception callback from func[] at that index, which is past the end when the callback was the last subprogram, or another subprogram otherwise.

Rebase the index along with the entries it refers to.

Fixes b9ae0c9dd0ac ("bpf: Add support for custom exception callbacks")
[ sashal: Applied the fix to the same function in kernel/bpf/verifier.c, since this tree predates the split into fixups.c; the three added lines and surrounding context are otherwise identical. ]
---
 kernel/bpf/verifier.c | 3 +++
 1 file changed, 3 insertions(+)
kernel/bpf/verifier.c +3 -0
index 23c1401a97bdf..b664c160b9277 100644
@@ -21608,6 +21608,9 @@ static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
 			 * in adjust_btf_func() - no need to adjust
 			 */
 		}
+		/* The exception callback is live, so it cannot sit inside the removed range. */
+		if (env->exception_callback_subprog >= j)
+			env->exception_callback_subprog -= j - i;
 	} else {
 		/* convert i from "first prog to remove" to "first to adjust" */
 		if (env->subprog_info[i].start == off)
Signature · 1 line
2.53.0
author maintainer
#555 lore raw

PATCH 554/990 tools/nolibc: fix readdir_r() with 64-bit directory offsets

In reply to Greg Kroah-Hartman

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

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

From: Danish Khateeb <[email protected]>

[ Upstream commit 00c81514ad49110574e4b9bdbc448551004161f2 ]

readdir_r() stores the result of _sys_lseek() in an int. Directory offsets are opaque cookies which can use all 64 bits: ext4, for instance, gives 64-bit processes 63-bit hashes, and 0x7fffffffffffffff as the offset after the last entry. Truncated to an int, such an offset is negative about half the time, and readdir_r() takes it for an error.

Since commit 4ada5679f18d ("tools/nolibc/dirent: avoid errno in readdir_r"), readdir_r() fails at the first entry whose offset has bit 31 set, which on ext4 is usually one of the first few, and returns the truncated offset as the error number. Before that, only -1 counted as an error, which the last entry always hits: readdir_r() then returned errno, usually 0, without filling in the entry, so the caller got the previous entry a second time and never saw the last one.

32-bit processes get 31-bit hashes from ext4 and are not affected.

Keep the offset in an off_t.

Fixes 665fa8dea90d ("tools/nolibc: add support for directory access")
Assisted-by LLM
[ sashal: Renamed _sys_lseek() to sys_lseek() in the readdir_r() hunk, since this tree still uses the older helper name. ]
---
 tools/include/nolibc/dirent.h | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
tools/include/nolibc/dirent.h +4 -3
index 61a122a60327d..be0eaefea7a41 100644
@@ -67,6 +67,7 @@ int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
 	struct linux_dirent64 *ldir = (void *)buf;
 	intptr_t i = (intptr_t)dirp;
 	int fd, ret;
+	off_t off;
 
 	if (i >= 0)
 		return EBADF;
@@ -86,9 +87,9 @@ int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
 	 * readdir() can only return one entry at a time.
 	 * Make sure the non-returned ones are not skipped.
 	 */
-	ret = sys_lseek(fd, ldir->d_off, SEEK_SET);
-	if (ret < 0)
-		return -ret;
+	off = sys_lseek(fd, ldir->d_off, SEEK_SET);
+	if (off < 0)
+		return -off;
 
 	entry->d_ino = ldir->d_ino;
 	/* the destination should always be big enough */
Signature · 1 line
2.53.0
author maintainer
#556 lore raw

PATCH 555/990 RDMA/vmw_pvrdma: Pin QP and SRQ rings writable to match device DMA write access

In reply to Greg Kroah-Hartman

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

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

From: Yishai Hadas <[email protected]>

[ Upstream commit 89abac4b60b708037595255ea2614b6967c86ee5 ]

pvrdma embeds a pvrdma_ring_state header directly inside the QP and SRQ ring buffers, and the hypervisor writes cons_head into that header. Pinning with access=0 does not force a private page copy (no FOLL_WRITE), so the hypervisor may write into a shared page.

Pass IB_ACCESS_LOCAL_WRITE for all three rings. The SRQ ring_state is not currently used by the driver but is pinned writable for consistency.

Fixes 29c8d9eba550 ("IB: Add vmw_pvrdma driver")
[ sashal: Replaced ib_umem_get_va() calls with the older ib_umem_get() name while changing the access argument from 0 to IB_ACCESS_LOCAL_WRITE. ]
---
 drivers/infiniband/hw/vmw_pvrdma/pvrdma_qp.c  | 6 ++++--
 drivers/infiniband/hw/vmw_pvrdma/pvrdma_srq.c | 3 ++-
 2 files changed, 6 insertions(+), 3 deletions(-)
drivers/infiniband/hw/vmw_pvrdma/pvrdma_qp.c +4 -2
index 98b2a0090bf2a..3017a4080235d 100644
@@ -270,7 +270,8 @@ int pvrdma_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *init_attr,
 				/* set qp->sq.wqe_cnt, shift, buf_size.. */
 				qp->rumem = ib_umem_get(ibqp->device,
 							ucmd.rbuf_addr,
-							ucmd.rbuf_size, 0);
+							ucmd.rbuf_size,
+							IB_ACCESS_LOCAL_WRITE);
 				if (IS_ERR(qp->rumem)) {
 					ret = PTR_ERR(qp->rumem);
 					goto err_qp;
@@ -282,7 +283,8 @@ int pvrdma_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *init_attr,
 			}
 
 			qp->sumem = ib_umem_get(ibqp->device, ucmd.sbuf_addr,
-						ucmd.sbuf_size, 0);
+						ucmd.sbuf_size,
+						IB_ACCESS_LOCAL_WRITE);
 			if (IS_ERR(qp->sumem)) {
 				if (!is_srq)
 					ib_umem_release(qp->rumem);
drivers/infiniband/hw/vmw_pvrdma/pvrdma_srq.c +2 -1
index bdc2703532c6c..99748f0f296dd 100644
@@ -146,7 +146,8 @@ int pvrdma_create_srq(struct ib_srq *ibsrq, struct ib_srq_init_attr *init_attr,
 		goto err_srq;
 	}
 
-	srq->umem = ib_umem_get(ibsrq->device, ucmd.buf_addr, ucmd.buf_size, 0);
+	srq->umem = ib_umem_get(ibsrq->device, ucmd.buf_addr, ucmd.buf_size,
+				IB_ACCESS_LOCAL_WRITE);
 	if (IS_ERR(srq->umem)) {
 		ret = PTR_ERR(srq->umem);
 		goto err_srq;
Signature · 1 line
2.53.0
author maintainer
#557 lore raw

PATCH 556/990 RDMA/mlx5: Set QP event handler before firmware QPC insertion

In reply to Greg Kroah-Hartman

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

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

From: Yishai Hadas <[email protected]>

[ Upstream commit 05a078c97eb0bb7158526dae414b853737692485 ]

Four QP creation paths assigned base->container_mibqp and base->mqp.event after the firmware create call that inserts the QP into dev->qp_table.tree. A firmware error EQE in that window reaches qp->event() with a NULL pointer.

Move both assignments before the firmware call.

Also set ibqp.qp_num inside mlx5_qpc_create_qp() before create_resource_common() so an EQE arriving early does not observe qp_num==0.

In addition, add a WARN_ON_ONCE(!qp->event) guard in rsc_event_notifier() as a safeguard for future regressions.

Fixes e126ba97dba9 ("mlx5: Add driver for Mellanox Connect-IB adapters")
[ sashal: Moved the base->container_mibqp and mqp.event assignments ahead of the firmware QP creation call, with context adjusted for the older base (no attrs argument in create_raw_packet_qp_sq()). ]
---
 drivers/infiniband/hw/mlx5/qp.c  | 22 ++++++++++------------
 drivers/infiniband/hw/mlx5/qpc.c | 10 ++++++++++
 2 files changed, 20 insertions(+), 12 deletions(-)
drivers/infiniband/hw/mlx5/qp.c +10 -12
index 865000d1a2c52..5a6aede3f138a 100644
@@ -1599,6 +1599,8 @@ static int create_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp,
 		if (err)
 			return err;
 
+		sq->base.container_mibqp = qp;
+		sq->base.mqp.event = mlx5_ib_qp_event;
 		err = create_raw_packet_qp_sq(dev, udata, sq, in, pd,
 					      to_mcq(init_attr->send_cq));
 		if (err)
@@ -1610,9 +1612,6 @@ static int create_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp,
 			resp->sqn = sq->base.mqp.qpn;
 			resp->comp_mask |= MLX5_IB_CREATE_QP_RESP_MASK_SQN;
 		}
-
-		sq->base.container_mibqp = qp;
-		sq->base.mqp.event = mlx5_ib_qp_event;
 	}
 
 	if (qp->rq.wqe_cnt) {
@@ -2062,13 +2061,13 @@ static int create_xrc_tgt_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp,
 	}
 
 	base = &qp->trans_qp.base;
+	base->container_mibqp = qp;
+	base->mqp.event = mlx5_ib_qp_event;
 	err = mlx5_qpc_create_qp(dev, &base->mqp, in, inlen, out);
 	kvfree(in);
 	if (err)
 		return err;
 
-	base->container_mibqp = qp;
-	base->mqp.event = mlx5_ib_qp_event;
 	if (MLX5_CAP_GEN(mdev, ece_support))
 		params->resp.ece_options = MLX5_GET(create_qp_out, out, ece);
 
@@ -2206,14 +2205,14 @@ static int create_dci(struct mlx5_ib_dev *dev, struct ib_pd *pd,
 		qp->flags &= ~IB_QP_CREATE_PCI_WRITE_END_PADDING;
 	}
 
+	base->container_mibqp = qp;
+	base->mqp.event = mlx5_ib_qp_event;
 	err = mlx5_qpc_create_qp(dev, &base->mqp, in, inlen, out);
 
 	kvfree(in);
 	if (err)
 		goto err_create;
 
-	base->container_mibqp = qp;
-	base->mqp.event = mlx5_ib_qp_event;
 	if (MLX5_CAP_GEN(mdev, ece_support))
 		params->resp.ece_options = MLX5_GET(create_qp_out, out, ece);
 
@@ -2402,6 +2401,8 @@ static int create_user_qp(struct mlx5_ib_dev *dev, struct ib_pd *pd,
 		qp->flags &= ~IB_QP_CREATE_PCI_WRITE_END_PADDING;
 	}
 
+	base->container_mibqp = qp;
+	base->mqp.event = mlx5_ib_qp_event;
 	if (init_attr->qp_type == IB_QPT_RAW_PACKET ||
 	    qp->flags & IB_QP_CREATE_SOURCE_QPN) {
 		qp->raw_packet_qp.sq.ubuffer.buf_addr = ucmd->sq_buf_addr;
@@ -2415,8 +2416,6 @@ static int create_user_qp(struct mlx5_ib_dev *dev, struct ib_pd *pd,
 	if (err)
 		goto err_create;
 
-	base->container_mibqp = qp;
-	base->mqp.event = mlx5_ib_qp_event;
 	if (MLX5_CAP_GEN(mdev, ece_support))
 		params->resp.ece_options = MLX5_GET(create_qp_out, out, ece);
 
@@ -2545,14 +2544,13 @@ static int create_kernel_qp(struct mlx5_ib_dev *dev, struct ib_pd *pd,
 	    MLX5_CAP_GEN(mdev, go_back_n))
 		MLX5_SET(qpc, qpc, retry_mode, MLX5_QP_RM_GO_BACK_N);
 
+	base->container_mibqp = qp;
+	base->mqp.event = mlx5_ib_qp_event;
 	err = mlx5_qpc_create_qp(dev, &base->mqp, in, inlen, out);
 	kvfree(in);
 	if (err)
 		goto err_create;
 
-	base->container_mibqp = qp;
-	base->mqp.event = mlx5_ib_qp_event;
-
 	get_cqs(qp->type, attr->send_cq, attr->recv_cq,
 		&send_cq, &recv_cq);
 	spin_lock_irqsave(&dev->reset_flow_resource_lock, flags);
drivers/infiniband/hw/mlx5/qpc.c +10 -0
index 67ed45f3ae17f..9272e1ef81135 100644
@@ -146,6 +146,8 @@ static int rsc_event_notifier(struct notifier_block *nb,
 	case MLX5_RES_RQ:
 	case MLX5_RES_SQ:
 		qp = (struct mlx5_core_qp *)common;
+		if (WARN_ON_ONCE(!qp->event))
+			goto out;
 		qp->event(qp, event_type);
 		/* Need to put resource in event handler */
 		return NOTIFY_OK;
@@ -258,6 +260,14 @@ int mlx5_qpc_create_qp(struct mlx5_ib_dev *dev, struct mlx5_core_qp *qp,
 
 	qp->uid = MLX5_GET(create_qp_in, in, uid);
 	qp->qpn = MLX5_GET(create_qp_out, out, qpn);
+	/* Set ibqp.qp_num before create_resource_common() inserts the QP into
+	 * the radix tree and makes it visible to EQE processing.  The
+	 * assignment in create_qp() happens only after this function returns,
+	 * leaving a window where an arriving EQE would observe qp_num == 0.
+	 * create_qp() still overrides this with 0/1 for QP0/QP1, and sets it
+	 * independently for DCT (which does not go through this function).
+	 */
+	to_mibqp(qp)->ibqp.qp_num = qp->qpn;
 
 	err = create_resource_common(dev, qp, MLX5_RES_QP);
 	if (err)
Signature · 1 line
2.53.0
author maintainer
#558 lore raw

PATCH 557/990 RDMA/bnxt_re: Serialize dcb_wq access against async notifier

In reply to Greg Kroah-Hartman

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

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

From: Selvin Xavier <[email protected]>

[ Upstream commit 81caf9240dfb082c0eb2b24feef8266268fd152f ]

bnxt_re_async_notifier() runs in NAPI/softirq context via bnxt_en's RCU-protected ULP ops dispatch, never under rtnl_lock, so it isn't serialized against bnxt_re_uninit_dcb_wq() destroying rdev->dcb_wq. A concurrent notifier call can queue_work() on a workqueue that is being, or has just been, destroyed.

Add a spinlock scoped to dcb_wq: the notifier takes it before checking dcb_wq and queuing work, and bnxt_re_uninit_dcb_wq() takes it to atomically clear dcb_wq before destroying it. Initialize the lock at rdev allocation so it is valid on every teardown path, including bnxt_re_dev_init()'s early failure labels.

Fixes 51dc5312dcd9 ("RDMA/bnxt_re: Add support to handle DCB_CONFIG_CHANGE event")
[ sashal: Used the branch's kzalloc(sizeof(*dcb_work), GFP_ATOMIC) in place of upstream's kzalloc_obj(*dcb_work, GFP_ATOMIC) in the DCB_CONFIG_CHANGE notifier, to fit the surrounding code. ]
---
 drivers/infiniband/hw/bnxt_re/bnxt_re.h |  4 ++++
 drivers/infiniband/hw/bnxt_re/main.c    | 24 ++++++++++++++++++++----
 2 files changed, 24 insertions(+), 4 deletions(-)
drivers/infiniband/hw/bnxt_re/bnxt_re.h +4 -0
index 3485e495ac6aa..ce3a1fd8aa830 100644
@@ -222,6 +222,10 @@ struct bnxt_re_dev {
 	unsigned long			event_bitmap;
 	struct bnxt_qplib_cc_param	cc_param;
 	struct workqueue_struct		*dcb_wq;
+	/* Protects dcb_wq against bnxt_re_uninit_dcb_wq() destroying it
+	 * concurrently with bnxt_re_async_notifier() queuing work on it.
+	 */
+	spinlock_t			dcb_lock;
 	struct dentry                   *cc_config;
 	struct bnxt_re_dbg_cc_config_params *cc_config_params;
 #define BNXT_VPD_FLD_LEN		32
drivers/infiniband/hw/bnxt_re/main.c +20 -4
index e8a4befd6ca01..690b261b581a5 100644
@@ -367,9 +367,15 @@ static int bnxt_re_init_dcb_wq(struct bnxt_re_dev *rdev)
 
 static void bnxt_re_uninit_dcb_wq(struct bnxt_re_dev *rdev)
 {
-	if (!rdev->dcb_wq)
-		return;
-	destroy_workqueue(rdev->dcb_wq);
+	struct workqueue_struct *dcb_wq;
+
+	spin_lock_bh(&rdev->dcb_lock);
+	dcb_wq = rdev->dcb_wq;
+	rdev->dcb_wq = NULL;
+	spin_unlock_bh(&rdev->dcb_lock);
+
+	if (dcb_wq)
+		destroy_workqueue(dcb_wq);
 }
 
 static void bnxt_re_dcb_wq_task(struct work_struct *work)
@@ -424,14 +430,23 @@ static void bnxt_re_async_notifier(void *handle, struct hwrm_async_event_cmpl *c
 
 	switch (event_id) {
 	case ASYNC_EVENT_CMPL_EVENT_ID_DCB_CONFIG_CHANGE:
+		spin_lock(&rdev->dcb_lock);
+		if (!rdev->dcb_wq) {
+			spin_unlock(&rdev->dcb_lock);
+			break;
+		}
+
 		dcb_work = kzalloc(sizeof(*dcb_work), GFP_ATOMIC);
-		if (!dcb_work)
+		if (!dcb_work) {
+			spin_unlock(&rdev->dcb_lock);
 			break;
+		}
 
 		dcb_work->rdev = rdev;
 		memcpy(&dcb_work->cmpl, cmpl, sizeof(*cmpl));
 		INIT_WORK(&dcb_work->work, bnxt_re_dcb_wq_task);
 		queue_work(rdev->dcb_wq, &dcb_work->work);
+		spin_unlock(&rdev->dcb_lock);
 		break;
 	default:
 		break;
@@ -1446,6 +1461,7 @@ static struct bnxt_re_dev *bnxt_re_dev_add(struct auxiliary_device *adev,
 	INIT_LIST_HEAD(&rdev->qp_list);
 	mutex_init(&rdev->qp_lock);
 	mutex_init(&rdev->pacing.dbq_lock);
+	spin_lock_init(&rdev->dcb_lock);
 	atomic_set(&rdev->stats.res.qp_count, 0);
 	atomic_set(&rdev->stats.res.cq_count, 0);
 	atomic_set(&rdev->stats.res.srq_count, 0);
Signature · 1 line
2.53.0
author maintainer
#559 lore raw

PATCH 558/990 powerpc/bpf: Move out dummy_tramp_addr after Long branch stub

In reply to Greg Kroah-Hartman

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

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

From: Abhishek Dubey <[email protected]>

[ Upstream commit 6652b9941a6c9b6814ca6d2eb153dbf162b89a02 ]

Move the long branch address field to the bottom of the long branch stub. This allows uninterrupted disassembly until the last 4/8 bytes. The last bytes exclusion is logically necessary to prevent disassembly failure, otherwise the actual program layout is never altered. Hence no effect on overall program size. Also, align dummy_tramp_addr field with 8-byte boundary.

Following is disassembler output for test program with moved down dummy_tramp_addr field:
.....
.....

pc:68    left:44     a6 03 08 7c  :  mtlr 0
pc:72    left:40     bc ff ff 4b  :  b .-68
pc:76    left:36     a6 02 68 7d  :  mflr 11
pc:80    left:32     05 00 9f 42  :  bcl 20, 31, .+4
pc:84    left:28     a6 02 88 7d  :  mflr 12
pc:88    left:24     14 00 8c e9  :  ld 12, 20(12)
pc:92    left:20     a6 03 89 7d  :  mtctr 12
pc:96    left:16     a6 03 68 7d  :  mtlr 11
pc:100   left:12     20 04 80 4e  :  bctr
pc:104   left:8      c0 34 1d 00  :

Failure log:
Can't disasm instruction at offset 104: c0 34 1d 00 00 00 00 c0 Disassembly logic can truncate at 104, ignoring last 8 bytes.

Update the dummy_tramp_addr field offset calculation from the end of the program to reflect its new location, for bpf_arch_text_poke() to update the actual trampoline's address in this field.

All BPF trampoline selftests continue to pass with this patch applied.

---
 arch/powerpc/net/bpf_jit_comp.c | 44 ++++++++++++++++++---------------
 1 file changed, 24 insertions(+), 20 deletions(-)
arch/powerpc/net/bpf_jit_comp.c +24 -20
index 4a7f5108fe0fd..f23ed48c4e327 100644
@@ -52,19 +52,19 @@ asm (
 void bpf_jit_build_fentry_stubs(u32 *image, u32 *fimage, struct codegen_context *ctx)
 {
 	int ool_stub_idx, long_branch_stub_idx;
-	int ool_stub_sz;
+	int stub_sz;
 
 	/*
+	 * The dummy_tramp_addr field is placed at bottom of Long branch stub.
 	 * Align the mis-aligned dummy_tramp_addr field in the fimage.
 	 * The alignment NOP must appear before OOL stub, to make
 	 * ool_stub_idx & long_branch_stub_idx constant from end.
 	 *
 	 * The fimage can be non 8-byte aligned, so final alignment depends
-	 * on start of fimage and the stub's instruction count offset. The
-	 * OOL stub size is 4 instructions (with CONFIG_PPC_FTRACE_OUT_OF_LINE)
-	 * or 3 instructions (without) before dummy_tramp_addr.
-	 *
-	 * Emit a NOP here if address is not SZL aligned.
+	 * on start of fimage and the stub's instruction count. The
+	 * stubs block has 11 instructions (with CONFIG_PPC_FTRACE_OUT_OF_LINE)
+	 * or 10 instructions (without) before dummy_tramp_addr field. Emit a
+	 * NOP if the address of dummy_tramp_addr is non aligned.
 	 *
 	 * In pass=0 when image==NULL, conservatively account for space
 	 * required to accommodate alignment NOP. In case final pass skips
@@ -72,8 +72,8 @@ void bpf_jit_build_fentry_stubs(u32 *image, u32 *fimage, struct codegen_context
 	 * jited_len signifies correct program size.
 	 */
 
-	ool_stub_sz = IS_ENABLED(CONFIG_PPC_FTRACE_OUT_OF_LINE) ? 16 : 12;
-	if (!image || !IS_ALIGNED((unsigned long)fimage + ctx->idx*4 + ool_stub_sz, SZL))
+	stub_sz = IS_ENABLED(CONFIG_PPC_FTRACE_OUT_OF_LINE) ? 44 : 40;
+	if (!image || !IS_ALIGNED((unsigned long)fimage + ctx->idx*4 + stub_sz, SZL))
 		EMIT(PPC_RAW_NOP());
 
 	/*
@@ -94,28 +94,29 @@ void bpf_jit_build_fentry_stubs(u32 *image, u32 *fimage, struct codegen_context
 
 	/*
 	 * Long branch stub:
-	 *	.long	<dummy_tramp_addr>  // 8-byte aligned
 	 *	mflr	r11
 	 *	bcl	20,31,$+4
-	 *	mflr	r12
-	 *	ld	r12, -8-SZL(r12)
+	 *	mflr	r12	// lr/r12 stores pc of current(this) inst.
+	 *	ld	r12, 20(r12) // offset(dummy_tramp_addr) from prev inst. is 20
 	 *	mtctr	r12
-	 *	mtlr	r11 // needed to retain ftrace ABI
+	 *	mtlr	r11	// needed to retain ftrace ABI
 	 *	bctr
+	 *	.long	<dummy_tramp_addr>  // SZL bytes aligned
 	 */
-	if (image)
-		*((unsigned long *)&image[ctx->idx]) = (unsigned long)dummy_tramp;
-
-	ctx->idx += SZL / 4;
 	long_branch_stub_idx = ctx->idx;
 	EMIT(PPC_RAW_MFLR(_R11));
 	EMIT(PPC_RAW_BCL4());
 	EMIT(PPC_RAW_MFLR(_R12));
-	EMIT(PPC_RAW_LL(_R12, _R12, -8-SZL));
+	EMIT(PPC_RAW_LL(_R12, _R12, 20));
 	EMIT(PPC_RAW_MTCTR(_R12));
 	EMIT(PPC_RAW_MTLR(_R11));
 	EMIT(PPC_RAW_BCTR());
 
+	if (image)
+		*((unsigned long *)&image[ctx->idx]) = (unsigned long)dummy_tramp;
+
+	ctx->idx += SZL / 4;
+
 	if (!bpf_jit_ool_stub) {
 		bpf_jit_ool_stub = (ctx->idx - ool_stub_idx) * 4;
 		bpf_jit_long_branch_stub = (ctx->idx - long_branch_stub_idx) * 4;
@@ -1129,6 +1130,7 @@ static void do_isync(void *info __maybe_unused)
  * bpf_func:
  *	[nop|b]	ool_stub
  * 2. Out-of-line stub:
+ *	nop	// optional nop for alignment
  * ool_stub:
  *	mflr	r0
  *	[b|bl]	<bpf_prog>/<long_branch_stub>
@@ -1136,14 +1138,14 @@ static void do_isync(void *info __maybe_unused)
  *	b	bpf_func + 4
  * 3. Long branch stub:
  * long_branch_stub:
- *	.long	<branch_addr>/<dummy_tramp>
  *	mflr	r11
  *	bcl	20,31,$+4
  *	mflr	r12
- *	ld	r12, -16(r12)
+ *	ld	r12, 20(r12)
  *	mtctr	r12
  *	mtlr	r11 // needed to retain ftrace ABI
  *	bctr
+ *	.long	<branch_addr>/<dummy_tramp>
  *
  * dummy_tramp is used to reduce synchronization requirements.
  *
@@ -1243,10 +1245,12 @@ int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type poke_type,
 	 * 1. Update the address in the long branch stub:
 	 * If new_addr is out of range, we will have to use the long branch stub, so patch new_addr
 	 * here. Otherwise, revert to dummy_tramp, but only if we had patched old_addr here.
+	 *
+	 * dummy_tramp_addr moved to bottom of long branch stub.
 	 */
 	if ((new_addr && !is_offset_in_branch_range(new_addr - ip)) ||
 	    (old_addr && !is_offset_in_branch_range(old_addr - ip)))
-		ret = patch_ulong((void *)(bpf_func_end - bpf_jit_long_branch_stub - SZL),
+		ret = patch_ulong((void *)(bpf_func_end - SZL), /* SZL: dummy_tramp_addr offset */
 				  (new_addr && !is_offset_in_branch_range(new_addr - ip)) ?
 				  (unsigned long)new_addr : (unsigned long)dummy_tramp);
 	if (ret)
Signature · 1 line
2.53.0
author maintainer
#560 lore raw

PATCH 559/990 powerpc/interrupt: Use early_radix_enabled() in NMI real-mode guard

In reply to Greg Kroah-Hartman

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

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

From: Venkat Rao Bagalkote <[email protected]>

[ Upstream commit 644ffb02746690c0ebfe143e066f81c9bde2975e ]

radix_enabled() uses a jump label which is only valid after setup_feature_keys() is called. Before that point, on a pSeries hash guest, early_check_vec5() clears MMU_FTR_TYPE_RADIX in cur_cpu_spec->mmu_features, but the jump label has not yet been patched, so radix_enabled() incorrectly returns true.

The dangerous usage window where it goes wrong in early_setup():

early_setup:
configure_exceptions();
<exceptions can happen now, and handler enter/exit can be invoked> <those could use radix_enabled(), which returns stale true> setup_feature_keys();
<jump labels set up; post this it is safe to use radix_enabled()>

If an NMI occurs in this window, !radix_enabled() evaluates to false in DEFINE_INTERRUPT_HANDLER_NMI. The handler fails to skip NMI entry in real mode and attempts to access memory outside the Real Mode Area (RMA), hanging the boot.

Since common interrupt wrappers do not have the context of early or late, using early_radix_enabled() is the safer option. It does a plain bitmask check against cur_cpu_spec->mmu_features and is correct at all times.

Console logs from a pSeries HASH guest showing values across boot stages:

[    0.000000] DEBUG: after early_init_devtree: early_radix_enabled=0 radix_enabled=1 (mismatch means NMI real-mode check is unsafe!)
[    0.000000] DEBUG: after configure_exceptions (DANGEROUS WINDOW): early_radix_enabled=0 radix_enabled=1
[    0.000000] DEBUG: after setup_feature_keys (jump labels initialized): early_radix_enabled=0 radix_enabled=0 (should now match!)
[    0.057124] DEBUG: post secondary CPU bringup: early_radix_enabled=0 radix_enabled=0 (should match!)

Console logs from a RADIX guest showing values across boot stages:

[    0.000000] DEBUG: after early_init_devtree: early_radix_enabled=1 radix_enabled=1 (mismatch means NMI real-mode check is unsafe!)
[    0.000000] DEBUG: after configure_exceptions (DANGEROUS WINDOW): early_radix_enabled=1 radix_enabled=1
[    0.000000] DEBUG: after setup_feature_keys (jump labels initialized): early_radix_enabled=1 radix_enabled=1 (should now match!)
[    0.057016] DEBUG: post secondary CPU bringup: early_radix_enabled=1 radix_enabled=1 (should match!)

Add the missing #include <asm/mmu.h> in alphabetical order since early_radix_enabled() is declared there.

Fixes 8d0e21012743 ("powerpc/mce: Avoid nmi_enter/exit in real mode on pseries hash")
[ sashal: Applied the early_radix_enabled() change in the interrupt_nmi_enter_prepare() and interrupt_nmi_exit_prepare() helpers instead of the DEFINE_INTERRUPT_HANDLER_NMI macro body, since the logic was already refactored there. ]
---
 arch/powerpc/include/asm/interrupt.h | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
arch/powerpc/include/asm/interrupt.h +3 -2
index eb0e4a20b8188..af8c7df0ab9d0 100644
@@ -72,6 +72,7 @@
 #include <asm/firmware.h>
 #include <asm/ftrace.h>
 #include <asm/kprobes.h>
+#include <asm/mmu.h>
 #include <asm/runlatch.h>
 
 #ifdef CONFIG_PPC_IRQ_SOFT_MASK_DEBUG
@@ -326,7 +327,7 @@ static inline void interrupt_nmi_enter_prepare(struct pt_regs *regs, struct inte
 	 */
 	if (IS_ENABLED(CONFIG_PPC_BOOK3S_64) &&
 	    firmware_has_feature(FW_FEATURE_LPAR) &&
-	    !radix_enabled())
+	    !early_radix_enabled())
 		return;
 
 	/*
@@ -355,7 +356,7 @@ static inline void interrupt_nmi_exit_prepare(struct pt_regs *regs, struct inter
 		nmi_exit();
 	} else if (IS_ENABLED(CONFIG_PPC_BOOK3S_64) &&
 		   firmware_has_feature(FW_FEATURE_LPAR) &&
-		   !radix_enabled()) {
+		   !early_radix_enabled()) {
 		// no nmi_exit for a pseries hash guest taking a real mode exception
 	} else if (IS_ENABLED(CONFIG_KASAN)) {
 		// no nmi_exit for KASAN in real mode
Signature · 1 line
2.53.0
author maintainer
#561 lore raw

PATCH 560/990 perf evsel: Clamp sample_id size for ksymbol, bpf, and text_poke events

In reply to Greg Kroah-Hartman

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

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

From: Ian Rogers <[email protected]>

[ Upstream commit 7c89ea1bd4c612eb5cc2e6c01f77ebfc21d5c95d ]

On kernels without the fix ("perf/core: Restore header fields in sideband output callbacks") to restore event_id.header.size in perf_event_ksymbol_output(), perf_event_bpf_output(), and perf_event_text_poke_output(), concurrent perf sessions cause those sideband records to be emitted with header.size inflated by multiple id_header_size increments while the single id_sample is written immediately after the event payload. Indexing backwards from event->header.size reads uninitialized ring-buffer bytes at the end of the record, causing evlist__event2evsel() to fail with -EFAULT.

Add evsel__event_size() to clamp the effective size used to locate the trailing id_sample for PERF_RECORD_KSYMBOL, PERF_RECORD_BPF_EVENT, and PERF_RECORD_TEXT_POKE to payload + id_hdr_size while leaving event->header.size intact for advancing the ring-buffer/file stream.

Fixes 9aa0bfa370b278a5 ("perf tools: Handle PERF_RECORD_KSYMBOL")
Fixes 45178a928a4b7c60 ("perf tools: Handle PERF_RECORD_BPF_EVENT")
Fixes 246eba8e9041c477 ("perf tools: Add support for PERF_RECORD_TEXT_POKE")
Assisted-by Antigravity:gemini-3.1-pro
Cc Adrian Hunter <[email protected]>
Cc Song Liu <[email protected]>
[ sashal: Replaced evlist__id_pos()/evlist__is_pos() accessors with direct evlist->id_pos/is_pos field reads, and adapted perf_evsel__parse_id_sample() to the pointer-walk array form instead of an index. ]
---
 tools/perf/util/evlist.c |  6 ++--
 tools/perf/util/evsel.c  | 59 +++++++++++++++++++++++++++++++++++++++-
 tools/perf/util/evsel.h  |  1 +
 3 files changed, 63 insertions(+), 3 deletions(-)
tools/perf/util/evlist.c +4 -2
index 314393a430a37..67d1ad8a6ee16 100644
@@ -648,13 +648,15 @@ static int evlist__event2id(struct evlist *evlist, union perf_event *event, u64
 	const __u64 *array = event->sample.array;
 	ssize_t n;
 
-	n = (event->header.size - sizeof(event->header)) >> 3;
-
 	if (event->header.type == PERF_RECORD_SAMPLE) {
+		n = (event->header.size - sizeof(event->header)) >> 3;
 		if (evlist->id_pos >= n)
 			return -1;
 		*id = array[evlist->id_pos];
 	} else {
+		u16 size = evsel__event_size(evlist__first(evlist), event);
+
+		n = (size - sizeof(event->header)) >> 3;
 		if (evlist->is_pos > n)
 			return -1;
 		n -= evlist->is_pos;
tools/perf/util/evsel.c +58 -1

71 lines not on this page · raw message

tools/perf/util/evsel.h +1 -0
index f8de0f9a719b0..664bcc8712c2f 100644
@@ -425,6 +425,7 @@ int evsel__parse_sample_timestamp(struct evsel *evsel, union perf_event *event,
 				  u64 *timestamp);
 
 u16 evsel__id_hdr_size(const struct evsel *evsel);
+u16 evsel__event_size(const struct evsel *evsel, const union perf_event *event);
 
 static inline struct evsel *evsel__next(struct evsel *evsel)
 {
Signature · 1 line
2.53.0
author maintainer
#562 lore raw

PATCH 561/990 ALSA: usb-audio: Fix UAC2 mixer unit request handling

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit 0458d97859840506c3688a963dcd4f72b4a23083 ]

For a request for a Mixer Unit on UAC2 (also UAC3), the wValue is different from UAC1 and an incompatible value must be passed. Namely, UAC1 takes a word consisting of 1-based input channel in the high byte and 1-based output channel in the low byte. Meanwhile, UAC2/3 takes UAC2_MU_MIXER in the high byte and a MCN (0-based bit position of input/output channels) in the low byte. The current driver implementation blindly assumes the UAC1 way, hence it would cause a firmware error.

This patch attempts to implement the conversion to UAC2 MCN at get_ctl_value_v2() and snd_usb_mixer_set_ctl_value() for mixer units. At the points above, the old wValue containing ICN and OCN is converted to the corresponding MCN, and it's used as the proper wValue.

---
 sound/usb/mixer.c | 23 +++++++++++++++++++++++
 sound/usb/mixer.h |  2 ++
 2 files changed, 25 insertions(+)
sound/usb/mixer.c +23 -0
index f4e44c31111cd..e578a29a675f0 100644
@@ -335,6 +335,17 @@ static int get_ctl_value_v1(struct usb_mixer_elem_info *cval, int request,
 	return -EINVAL;
 }
 
+/* convert the given UAC1 wValue (ICN|OCN) to UAC2 MCN */
+static unsigned char to_mcn(const struct usb_mixer_elem_info *cval,
+			    unsigned int validx)
+{
+	unsigned char m = (validx >> 8) & 0xff; /* 1-based input channel */
+	unsigned char v = validx & 0xff; /* 1-based output channel */
+
+	/* num_inputs * num_outputs is guaranteed to be < 256 */
+	return (m - 1) * cval->num_outputs + (v - 1);
+}
+
 static int get_ctl_value_v2(struct usb_mixer_elem_info *cval, int request,
 			    int validx, int *value_ret)
 {
@@ -347,6 +358,10 @@ static int get_ctl_value_v2(struct usb_mixer_elem_info *cval, int request,
 
 	val_size = uac2_ctl_value_size(cval->val_type);
 
+	/* correct wValue for UAC2 mixer control with MCN */
+	if (cval->v2_mixer)
+		validx = (UAC2_MU_MIXER << 8) | to_mcn(cval, validx);
+
 	if (request == UAC_GET_CUR) {
 		bRequest = UAC2_CS_CUR;
 		size = val_size;
@@ -473,6 +488,10 @@ int snd_usb_mixer_set_ctl_value(struct usb_mixer_elem_info *cval,
 		}
 
 		request = UAC2_CS_CUR;
+
+		/* correct wValue for UAC2 mixer control with MCN */
+		if (cval->v2_mixer)
+			validx = (UAC2_MU_MIXER << 8) | to_mcn(cval, validx);
 	}
 
 	value_set = convert_bytes_value(cval, value_set);
@@ -2206,6 +2225,10 @@ static void build_mixer_unit_ctl(struct mixer_build *state,
 
 	snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
 	cval->control = in_ch + 1; /* based on 1 */
+	if (state->mixer->protocol == UAC_VERSION_2 ||
+	    state->mixer->protocol == UAC_VERSION_3)
+		cval->v2_mixer = true;
+	cval->num_outputs = num_outs;
 	cval->val_type = USB_MIXER_S16;
 	for (i = 0; i < num_outs; i++) {
 		__u8 *c = uac_mixer_unit_bmControls(desc, state->mixer->protocol);
sound/usb/mixer.h +2 -0
index 8e5e8da6d480f..00ffefb751d2a 100644
@@ -97,6 +97,8 @@ struct usb_mixer_elem_info {
 	int cache_val[MAX_CHANNELS];
 	u8 initialized;
 	u8 min_mute;
+	u8 num_outputs;
+	bool v2_mixer;
 	void *private_data;
 };
 
Signature · 1 line
2.53.0
author maintainer
#563 lore raw

PATCH 562/990 serial: 8250_mid: Add missing module namespace import for SERIAL_8250

In reply to Greg Kroah-Hartman

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

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

From: Nathan Chancellor <[email protected]>

[ Upstream commit 789f52f83305032ecfaaf7efae9a8ba75815c01b ]

After commit 1c305d5f1daa ("serial: 8250_mid: wait for LSR tx empty before setting termios"), modpost errors (or warning with CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS=y):

ERROR: modpost: drivers/tty/serial/8250/8250_mid.ko: module uses symbol 'serial8250_wait_for_xmitr' from namespace 'SERIAL_8250', but does not import it.

Add the missing module namespace import to clear up the error/warning.

Fixes 1c305d5f1daa ("serial: 8250_mid: wait for LSR tx empty before setting termios")
---
 drivers/tty/serial/8250/8250_mid.c | 1 +
 1 file changed, 1 insertion(+)
drivers/tty/serial/8250/8250_mid.c +1 -0
index c02ecb96e8b6f..47f820fcd1a45 100644
@@ -415,3 +415,4 @@ module_pci_driver(mid8250_pci_driver);
 MODULE_AUTHOR("Intel Corporation");
 MODULE_LICENSE("GPL v2");
 MODULE_DESCRIPTION("Intel MID UART driver");
+MODULE_IMPORT_NS("SERIAL_8250");
Signature · 1 line
2.53.0
author maintainer
#564 lore raw

PATCH 563/990 mm/memory_hotplug: fix missing rollback in __add_pages()

In reply to Greg Kroah-Hartman

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

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

From: Lance Yang <[email protected]>

[ Upstream commit c31bb839fb829958101250ee5acfa4f94fdb7ecd ]

__add_pages() returns on a sparse_add_section() failure without removing the sections already added in the same request.

For memremap_pages(), the failed range is not counted in pgmap->nr_range, so memunmap_pages() skips it. The sections already added in that range retain their vmemmap mappings and subsection bits. Retrying a section-aligned range can then fail with -EEXIST.

Save the initial PFN and remove [start_pfn, pfn) on failure. For a vmemmap population failure, section_activate() already cleans up the current section, so the rollback excludes it. If the first section fails, __remove_pages() receives an empty range and does nothing.

Fixes ba72b4c8cf60 ("mm/sparsemem: support sub-section hotplug")
[ sashal: Dropped the fourth params->pgmap argument from the __remove_pages() rollback call, since this tree's __remove_pages() takes only three arguments. ]
---
 mm/memory_hotplug.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
mm/memory_hotplug.c +4 -1
index 9fdfb2d317654..5172401788bd0 100644
@@ -389,6 +389,7 @@ EXPORT_SYMBOL_GPL(pfn_to_online_page);
 int __add_pages(int nid, unsigned long pfn, unsigned long nr_pages,
 		struct mhp_params *params)
 {
+	const unsigned long start_pfn = pfn;
 	const unsigned long end_pfn = pfn + nr_pages;
 	unsigned long cur_nr_pages;
 	int err;
@@ -422,8 +423,10 @@ int __add_pages(int nid, unsigned long pfn, unsigned long nr_pages,
 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
 		err = sparse_add_section(nid, pfn, cur_nr_pages, altmap,
 					 params->pgmap);
-		if (err)
+		if (err) {
+			__remove_pages(start_pfn, pfn - start_pfn, altmap);
 			break;
+		}
 		cond_resched();
 	}
 	vmemmap_populate_print_last();
Signature · 1 line
2.53.0
author maintainer
#565 lore raw

PATCH 564/990 bpf: Roll back freplace link state when bpf_arch_text_poke() fails

In reply to Greg Kroah-Hartman

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

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

From: Yuan Chen <[email protected]>

[ Upstream commit 5ec398d9ec8fe13f8058af9a2e5f5e8f46e0a35a ]

A freplace attach claims the target prog by bumping tgt_prog->aux->freplace_link_cnt and setting tr->extension_prog. bpf_arch_text_poke() then makes the extension take effect. If the poke fails, the claims are never released: the attach unwinds through bpf_link_cleanup(), which clears link->prog, so bpf_trampoline_unlink_prog() never runs.

Drop the link count under ext_mutex on the error path, and set tr->extension_prog only after the poke succeeded. The count is still bumped before the poke: it blocks prog_array updates while the entry is patched.

Fixes d6083f040d5d ("bpf: Prevent tailcall infinite loop caused by freplace")
Fixes be8704ff07d2 ("bpf: Introduce dynamic program extensions")
[ sashal: Adapted the freplace fix to the older bpf_arch_text_poke() four-argument form and link->link.prog, instead of the newer BPF_MOD_NOP call and node->link->prog. ]
---
 kernel/bpf/trampoline.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
kernel/bpf/trampoline.c +9 -2
index 478ea4ec3a801..98704c030a20b 100644
@@ -576,9 +576,16 @@ static int __bpf_trampoline_link_prog(struct bpf_tramp_link *link,
 		err = bpf_freplace_link_tgt_prog(tgt_prog);
 		if (err)
 			return err;
+		err = bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP, NULL,
+					 link->link.prog->bpf_func);
+		if (err) {
+			/* Undo the claim from bpf_freplace_link_tgt_prog(). */
+			guard(mutex)(&tgt_prog->aux->ext_mutex);
+			tgt_prog->aux->freplace_link_cnt--;
+			return err;
+		}
 		tr->extension_prog = link->link.prog;
-		return bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP, NULL,
-					  link->link.prog->bpf_func);
+		return 0;
 	}
 	if (cnt >= BPF_MAX_TRAMP_LINKS)
 		return -E2BIG;
Signature · 1 line
2.53.0
author maintainer
#566 lore raw

PATCH 565/990 scsi: scsi_debug: Enforce physical block alignment of zoned writes

In reply to Greg Kroah-Hartman

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

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

From: Niklas Cassel <[email protected]>

[ Upstream commit 63cb3900be261fccc05cadcf3402058418a5fada ]

ZBC-3 r06 (T10/BSR INCITS 579), 4.5.3.3.2, requires a write to a sequential write required zone to be terminated with ILLEGAL REQUEST / UNALIGNED WRITE COMMAND both when it does not start at the write pointer and when it does not end on a physical block boundary. That is why sd_zbc_read_zones() sets the zone_write_granularity queue limit to the physical block size of a host-managed device.

check_zbc_access_params() implements the first condition but not the second. So with zbc=managed sector_size=512 physblk_exp=3, a write of a single logical block at the write pointer is accepted and advances the write pointer by one logical block, leaving it off the granularity that was
advertised: nothing can write at it any more, and the zone can only be used again after being reset.

Check the ending LBA as well, with the same sense data, as the standard gives both conditions the same. An entire medium write same command, which the standard excludes, needs no special case: the preceding check already terminates it with WRITE BOUNDARY VIOLATION. Sequential write preferred zones are left alone, as writes to them need not be sequential, and with the default physblk_exp=0 the check is a no-op.

Assisted-by LLM
Fixes f0d1cf9378bd ("scsi: scsi_debug: Add ZBC zone commands")
[ sashal: changed the mk_sense_buffer() call to the older four-argument form (LBA_OUT_OF_RANGE, UNALIGNED_WRITE_ASCQ) used by neighbouring code, since the combined UNALIGNED_WRITE_COMMAND form is not used here. ]
---
 drivers/scsi/scsi_debug.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/scsi/scsi_debug.c +11 -0
index 524e0fa457a83..60baa3a3ccbd0 100644
@@ -3904,6 +3904,17 @@ static int check_zbc_access_params(struct scsi_cmnd *scp,
 					UNALIGNED_WRITE_ASCQ);
 			return check_condition_result;
 		}
+		/*
+		 * Writes must end on a physical block boundary, that is, the
+		 * transfer length must be a multiple of the physical block
+		 * size.
+		 */
+		if (!IS_ALIGNED(lba + num, 1U << sdebug_physblk_exp)) {
+			mk_sense_buffer(scp, ILLEGAL_REQUEST,
+					LBA_OUT_OF_RANGE,
+					UNALIGNED_WRITE_ASCQ);
+			return check_condition_result;
+		}
 	}
 
 	/* Handle implicit open of closed and empty zones */
Signature · 1 line
2.53.0
author maintainer
#567 lore raw

PATCH 566/990 iommu/arm-smmu-v3: Dont rb_erase() a never-inserted stream node

In reply to Greg Kroah-Hartman

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

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

From: Nicolin Chen <[email protected]>

[ Upstream commit 2888520bdcbe0599cfc77b2fad8dc6c95505a3cb ]

arm_smmu_insert_master() skips inserting a stream whose StreamID duplicates one the same master already owns (bridged PCI devices can present duplicate IDs), leaving that master->streams[i].node zeroed and unlinked from the smmu->streams rb-tree.

Both the insert error-rollback loop and arm_smmu_remove_master() then call rb_erase() on every master->streams[i].node unconditionally. rb_erase() on a zeroed node sees a NULL parent, treats the node as the tree root and sets root->rb_node = NULL, silently emptying the whole SID tree and breaking SID lookups (and DMA) for every other master on the SMMU.

Mark each node with RB_CLEAR_NODE() after sort_nonatomic() reorders the array, since sorting relocates the entries and would leave the earlier self-referential RB_CLEAR_NODE() pointer stale. An un-inserted node then stays RB_EMPTY_NODE() and is skipped in both erase loops; inserted nodes are linked by rb_find_add() and erased as before.

Fixes b00d24997a11 ("iommu/arm-smmu-v3: Fix iommu_device_probe bug due to duplicated stream ids")
Assisted-by LLM
[ sashal: Placed the RB_CLEAR_NODE() loop right after master->num_streams is set, since this tree has no sort() or build_invs context, and dropped the upstream sort comment. ]
---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +8 -2
index 84dff2f06bcd1..8a678910a18cd 100644
@@ -3535,6 +3535,9 @@ static int arm_smmu_insert_master(struct arm_smmu_device *smmu,
 		return -ENOMEM;
 	master->num_streams = fwspec->num_ids;
 
+	for (i = 0; i < fwspec->num_ids; i++)
+		RB_CLEAR_NODE(&master->streams[i].node);
+
 	mutex_lock(&smmu->streams_mutex);
 	for (i = 0; i < fwspec->num_ids; i++) {
 		struct arm_smmu_stream *new_stream = &master->streams[i];
@@ -3570,7 +3573,9 @@ static int arm_smmu_insert_master(struct arm_smmu_device *smmu,
 
 	if (ret) {
 		for (i--; i >= 0; i--)
-			rb_erase(&master->streams[i].node, &smmu->streams);
+			if (!RB_EMPTY_NODE(&master->streams[i].node))
+				rb_erase(&master->streams[i].node,
+					 &smmu->streams);
 		kfree(master->streams);
 	}
 	mutex_unlock(&smmu->streams_mutex);
@@ -3589,7 +3594,8 @@ static void arm_smmu_remove_master(struct arm_smmu_master *master)
 
 	mutex_lock(&smmu->streams_mutex);
 	for (i = 0; i < fwspec->num_ids; i++)
-		rb_erase(&master->streams[i].node, &smmu->streams);
+		if (!RB_EMPTY_NODE(&master->streams[i].node))
+			rb_erase(&master->streams[i].node, &smmu->streams);
 	mutex_unlock(&smmu->streams_mutex);
 
 	kfree(master->streams);
Signature · 1 line
2.53.0
author maintainer
#568 lore raw

PATCH 567/990 drm/msm/a5xx: dont read the GPMU registers on GPUs without a GPMU

In reply to Greg Kroah-Hartman

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

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

From: Dmitry Baryshkov <[email protected]>

[ Upstream commit 77e3ffcf69065c4ce92c725540e0b4db14f43ad7 ]

Only a530/a540 have a GPMU. On the other a5xx parts, reading the 0xa800-0xac60 GPMU aperture during a crashdump resets the board -- on sda660 (a512) a GPU hang thus reboots the SoC instead of recovering.

Split the GPMU block into its own array and collect it only when a GPMU is present.

Fixes e20c9284c8f2 ("drm/msm/adreno: Add support for Adreno 510 GPU")
Assisted-by LLM

Patchwork: https://patchwork.freedesktop.org/patch/754867/
Message-ID: <[email protected]>

[ sashal: Replaced upstream's kzalloc_obj(*a5xx_state) with kzalloc(sizeof(*a5xx_state), GFP_KERNEL) because the helper doesn't exist here, and kept the added adreno_gpu declaration. ]
---
 drivers/gpu/drm/msm/adreno/a5xx_gpu.c | 49 +++++++++++++++++++++++++--
 1 file changed, 46 insertions(+), 3 deletions(-)
drivers/gpu/drm/msm/adreno/a5xx_gpu.c +46 -3
index 4a04dc43a8e67..3d123f6e51ab2 100644
@@ -1338,9 +1338,14 @@ static const u32 a5xx_registers[] = {
 	0xE800, 0xE806, 0xE810, 0xE89A, 0xE8A0, 0xE8A4, 0xE8AA, 0xE8EB,
 	0xE900, 0xE905, 0xEB80, 0xEB8F, 0xEBB0, 0xEBB0, 0xEC00, 0xEC05,
 	0xEC08, 0xECE9, 0xECF0, 0xECF0, 0xEA80, 0xEA80, 0xEA82, 0xEAA3,
-	0xEAA5, 0xEAC2, 0xA800, 0xA800, 0xA820, 0xA828, 0xA840, 0xA87D,
-	0XA880, 0xA88D, 0xA890, 0xA8A3, 0xA8D0, 0xA8D8, 0xA8E0, 0xA8F5,
-	0xAC60, 0xAC60, ~0,
+	0xEAA5, 0xEAC2, ~0,
+};
+
+/* GPMU registers, only valid on parts with a GPMU (a530/a540) */
+static const u32 a5xx_gpmu_registers[] = {
+	0xA800, 0xA800, 0xA820, 0xA828, 0xA840, 0xA87D, 0xA880, 0xA88D,
+	0xA890, 0xA8A3, 0xA8D0, 0xA8D8, 0xA8E0, 0xA8F5, 0xAC60, 0xAC60,
+	~0,
 };
 
 static void a5xx_dump(struct msm_gpu *gpu)
@@ -1451,6 +1456,7 @@ struct a5xx_crashdumper {
 struct a5xx_gpu_state {
 	struct msm_gpu_state base;
 	u32 *hlsqregs;
+	u32 *gpmuregs;
 };
 
 static int a5xx_crashdumper_init(struct msm_gpu *gpu,
@@ -1568,8 +1574,30 @@ static void a5xx_gpu_state_get_hlsq_regs(struct msm_gpu *gpu,
 	msm_gem_kernel_put(dumper.bo, gpu->vm);
 }
 
+static void a5xx_gpu_state_get_gpmu_regs(struct msm_gpu *gpu,
+		struct a5xx_gpu_state *a5xx_state)
+{
+	u32 count = 0, pos = 0;
+	int i;
+
+	for (i = 0; a5xx_gpmu_registers[i] != ~0; i += 2)
+		count += a5xx_gpmu_registers[i + 1] - a5xx_gpmu_registers[i] + 1;
+
+	a5xx_state->gpmuregs = kcalloc(count, sizeof(u32), GFP_KERNEL);
+	if (!a5xx_state->gpmuregs)
+		return;
+
+	for (i = 0; a5xx_gpmu_registers[i] != ~0; i += 2) {
+		u32 addr;
+
+		for (addr = a5xx_gpmu_registers[i]; addr <= a5xx_gpmu_registers[i + 1]; addr++)
+			a5xx_state->gpmuregs[pos++] = gpu_read(gpu, addr);
+	}
+}
+
 static struct msm_gpu_state *a5xx_gpu_state_get(struct msm_gpu *gpu)
 {
+	struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu);
 	struct a5xx_gpu_state *a5xx_state = kzalloc(sizeof(*a5xx_state),
 			GFP_KERNEL);
 	bool stalled = !!(gpu_read(gpu, REG_A5XX_RBBM_STATUS3) & BIT(24));
@@ -1585,6 +1613,9 @@ static struct msm_gpu_state *a5xx_gpu_state_get(struct msm_gpu *gpu)
 
 	a5xx_state->base.rbbm_status = gpu_read(gpu, REG_A5XX_RBBM_STATUS);
 
+	if (adreno_is_a530(adreno_gpu) || adreno_is_a540(adreno_gpu))
+		a5xx_gpu_state_get_gpmu_regs(gpu, a5xx_state);
+
 	/*
 	 * Get the HLSQ regs with the help of the crashdumper, but only if
 	 * we are not stalled in an iommu fault (in which case the crashdumper
@@ -1606,6 +1637,7 @@ static void a5xx_gpu_state_destroy(struct kref *kref)
 		struct a5xx_gpu_state, base);
 
 	kfree(a5xx_state->hlsqregs);
+	kfree(a5xx_state->gpmuregs);
 
 	adreno_gpu_state_destroy(state);
 	kfree(a5xx_state);
@@ -1634,6 +1666,17 @@ static void a5xx_show(struct msm_gpu *gpu, struct msm_gpu_state *state,
 
 	adreno_show(gpu, state, p);
 
+	if (a5xx_state->gpmuregs) {
+		u32 o, pos = 0;
+
+		drm_printf(p, "registers-gpmu:\n");
+
+		for (i = 0; a5xx_gpmu_registers[i] != ~0; i += 2)
+			for (o = a5xx_gpmu_registers[i]; o <= a5xx_gpmu_registers[i + 1]; o++)
+				drm_printf(p, "  - { offset: 0x%04x, value: 0x%08x }\n",
+					o << 2, a5xx_state->gpmuregs[pos++]);
+	}
+
 	/* Dump the additional a5xx HLSQ registers */
 	if (!a5xx_state->hlsqregs)
 		return;
Signature · 1 line
2.53.0
author maintainer
#569 lore raw

PATCH 568/990 dlm: validate node weights before building member array

In reply to Greg Kroah-Hartman

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

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

From: Qing Ming <[email protected]>

[ Upstream commit 7f662eb1807ed732ac7d5e119753c8185f241bb8 ]

DLM node weights are parsed as signed integers and copied into the member list. make_member_array() uses their sum as the allocation count, but only positive weights contribute entries to the array. A negative weight can therefore reduce the allocation without reducing the number of writes.

The issue was found through static analysis of the configfs input and member array construction. With two recovery members weighted -31 and 32, the sum is 1, so recovery allocates one int and then writes the positive member's node ID 32 times. A reproducer using dlm_controld and dlm_tool triggered the same report on a KASAN kernel:

  BUG: KASAN: slab-out-of-bounds in dlm_recover_members [dlm]
  Write of size 4 by task dlm_recoverd

  Call Trace:
   dlm_recover_members
   dlm_recoverd
   kthread
   ret_from_fork

Reject negative weights at the configfs input boundary. Also detect overflow when adding non-negative weights to the signed allocation count, and propagate array construction errors to the recovery path.

Fixes e7fd41792fc0 ("[DLM] The core of the DLM for GFS2/CLVM")
Assisted-by Codex:gpt-5
[ sashal: Kept the branch's kmalloc_array() allocation in make_member_array() where upstream context uses kmalloc_objs(), and dropped the early ls_total_weight assignment. ]
---
 fs/dlm/config.c |  9 ++++++++-
 fs/dlm/member.c | 17 +++++++++++------
 2 files changed, 19 insertions(+), 7 deletions(-)
fs/dlm/config.c +8 -1
index 0db5ce43425ca..8ea193017ee98 100644
@@ -857,10 +857,17 @@ static ssize_t node_weight_show(struct config_item *item, char *buf)
 static ssize_t node_weight_store(struct config_item *item, const char *buf,
 				 size_t len)
 {
-	int rc = kstrtoint(buf, 0, &config_item_to_node(item)->weight);
+	struct dlm_node *node = config_item_to_node(item);
+	int weight;
+	int rc;
 
+	rc = kstrtoint(buf, 0, &weight);
 	if (rc)
 		return rc;
+	if (weight < 0)
+		return -EINVAL;
+
+	node->weight = weight;
 	return len;
 }
 
fs/dlm/member.c +11 -6
index c0f557a80a754..c33782235d1b1 100644
@@ -406,7 +406,7 @@ void dlm_clear_members_gone(struct dlm_ls *ls)
 	clear_memb_list(&ls->ls_nodes_gone, NULL);
 }
 
-static void make_member_array(struct dlm_ls *ls)
+static int make_member_array(struct dlm_ls *ls)
 {
 	struct dlm_member *memb;
 	int i, w, x = 0, total = 0, all_zero = 0, *array;
@@ -415,8 +415,8 @@ static void make_member_array(struct dlm_ls *ls)
 	ls->ls_node_array = NULL;
 
 	list_for_each_entry(memb, &ls->ls_nodes, list) {
-		if (memb->weight)
-			total += memb->weight;
+		if (check_add_overflow(total, memb->weight, &total))
+			return -EOVERFLOW;
 	}
 
 	/* all nodes revert to weight of 1 if all have weight 0 */
@@ -426,10 +426,9 @@ static void make_member_array(struct dlm_ls *ls)
 		all_zero = 1;
 	}
 
-	ls->ls_total_weight = total;
 	array = kmalloc_array(total, sizeof(*array), GFP_NOFS);
 	if (!array)
-		return;
+		return -ENOMEM;
 
 	list_for_each_entry(memb, &ls->ls_nodes, list) {
 		if (!all_zero && !memb->weight)
@@ -446,7 +445,10 @@ static void make_member_array(struct dlm_ls *ls)
 			array[x++] = memb->nodeid;
 	}
 
+	ls->ls_total_weight = total;
 	ls->ls_node_array = array;
+
+	return 0;
 }
 
 /* send a status request to all members just to establish comms connections */
@@ -621,7 +623,10 @@ int dlm_recover_members(struct dlm_ls *ls, struct dlm_recover *rv, int *neg_out)
 	}
 	ls->ls_low_nodeid = low;
 
-	make_member_array(ls);
+	error = make_member_array(ls);
+	if (error)
+		return error;
+
 	*neg_out = neg;
 
 	error = ping_members(ls, rv->seq);
Signature · 1 line
2.53.0
author maintainer
#570 lore raw

PATCH 569/990 dmaengine: ste_dma40: Fix cyclic transfer residue

In reply to Greg Kroah-Hartman

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

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

From: Linus Walleij <[email protected]>

[ Upstream commit c80edceff29ee212987c2d2c851b2cb2eb4b477a ]

DMA40 reads residue from the element count of the currently active LLI. For a cyclic transfer this reports at most one period, not the bytes remaining until the cyclic buffer wraps.

Once DMA40 advertises burst granularity, DMAengine PCM uses this residue directly. For a four-period PCM buffer it consequently reports the hardware pointer near three periods after every period interrupt. ALSA eventually stops playback with -EIO although DMA period callbacks continue.

Calculate cyclic residue from the current memory-side hardware pointer instead. Read the destination pointer for capture and the source pointer for playback. Sample the split logical channel pointer coherently and retain the last valid residue during relink transitions.

Make at most three residue sampling attempts: one initial read plus two retries. The retries let transient split-register updates or LLI relink windows settle, while the limit prevents unbounded polling if hardware does not yield a valid pointer.

This avoids counting terminal-count interrupts, which races with hardware advancing to the next LLI and cannot account for coalesced interrupt status. Also reject cyclic periods that expand into multiple LLIs because logical cyclic LLIs each request a terminal-count interrupt and would generate more than one callback per period.

Reject invalid cyclic geometries before dividing or constructing the scatterlist as well.

Fixes 15c606686541 ("dmaengine: ste_dma40: indicate granularity on channels")
Assisted-by LLM
[ sashal: Replaced the kzalloc_objs() allocation call with kcalloc() for the scatterlist in dma40_prep_dma_cyclic(), since the newer helper is missing here. ]
---
 drivers/dma/ste_dma40.c | 106 ++++++++++++++++++++++++++++++++++++++--
 1 file changed, 101 insertions(+), 5 deletions(-)
drivers/dma/ste_dma40.c +101 -5
index 21469034495d7..53e56b4be3fca 100644
@@ -69,6 +69,9 @@ struct stedma40_platform_data {
 /* Maximum iterations taken before giving up suspending a channel */
 #define D40_SUSPEND_MAX_IT 500
 
+/* Maximum attempts to sample a stable cyclic residue position */
+#define D40_RESIDUE_MAX_ATTEMPTS 3
+
 /* Milliseconds */
 #define DMA40_AUTOSUSPEND_DELAY	100
 
@@ -368,6 +371,9 @@ struct d40_lli_pool {
  * @lli_len: Number of llis of current descriptor.
  * @lli_current: Number of transferred llis.
  * @lcla_alloc: Number of LCLA entries allocated.
+ * @cyclic_dma_addr: Start address of the cyclic buffer.
+ * @cyclic_buf_len: Length of the cyclic buffer.
+ * @cyclic_residue: Last valid cyclic residue sample.
  * @txd: DMA engine struct. Used for among other things for communication
  * during a transfer.
  * @node: List entry.
@@ -386,6 +392,9 @@ struct d40_desc {
 	int				 lli_len;
 	int				 lli_current;
 	int				 lcla_alloc;
+	dma_addr_t			 cyclic_dma_addr;
+	size_t				 cyclic_buf_len;
+	size_t				 cyclic_residue;
 
 	struct dma_async_tx_descriptor	 txd;
 	struct list_head		 node;
@@ -1412,6 +1421,64 @@ static u32 d40_residue(struct d40_chan *d40c)
 	return num_elt * d40c->dma_cfg.dst_info.data_width;
 }
 
+static bool d40_current_addr(struct d40_chan *d40c, dma_addr_t *addr)
+{
+	bool dst = d40c->dma_cfg.dir == DMA_DEV_TO_MEM;
+	void __iomem *high_reg;
+	void __iomem *low_reg;
+	u32 low;
+	u32 high;
+	u32 check;
+	int i;
+
+	if (chan_is_physical(d40c)) {
+		*addr = readl(chan_base(d40c) +
+			      (dst ? D40_CHAN_REG_SDPTR : D40_CHAN_REG_SSPTR));
+		return true;
+	}
+
+	if (dst) {
+		low_reg = &d40c->lcpa->lcsp2;
+		high_reg = &d40c->lcpa->lcsp3;
+	} else {
+		low_reg = &d40c->lcpa->lcsp0;
+		high_reg = &d40c->lcpa->lcsp1;
+	}
+
+	for (i = 0; i < D40_RESIDUE_MAX_ATTEMPTS; i++) {
+		high = readl(high_reg) & D40_MEM_LCSP1_SPTR_MASK;
+		low = readl(low_reg) & D40_MEM_LCSP0_SPTR_MASK;
+		check = readl(high_reg) & D40_MEM_LCSP1_SPTR_MASK;
+		if (high == check) {
+			*addr = low | high;
+			return true;
+		}
+	}
+
+	return false;
+}
+
+static bool d40_cyclic_offset(struct d40_chan *d40c, struct d40_desc *d40d,
+			      size_t *offset)
+{
+	dma_addr_t current_addr;
+	dma_addr_t current_offset;
+	int i;
+
+	for (i = 0; i < D40_RESIDUE_MAX_ATTEMPTS; i++) {
+		if (!d40_current_addr(d40c, &current_addr))
+			continue;
+
+		current_offset = current_addr - d40d->cyclic_dma_addr;
+		if (current_offset <= d40d->cyclic_buf_len) {
+			*offset = current_offset;
+			return true;
+		}
+	}
+
+	return false;
+}
+
 static bool d40_tx_is_linked(struct d40_chan *d40c)
 {
 	bool is_link;
@@ -2202,15 +2269,26 @@ static bool d40_is_paused(struct d40_chan *d40c)
 
 }
 
-static u32 stedma40_residue(struct dma_chan *chan)
+static u32 stedma40_residue(struct dma_chan *chan, dma_cookie_t cookie)
 {
 	struct d40_chan *d40c =
 		container_of(chan, struct d40_chan, chan);
+	struct d40_desc *d40d;
+	size_t offset;
 	u32 bytes_left;
 	unsigned long flags;
 
 	spin_lock_irqsave(&d40c->lock, flags);
-	bytes_left = d40_residue(d40c);
+	d40d = d40_first_active_get(d40c);
+	if (d40d && d40d->txd.cookie == cookie && d40d->cyclic &&
+	    d40d->cyclic_buf_len) {
+		if (d40_cyclic_offset(d40c, d40d, &offset))
+			d40d->cyclic_residue = d40d->cyclic_buf_len - offset;
+		bytes_left = d40d->cyclic_residue;
+	} else {
+		bytes_left = d40_residue(d40c);
+	}
+
 	spin_unlock_irqrestore(&d40c->lock, flags);
 
 	return bytes_left;
@@ -2346,8 +2424,13 @@ d40_prep_sg(struct dma_chan *dchan, struct scatterlist *sg_src,
 	if (desc == NULL)
 		goto unlock;
 
-	if (sg_next(&sg_src[sg_len - 1]) == sg_src)
+	if (sg_next(&sg_src[sg_len - 1]) == sg_src) {
 		desc->cyclic = true;
+		if (desc->lli_len != sg_len) {
+			chan_err(chan, "Cyclic periods must fit in one LLI\n");
+			goto free_desc;
+		}
+	}
 
 	src_dev_addr = 0;
 	dst_dev_addr = 0;
@@ -2630,11 +2713,18 @@ dma40_prep_dma_cyclic(struct dma_chan *chan, dma_addr_t dma_addr,
 		     size_t buf_len, size_t period_len,
 		     enum dma_transfer_direction direction, unsigned long flags)
 {
-	unsigned int periods = buf_len / period_len;
+	unsigned int periods;
 	struct dma_async_tx_descriptor *txd;
+	struct d40_desc *desc;
 	struct scatterlist *sg;
+	dma_addr_t buf_addr = dma_addr;
 	int i;
 
+	if (!buf_len || !period_len || buf_len % period_len)
+		return NULL;
+
+	periods = buf_len / period_len;
+
 	sg = kcalloc(periods + 1, sizeof(struct scatterlist), GFP_NOWAIT);
 	if (!sg)
 		return NULL;
@@ -2649,6 +2739,12 @@ dma40_prep_dma_cyclic(struct dma_chan *chan, dma_addr_t dma_addr,
 
 	txd = d40_prep_sg(chan, sg, sg, periods, direction,
 			  DMA_PREP_INTERRUPT);
+	if (txd) {
+		desc = container_of(txd, struct d40_desc, txd);
+		desc->cyclic_dma_addr = buf_addr;
+		desc->cyclic_buf_len = buf_len;
+		desc->cyclic_residue = buf_len;
+	}
 
 	kfree(sg);
 
@@ -2669,7 +2765,7 @@ static enum dma_status d40_tx_status(struct dma_chan *chan,
 
 	ret = dma_cookie_status(chan, cookie, txstate);
 	if (ret != DMA_COMPLETE && txstate)
-		dma_set_residue(txstate, stedma40_residue(chan));
+		dma_set_residue(txstate, stedma40_residue(chan, cookie));
 
 	if (d40_is_paused(d40c))
 		ret = DMA_PAUSED;
Signature · 1 line
2.53.0
author maintainer
#571 lore raw

PATCH 570/990 dmaengine: ste_dma40: Recover coalesced cyclic callbacks

In reply to Greg Kroah-Hartman

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

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

From: Linus Walleij <[email protected]>

[ Upstream commit db28400d92cd97005065dad230b8a5d72ab121cb ]

DMA40 has one terminal-count status bit per channel, so cyclic period interrupts can coalesce.

Use the memory-side pointer displacement to queue the minimum observable number of callbacks. If sampling fails, queue one callback and invalidate the saved position; the next successful sample resynchronizes without recounting it.

The pointer is modulo the cyclic buffer: a displacement of d periods can mean d plus n complete iterations of the buffer. Report d, so the driver could have missed n iterations of the buffer; DMA40 has no counter to recover them. For an unchanged pointer, report one callback rather than risk a spurious full-buffer burst.

This condition has not been seen in practice and is only a product of review comments that the buffer can miss interrupts.

The preceding cyclic-residue fix ensures that every cyclic period fits in one LLI, so each boundary corresponds to one client callback.

Fixes 0c842b551063 ("dma40: cyclic xfer support")
Assisted-by LLM
---
 drivers/dma/ste_dma40.c | 69 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 68 insertions(+), 1 deletion(-)
drivers/dma/ste_dma40.c +68 -1
index 53e56b4be3fca..2c83eb05faa16 100644
@@ -374,11 +374,14 @@ struct d40_lli_pool {
  * @cyclic_dma_addr: Start address of the cyclic buffer.
  * @cyclic_buf_len: Length of the cyclic buffer.
  * @cyclic_residue: Last valid cyclic residue sample.
+ * @cyclic_period_len: Length of one cyclic period.
+ * @cyclic_callback_pos: Position after the callbacks already queued.
  * @txd: DMA engine struct. Used for among other things for communication
  * during a transfer.
  * @node: List entry.
  * @is_in_client_list: true if the client owns this descriptor.
  * @cyclic: true if this is a cyclic job
+ * @cyclic_callback_pos_valid: Whether cyclic_callback_pos is reliable.
  *
  * This descriptor is used for both logical and physical transfers.
  */
@@ -395,12 +398,15 @@ struct d40_desc {
 	dma_addr_t			 cyclic_dma_addr;
 	size_t				 cyclic_buf_len;
 	size_t				 cyclic_residue;
+	size_t				 cyclic_period_len;
+	size_t				 cyclic_callback_pos;
 
 	struct dma_async_tx_descriptor	 txd;
 	struct list_head		 node;
 
 	bool				 is_in_client_list;
 	bool				 cyclic;
+	bool				 cyclic_callback_pos_valid;
 };
 
 /**
@@ -1479,6 +1485,61 @@ static bool d40_cyclic_offset(struct d40_chan *d40c, struct d40_desc *d40d,
 	return false;
 }
 
+static unsigned int d40_cyclic_periods_elapsed(struct d40_chan *d40c,
+					       struct d40_desc *d40d)
+{
+	size_t current_pos;
+	size_t delta;
+	size_t offset;
+	unsigned int periods;
+
+	if (!d40d->cyclic_period_len)
+		return 1;
+
+	if (!d40_cyclic_offset(d40c, d40d, &offset)) {
+		d40d->cyclic_callback_pos_valid = false;
+		return 1;
+	}
+
+	current_pos = rounddown(offset, d40d->cyclic_period_len);
+	if (!d40_residue(d40c) && current_pos != offset)
+		current_pos += d40d->cyclic_period_len;
+	if (current_pos == d40d->cyclic_buf_len)
+		current_pos = 0;
+
+	if (!d40d->cyclic_callback_pos_valid) {
+		/*
+		 * The previous interrupt was reported without a pointer
+		 * sample. Resynchronize without using the stale position,
+		 * which would count that callback again.
+		 */
+		d40d->cyclic_callback_pos = current_pos;
+		d40d->cyclic_callback_pos_valid = true;
+		return 1;
+	}
+
+	/*
+	 * The pointer wraps with the cyclic buffer, so its displacement is
+	 * only the minimum number of elapsed periods. Complete buffer laps
+	 * are not observable.
+	 */
+	delta = (current_pos + d40d->cyclic_buf_len -
+		 d40d->cyclic_callback_pos) % d40d->cyclic_buf_len;
+	periods = delta / d40d->cyclic_period_len;
+	if (!periods) {
+		/*
+		 * The TC status is a single latched bit. An unchanged pointer
+		 * cannot distinguish a complete lap from a repeated interrupt,
+		 * so do not amplify it into a buffer's worth of callbacks.
+		 */
+		periods = 1;
+	}
+
+	d40d->cyclic_callback_pos = current_pos;
+
+	return periods;
+}
+
 static bool d40_tx_is_linked(struct d40_chan *d40c)
 {
 	bool is_link;
@@ -1626,6 +1687,7 @@ static struct d40_desc *d40_queue_start(struct d40_chan *d40c)
 static void dma_tc_handle(struct d40_chan *d40c)
 {
 	struct d40_desc *d40d;
+	unsigned int callbacks = 1;
 
 	/* Get first active entry from list */
 	d40d = d40_first_active_get(d40c);
@@ -1650,6 +1712,8 @@ static void dma_tc_handle(struct d40_chan *d40c)
 			if (d40d->lli_current == d40d->lli_len)
 				d40d->lli_current = 0;
 		}
+
+		callbacks = d40_cyclic_periods_elapsed(d40c, d40d);
 	} else {
 		d40_lcla_free_all(d40c, d40d);
 
@@ -1670,7 +1734,7 @@ static void dma_tc_handle(struct d40_chan *d40c)
 		}
 	}
 
-	d40c->pending_tx++;
+	d40c->pending_tx += callbacks;
 	tasklet_schedule(&d40c->tasklet);
 
 }
@@ -2744,6 +2808,9 @@ dma40_prep_dma_cyclic(struct dma_chan *chan, dma_addr_t dma_addr,
 		desc->cyclic_dma_addr = buf_addr;
 		desc->cyclic_buf_len = buf_len;
 		desc->cyclic_residue = buf_len;
+		desc->cyclic_period_len = period_len;
+		desc->cyclic_callback_pos = 0;
+		desc->cyclic_callback_pos_valid = true;
 	}
 
 	kfree(sg);
Signature · 1 line
2.53.0
author maintainer
#572 lore raw

PATCH 571/990 wifi: mt76: mt7996: free the WTBL index if a link allocation fails

In reply to Greg Kroah-Hartman

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

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

From: Felix Fietkau <[email protected]>

[ Upstream commit 36f1934a2bf04f355e748c68ba7f7cbb5e6950fc ]

mt7996_mac_sta_init_link() takes a WTBL index from wcid_mask before it allocates the msta_link of a link other than the first one. If that allocation fails, the function returns -ENOMEM and the index stays set in wcid_mask, so no later station can use it.

Return the index to wcid_mask on that error.

Fixes dd82a9e02c05 ("wifi: mt76: mt7996: Rely on mt7996_sta_link in sta_add/sta_remove callbacks")
[ sashal: Kept the older kzalloc(sizeof(*msta_link), GFP_KERNEL) allocation instead of kzalloc_obj(*msta_link) as the context line, then applied the same fix on top. ]
---
 drivers/net/wireless/mediatek/mt76/mt7996/main.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/net/wireless/mediatek/mt76/mt7996/main.c +3 -1
index fa0fe117e8f30..02ffd5b1c0ca3 100644
@@ -1056,8 +1056,10 @@ mt7996_mac_sta_init_link(struct mt7996_dev *dev,
 		mt7996_sta_init_txq_wcid(sta, idx);
 	} else {
 		msta_link = kzalloc(sizeof(*msta_link), GFP_KERNEL);
-		if (!msta_link)
+		if (!msta_link) {
+			mt76_wcid_mask_clear(dev->mt76.wcid_mask, idx);
 			return -ENOMEM;
+		}
 
 		if (msta->seclink_id == msta->deflink_id &&
 		    (sta->valid_links & ~BIT(msta->deflink_id)))
Signature · 1 line
2.53.0
author maintainer
#573 lore raw

PATCH 572/990 wifi: mt76: mt7921: fix of_node reference leaks in regd update

In reply to Greg Kroah-Hartman

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

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

From: Felix Fietkau <[email protected]>

[ Upstream commit 2f209a8dca88507bc094de370e582adefc55723e ]

mt7921_regd_channel_update() and __mt7921_mcu_set_clc() never release the nodes returned by mt76_find_power_limits_node(), of_get_child_by_name() and mt76_find_channel_node(). Each regulatory domain change and each CLC update on a device with DT power limits leaks these references.

Release every node after use. This relies on mt76_find_power_limits_node() also returning a reference for the fallback node, which it does since commit 3a62c9f7ec3d ("wifi: mt76:
Fix of_node reference leak in mt76_get_rate_power_limits()").

Fixes 09382d8f8641 ("wifi: mt76: mt7921: update the channel usage when the regd domain changed")
[ sashal: Applied the fix inside mt7921_regd_channel_update() in init.c (no regd.c here) and inlined the mt7921_regd_dt_has_channel() helper, with no goto out on the 5 GHz check. ]
---
 .../net/wireless/mediatek/mt76/mt7921/init.c  | 31 ++++++++++++++-----
 .../net/wireless/mediatek/mt76/mt7921/mcu.c   |  7 ++++-
 2 files changed, 29 insertions(+), 9 deletions(-)
drivers/net/wireless/mediatek/mt76/mt7921/init.c +23 -8
index b9098a7331b1a..67a3b3dcf60a2 100644
@@ -67,7 +67,7 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev)
 	(!(dev->phy.clc_chan_conf & BIT(idx)) && (cfreq) >= (sfreq) && (cfreq) <= (efreq))
 	struct ieee80211_supported_band *sband;
 	struct mt76_dev *mdev = &dev->mt76;
-	struct device_node *np, *band_np;
+	struct device_node *np, *band_np, *chan_np;
 	struct ieee80211_channel *ch;
 	int i, cfreq;
 
@@ -79,28 +79,39 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev)
 		ch = &sband->channels[i];
 		cfreq = ch->center_freq;
 
-		if (np && (!band_np || !mt76_find_channel_node(band_np, ch))) {
-			ch->flags |= IEEE80211_CHAN_DISABLED;
-			continue;
+		if (np) {
+			chan_np = band_np ?
+				  mt76_find_channel_node(band_np, ch) : NULL;
+			of_node_put(chan_np);
+			if (!chan_np) {
+				ch->flags |= IEEE80211_CHAN_DISABLED;
+				continue;
+			}
 		}
 
 		/* UNII-4 */
 		if (IS_UNII_INVALID(0, 5845, 5925))
 			ch->flags |= IEEE80211_CHAN_DISABLED;
 	}
+	of_node_put(band_np);
 
 	sband = wiphy->bands[NL80211_BAND_6GHZ];
 	if (!sband)
-		return;
+		goto out;
 
 	band_np = np ? of_get_child_by_name(np, "txpower-6g") : NULL;
 	for (i = 0; i < sband->n_channels; i++) {
 		ch = &sband->channels[i];
 		cfreq = ch->center_freq;
 
-		if (np && (!band_np || !mt76_find_channel_node(band_np, ch))) {
-			ch->flags |= IEEE80211_CHAN_DISABLED;
-			continue;
+		if (np) {
+			chan_np = band_np ?
+				  mt76_find_channel_node(band_np, ch) : NULL;
+			of_node_put(chan_np);
+			if (!chan_np) {
+				ch->flags |= IEEE80211_CHAN_DISABLED;
+				continue;
+			}
 		}
 
 		/* UNII-5/6/7/8 */
@@ -110,6 +121,10 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev)
 		    IS_UNII_INVALID(4, 6875, 7125))
 			ch->flags |= IEEE80211_CHAN_DISABLED;
 	}
+	of_node_put(band_np);
+
+out:
+	of_node_put(np);
 }
 
 void mt7921_regd_update(struct mt792x_dev *dev)
drivers/net/wireless/mediatek/mt76/mt7921/mcu.c +6 -1
index 7363a553a007d..5e6e3cb4d5e15 100644
@@ -3,6 +3,7 @@
 
 #include <linux/fs.h>
 #include <linux/firmware.h>
+#include <linux/of.h>
 #include "mt7921.h"
 #include "mcu.h"
 #include "../mt76_connac2_mac.h"
@@ -1361,6 +1362,7 @@ int __mt7921_mcu_set_clc(struct mt792x_dev *dev, u8 *alpha2,
 		.acpi_conf = mt792x_acpi_get_flags(&dev->phy),
 		.mtcl_conf = mt792x_acpi_get_mtcl_conf(&dev->phy, alpha2),
 	};
+	struct device_node *np;
 	int ret, valid_cnt = 0;
 	u32 buf_len = 0;
 	u8 *pos;
@@ -1370,8 +1372,11 @@ int __mt7921_mcu_set_clc(struct mt792x_dev *dev, u8 *alpha2,
 
 	if (dev->phy.chip_cap & MT792x_CHIP_CAP_CLC_EVT_EN)
 		req.cap |= CLC_CAP_EVT_EN;
-	if (mt76_find_power_limits_node(&dev->mt76))
+
+	np = mt76_find_power_limits_node(&dev->mt76);
+	if (np)
 		req.cap |= CLC_CAP_DTS_EN;
+	of_node_put(np);
 
 	buf_len = le32_to_cpu(clc->len) - sizeof(*clc);
 	pos = clc->data;
Signature · 1 line
2.53.0
author maintainer
#574 lore raw

PATCH 573/990 drm/amd/display: declare amdgpu_dm_atomic_state_template as an event class

In reply to Greg Kroah-Hartman

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

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

From: Melissa Wen <[email protected]>

[ Upstream commit 6c4f8c5cc00326f6c709bff0d640d504c90862ca ]

Don't create an amdgpu_dm_atomic_state_template event since this is just a template. Declare the template as an event class that will be used by actual event tracers.

Fixes e8a982355f96 ("drm/amd/display: Add tracepoint for amdgpu_dm")
[ sashal: Replaced struct drm_atomic_commit with struct drm_atomic_state in TP_PROTO and __field, since the rename isn't present in this tree. ]
---
 .../amd/display/amdgpu_dm/amdgpu_dm_trace.h   | 56 +++++++++----------
 1 file changed, 26 insertions(+), 30 deletions(-)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_trace.h +26 -30
index a8f52c35a94d3..ec8b39b8342fb 100644
@@ -311,36 +311,32 @@ DEFINE_EVENT(amdgpu_dm_plane_state_template, amdgpu_dm_atomic_update_cursor,
 	     TP_PROTO(const struct drm_plane_state *state),
 	     TP_ARGS(state));
 
-TRACE_EVENT(amdgpu_dm_atomic_state_template,
-	    TP_PROTO(const struct drm_atomic_state *state),
-	    TP_ARGS(state),
-
-	    TP_STRUCT__entry(
-			     __field(const struct drm_atomic_state *, state)
-			     __field(bool, allow_modeset)
-			     __field(bool, legacy_cursor_update)
-			     __field(bool, async_update)
-			     __field(bool, duplicated)
-			     __field(int, num_connector)
-			     __field(int, num_private_objs)
-	    ),
-
-	    TP_fast_assign(
-			   __entry->state = state;
-			   __entry->allow_modeset = state->allow_modeset;
-			   __entry->legacy_cursor_update = state->legacy_cursor_update;
-			   __entry->async_update = state->async_update;
-			   __entry->duplicated = state->duplicated;
-			   __entry->num_connector = state->num_connector;
-			   __entry->num_private_objs = state->num_private_objs;
-	    ),
-
-	    TP_printk("state=%p allow_modeset=%d legacy_cursor_update=%d "
-		      "async_update=%d duplicated=%d num_connector=%d "
-		      "num_private_objs=%d",
-		      __entry->state, __entry->allow_modeset, __entry->legacy_cursor_update,
-		      __entry->async_update, __entry->duplicated, __entry->num_connector,
-		      __entry->num_private_objs)
+DECLARE_EVENT_CLASS(amdgpu_dm_atomic_state_template,
+		    TP_PROTO(const struct drm_atomic_state *state),
+		    TP_ARGS(state),
+		    TP_STRUCT__entry(__field(const struct drm_atomic_state *, state)
+				     __field(bool, allow_modeset)
+				     __field(bool, legacy_cursor_update)
+				     __field(bool, async_update)
+				     __field(bool, duplicated)
+				     __field(int, num_connector)
+				     __field(int, num_private_objs)
+		    ),
+		    TP_fast_assign(__entry->state = state;
+				   __entry->allow_modeset = state->allow_modeset;
+				   __entry->legacy_cursor_update = state->legacy_cursor_update;
+				   __entry->async_update = state->async_update;
+				   __entry->duplicated = state->duplicated;
+				   __entry->num_connector = state->num_connector;
+				   __entry->num_private_objs = state->num_private_objs;
+		    ),
+		    TP_printk("state=%p allow_modeset=%d legacy_cursor_update=%d "
+			      "async_update=%d duplicated=%d num_connector=%d "
+			      "num_private_objs=%d",
+			      __entry->state, __entry->allow_modeset,
+			      __entry->legacy_cursor_update, __entry->async_update,
+			      __entry->duplicated, __entry->num_connector,
+			      __entry->num_private_objs)
 );
 
 DEFINE_EVENT(amdgpu_dm_atomic_state_template, amdgpu_dm_atomic_commit_tail_begin,
Signature · 1 line
2.53.0
author maintainer
#575 lore raw

PATCH 574/990 fs/ntfs3: check return values in indx_delete_entry()

In reply to Greg Kroah-Hartman

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

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

From: Dmitry Morgun <[email protected]>

[ Upstream commit 131f7d7abf0f10edc6ea6b032f8a3908bdb13ce8 ]

When the index tree collapses down to an empty root, indx_delete_entry() calls attr_set_size() and ni_remove_attr() for both ATTR_ALLOC and ATTR_BITMAP, but their return values are overwritten by the following call without being checked.

In most other call sites of these functions the return value is checked, so add the same checks here in case an error at this point is meaningful.

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

Fixes 82cae269cfa9 ("fs/ntfs3: Add initialization of super block")
[ sashal: added the missing NULL argument to both attr_set_size() calls to match this branch's older function prototype. ]
---
 fs/ntfs3/index.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
fs/ntfs3/index.c +10 -0
index 97cbe176a83e5..88a5f336d9040 100644
@@ -2691,18 +2691,28 @@ int indx_delete_entry(struct ntfs_index *indx, struct ntfs_inode *ni,
 
 		err = attr_set_size(ni, ATTR_ALLOC, in->name, in->name_len,
 				    &indx->alloc_run, 0, NULL, false, NULL);
+		if (err)
+			goto out;
+
 		if (in->name == I30_NAME)
 			i_size_write(&ni->vfs_inode, 0);
 
 		err = ni_remove_attr(ni, ATTR_ALLOC, in->name, in->name_len,
 				     false, NULL);
 		run_close(&indx->alloc_run);
+		if (err)
+			goto out;
 
 		err = attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len,
 				    &indx->bitmap_run, 0, NULL, false, NULL);
+		if (err)
+			goto out;
+
 		err = ni_remove_attr(ni, ATTR_BITMAP, in->name, in->name_len,
 				     false, NULL);
 		run_close(&indx->bitmap_run);
+		if (err)
+			goto out;
 
 		root = indx_get_root(indx, ni, &attr, &mi);
 		if (!root) {
Signature · 1 line
2.53.0
author maintainer
#576 lore raw

PATCH 575/990 net: stmmac: fix TX coalesce race and div-by-zero in XDP/legacy path

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit 237782c3d416b392a12642f32959e9d3c94e0c26 ]

tx_coal_frames[] is written by ethtool (stmmac_set_coalesce) and read locklessly from the TX fast path (stmmac_xmit, stmmac_tso_xmit, stmmac_xdp_xmit_zc and stmmac_xdp_xmit_xdpf), so pair every access with READ_ONCE()/WRITE_ONCE() to mark the intentional data race and read a consistent value into a local variable.

Moreover, ethtool allows disabling TX coalescing by setting tx_max_coalesced_frames to 0: guard the modulo operation in stmmac_xdp_xmit_xdpf() against a zero tx_coal_frames[queue] to avoid a division by zero.

Both issues were found by code inspection while extending the XDP TX path with multi-buff support, and neither has ever been triggered, so they are only theoretical. Tested on the Qualcomm RB3-gen2 board.

Fixes db2f2842e6f5 ("net: stmmac: add per-queue TX & RX coalesce ethtool support")
Fixes be8b38a722e6 ("net: stmmac: Add support for XDP_TX action")
[ sashal: Dropped the duplicate pay_len, mss, queue declaration and kept this branch's local variable names (des, has_vlan, set_ic, proto_hdr_len) instead of upstream's declaration changes. ]
---
 .../ethernet/stmicro/stmmac/stmmac_ethtool.c  | 11 ++---
 .../net/ethernet/stmicro/stmmac/stmmac_main.c | 42 ++++++++-----------
 2 files changed, 24 insertions(+), 29 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c +6 -5
index 741e3864f5094..3d501be64619f 100644
@@ -832,7 +832,8 @@ static int __stmmac_get_coalesce(struct net_device *dev,
 
 	if (queue < tx_cnt) {
 		ec->tx_coalesce_usecs = priv->tx_coal_timer[queue];
-		ec->tx_max_coalesced_frames = priv->tx_coal_frames[queue];
+		ec->tx_max_coalesced_frames =
+			READ_ONCE(priv->tx_coal_frames[queue]);
 	} else {
 		ec->tx_coalesce_usecs = 0;
 		ec->tx_max_coalesced_frames = 0;
@@ -921,14 +922,14 @@ static int __stmmac_set_coalesce(struct net_device *dev,
 		int i;
 
 		for (i = 0; i < tx_cnt; i++) {
-			priv->tx_coal_frames[i] =
-				ec->tx_max_coalesced_frames;
+			WRITE_ONCE(priv->tx_coal_frames[i],
+				   ec->tx_max_coalesced_frames);
 			priv->tx_coal_timer[i] =
 				ec->tx_coalesce_usecs;
 		}
 	} else if (queue < tx_cnt) {
-		priv->tx_coal_frames[queue] =
-			ec->tx_max_coalesced_frames;
+		WRITE_ONCE(priv->tx_coal_frames[queue],
+			   ec->tx_max_coalesced_frames);
 		priv->tx_coal_timer[queue] =
 			ec->tx_coalesce_usecs;
 	}
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +18 -24

111 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#577 lore raw

PATCH 576/990 ALSA: pcmtest: Fix leak at probe error

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit d0f2ca62e89f3c666d0ec203eaa23b8d965e5443 ]

When an error happens at probe of pcmtest driver before snd_card_register() succeeds, we have to release the card explicitly, but it's not done, leading to a potential memory leak.

Also, pcmtest driver manages struct pcmtst object unnecessarily complicatedly by a dynamic allocation and release.

This patch fixes and cleans up the resource management:
- Use card's private_data allocation for struct sndpcmtst at the card creation, which is released automatically together with the card
- Since the allocation of pcmtest is gone, snd_pcmtst_create() is rather pointless, so just directly calling snd_pcmtst_new_pcm()
- Use the new auto-clean mechanism to handle the error case at probe.
- Many release handlers became superfluous and dropped

In the end we got a good amount of code reduction.

Fixes 315a3d57c64c ("ALSA: Implement the new Virtual PCM Test Driver")
[ sashal: Dropped the deleted snd_pcmtst_create() function in full, including its older kzalloc(sizeof(*pcmtst), GFP_KERNEL) line where upstream had kzalloc_obj(*pcmtst), since the branch lacks that helper. ]
---
 sound/drivers/pcmtest.c | 66 +++++++----------------------------------
 1 file changed, 10 insertions(+), 56 deletions(-)
sound/drivers/pcmtest.c +10 -56
index b63df0623c73f..026bc53211d77 100644
@@ -465,20 +465,6 @@ static snd_pcm_uframes_t snd_pcmtst_pcm_pointer(struct snd_pcm_substream *substr
 	return bytes_to_frames(substream->runtime, v_iter->buf_pos);
 }
 
-static int snd_pcmtst_free(struct pcmtst *pcmtst)
-{
-	if (!pcmtst)
-		return 0;
-	kfree(pcmtst);
-	return 0;
-}
-
-// These callbacks are required, but empty - all freeing occurs in pdev_remove
-static int snd_pcmtst_dev_free(struct snd_device *device)
-{
-	return 0;
-}
-
 static void pcmtst_pdev_release(struct device *dev)
 {
 }
@@ -582,40 +568,9 @@ static int snd_pcmtst_new_pcm(struct pcmtst *pcmtst)
 	return err;
 }
 
-static int snd_pcmtst_create(struct snd_card *card, struct platform_device *pdev,
-			     struct pcmtst **r_pcmtst)
-{
-	struct pcmtst *pcmtst;
-	int err;
-	static const struct snd_device_ops ops = {
-		.dev_free = snd_pcmtst_dev_free,
-	};
-
-	pcmtst = kzalloc(sizeof(*pcmtst), GFP_KERNEL);
-	if (!pcmtst)
-		return -ENOMEM;
-	pcmtst->card = card;
-	pcmtst->pdev = pdev;
-
-	err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, pcmtst, &ops);
-	if (err < 0)
-		goto _err_free_chip;
-
-	err = snd_pcmtst_new_pcm(pcmtst);
-	if (err < 0)
-		goto _err_free_chip;
-
-	*r_pcmtst = pcmtst;
-	return 0;
-
-_err_free_chip:
-	snd_pcmtst_free(pcmtst);
-	return err;
-}
-
 static int pcmtst_probe(struct platform_device *pdev)
 {
-	struct snd_card *card;
+	struct snd_card *card __free(snd_card_free) = NULL;
 	struct pcmtst *pcmtst;
 	int err;
 
@@ -623,10 +578,16 @@ static int pcmtst_probe(struct platform_device *pdev)
 	if (err)
 		return err;
 
-	err = snd_devm_card_new(&pdev->dev, index, id, THIS_MODULE, 0, &card);
+	err = snd_devm_card_new(&pdev->dev, index, id, THIS_MODULE,
+				sizeof(*pcmtst), &card);
 	if (err < 0)
 		return err;
-	err = snd_pcmtst_create(card, pdev, &pcmtst);
+
+	pcmtst = card->private_data;
+	pcmtst->card = card;
+	pcmtst->pdev = pdev;
+
+	err = snd_pcmtst_new_pcm(pcmtst);
 	if (err < 0)
 		return err;
 
@@ -639,17 +600,11 @@ static int pcmtst_probe(struct platform_device *pdev)
 		return err;
 
 	platform_set_drvdata(pdev, pcmtst);
+	card = NULL; /* probe succeeded, don't release as error */
 
 	return 0;
 }
 
-static void pdev_remove(struct platform_device *pdev)
-{
-	struct pcmtst *pcmtst = platform_get_drvdata(pdev);
-
-	snd_pcmtst_free(pcmtst);
-}
-
 static struct platform_device pcmtst_pdev = {
 	.name =		"pcmtest",
 	.dev.release =	pcmtst_pdev_release,
@@ -657,7 +612,6 @@ static struct platform_device pcmtst_pdev = {
 
 static struct platform_driver pcmtst_pdrv = {
 	.probe =	pcmtst_probe,
-	.remove =	pdev_remove,
 	.driver =	{
 		.name = "pcmtest",
 	},
Signature · 1 line
2.53.0
author maintainer
#578 lore raw

PATCH 577/990 ALSA: aloop: Avoid a bad mixure of guard() and goto

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit f7faf5d9b5668919cae84a6247f8f7b4e2c0227c ]

The rewrite of aloop driver code using guard() leaded to a mixture of guard() and some goto; although it currently works, it isn't really a good match.

For avoiding the bad match, just move the code using goto into a function and wrap it with guard().

Fixes ebd9b6c91d4e ("ALSA: aloop: Use guard() for mutex locks")
[ sashal: Kept the existing kzalloc(sizeof(*dpcm), GFP_KERNEL) call in the context instead of upstream's kzalloc_obj(*dpcm), since the file still uses plain kzalloc. ]
---
 sound/drivers/aloop.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
sound/drivers/aloop.c +9 -2
index 93ac63edfb975..c11648f431096 100644
@@ -1276,7 +1276,7 @@ static const struct loopback_ops loopback_snd_timer_ops = {
 	.dpcm_info = loopback_snd_timer_dpcm_info,
 };
 
-static int loopback_open(struct snd_pcm_substream *substream)
+static int __loopback_open(struct snd_pcm_substream *substream)
 {
 	struct snd_pcm_runtime *runtime = substream->runtime;
 	struct loopback *loopback = substream->private_data;
@@ -1285,7 +1285,6 @@ static int loopback_open(struct snd_pcm_substream *substream)
 	int err = 0;
 	int dev = get_cable_index(substream);
 
-	guard(mutex)(&loopback->cable_lock);
 	dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
 	if (!dpcm)
 		return -ENOMEM;
@@ -1375,6 +1374,14 @@ static int loopback_open(struct snd_pcm_substream *substream)
 	return err;
 }
 
+static int loopback_open(struct snd_pcm_substream *substream)
+{
+	struct loopback *loopback = substream->private_data;
+
+	guard(mutex)(&loopback->cable_lock);
+	return __loopback_open(substream);
+}
+
 static int loopback_close(struct snd_pcm_substream *substream)
 {
 	struct loopback *loopback = substream->private_data;
Signature · 1 line
2.53.0
author maintainer
#579 lore raw

PATCH 578/990 net: macb: configure ENST registers for all queues

In reply to Greg Kroah-Hartman

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

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

From: Vineeth Karumanchi <[email protected]>

[ Upstream commit 04a943067baa670fef3c1424ea616a2ed87d3d19 ]

When a taprio config only covered a subset of queues, the driver programmed the ENST registers only for the queues named in the config and left the remaining queues holding stale register values. This produced an inconsistent hardware setup that affected the scheduling of the configured queues.

This was observed on a GEM instance with four hardware queues, all enabled:

Initial configuration:
- All four queues are enabled.
- enst_on_time_qX registers are left at their reset value (0x0001FFFF).
- Only q0 and q1 are configured with valid, non-overlapping ENST schedules (T0 and T1 respectively).
- Traffic streams p0 and p1 are bound to q0 and q1.
- ENST is enabled only on q0 and q1.

Observed behavior:
- During T0 on-time, both p0 and p1 packets are transmitted.
- During T1 on-time, both p0 and p1 packets are transmitted.

With the unused queues (q2 and q3) explicitly programmed with enst_on_time = 0x0:
- During T0 on-time, only p0 packets are transmitted.
- During T1 on-time, only p1 packets are transmitted.

Leaving the ENST on-time registers of unused queues at their reset value (0x0001FFFF) disrupts the scheduling of the configured queues, whereas programming them with 0x0 yields the expected ENST operation.

Program the ENST registers for every queue unconditionally. The per-queue configuration array is now allocated for bp->num_queues and indexed directly by queue_id; unconfigured queues are left zero-initialized by kzalloc_objs(), so their registers are cleared. Indexing the array by queue_id also makes the queue_id field in struct macb_queue_enst_config redundant, so drop it.

Fixes 89934dbf169e ("net: macb: Add TAPRIO traffic scheduling support")
[ sashal: Queue index is computed with hweight32(bp->queue_mask & (gate_mask - 1)) instead of upstream's order_base_2(gate_mask), since sparse queue masks are possible here, and kcalloc replaces kzalloc_objs. ]
---
 drivers/net/ethernet/cadence/macb.h      |  2 --
 drivers/net/ethernet/cadence/macb_main.c | 23 ++++++++++++-----------
 2 files changed, 12 insertions(+), 13 deletions(-)
drivers/net/ethernet/cadence/macb.h +0 -2
index a6602aae3f9d3..008d7dc670099 100644
@@ -1458,7 +1458,6 @@ struct macb_platform_data {
  * @start_time_mask:  Bitmask representing the start time for the queue
  * @on_time_bytes:    "on" time nsec expressed in bytes
  * @off_time_bytes:   "off" time nsec expressed in bytes
- * @queue_id:         Identifier for the queue
  *
  * This structure holds the configuration parameters for an ENST queue,
  * used to control time-based transmission scheduling in the MACB driver.
@@ -1467,7 +1466,6 @@ struct macb_queue_enst_config {
 	u32 start_time_mask;
 	u32 on_time_bytes;
 	u32 off_time_bytes;
-	u8 queue_id;
 };
 
 #endif /* _MACB_H */
drivers/net/ethernet/cadence/macb_main.c +12 -11
index 1eaf9be483153..112b1785e817e 100644
@@ -4232,7 +4232,8 @@ static int macb_taprio_setup_replace(struct net_device *ndev,
 	struct macb *bp = netdev_priv(ndev);
 	struct ethtool_link_ksettings kset;
 	struct macb_queue *queue;
-	size_t i;
+	size_t i, q;
+	u8 queue_id;
 	int err;
 
 	if (conf->num_entries > bp->num_queues) {
@@ -4260,7 +4261,7 @@ static int macb_taprio_setup_replace(struct net_device *ndev,
 		return -EINVAL;
 	}
 
-	enst_queue = kcalloc(conf->num_entries, sizeof(*enst_queue), GFP_KERNEL);
+	enst_queue = kcalloc(bp->num_queues, sizeof(*enst_queue), GFP_KERNEL);
 	if (unlikely(!enst_queue))
 		return -ENOMEM;
 
@@ -4318,13 +4319,14 @@ static int macb_taprio_setup_replace(struct net_device *ndev,
 			goto cleanup;
 		}
 
-		enst_queue[i].queue_id = order_base_2(entry->gate_mask);
-		enst_queue[i].start_time_mask =
+		/* Map the hardware queue to its index in bp->queues (the mask may be sparse) */
+		queue_id = hweight32(bp->queue_mask & (entry->gate_mask - 1));
+		enst_queue[queue_id].start_time_mask =
 			(start_time_sec << GEM_START_TIME_SEC_OFFSET) |
 			start_time_nsec;
-		enst_queue[i].on_time_bytes =
+		enst_queue[queue_id].on_time_bytes =
 			enst_ns_to_hw_units(entry->interval, speed);
-		enst_queue[i].off_time_bytes =
+		enst_queue[queue_id].off_time_bytes =
 			enst_ns_to_hw_units(conf->cycle_time - entry->interval, speed);
 
 		configured_queues |= entry->gate_mask;
@@ -4349,15 +4351,14 @@ static int macb_taprio_setup_replace(struct net_device *ndev,
 		gem_writel(bp, ENST_CONTROL,
 			   bp->queue_mask << GEM_ENST_DISABLE_QUEUE_OFFSET);
 
-		for (i = 0; i < conf->num_entries; i++) {
-			queue = &bp->queues[enst_queue[i].queue_id];
+		for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) {
 			/* Configure queue timing registers */
 			queue_writel(queue, ENST_START_TIME,
-				     enst_queue[i].start_time_mask);
+				     enst_queue[q].start_time_mask);
 			queue_writel(queue, ENST_ON_TIME,
-				     enst_queue[i].on_time_bytes);
+				     enst_queue[q].on_time_bytes);
 			queue_writel(queue, ENST_OFF_TIME,
-				     enst_queue[i].off_time_bytes);
+				     enst_queue[q].off_time_bytes);
 		}
 
 		/* Enable ENST for all configured queues in one write */
Signature · 1 line
2.53.0
author maintainer
#580 lore raw

PATCH 579/990 wifi: nl80211: reject zero RNR/MBSSID elements

In reply to Greg Kroah-Hartman

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

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

From: Johannes Berg <[email protected]>

[ Upstream commit c767e1173aeab7825a8dfb197041d3996db84e39 ]

That's a nonsensical configuration, and we get errors reported further down in mac80211 for it; hostapd has code that only adds the nested element if it'll not be an empty list.

Remove an unnecessary NULL check while at it.

Fixes dbbb27e183b1 ("cfg80211: support RNR for EMA AP")
Assisted-by LLM
[ sashal: Kept the existing kzalloc(struct_size(...), GFP_KERNEL) allocation instead of upstream's kzalloc_flex(), adding the zero-element guard above it in both parse functions. ]
---
 net/wireless/nl80211.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
net/wireless/nl80211.c +8 -1
index d4b1e5dc5eb4f..429dba541cb88 100644
@@ -6152,6 +6152,9 @@ nl80211_parse_mbssid_elems(struct wiphy *wiphy, struct nlattr *attrs,
 		num_elems++;
 	}
 
+	if (!num_elems)
+		return ERR_PTR(-EINVAL);
+
 	elems = kzalloc(struct_size(elems, elem, num_elems), GFP_KERNEL);
 	if (!elems)
 		return ERR_PTR(-ENOMEM);
@@ -6187,6 +6190,9 @@ nl80211_parse_rnr_elems(struct wiphy *wiphy, struct nlattr *attrs,
 		num_elems++;
 	}
 
+	if (!num_elems)
+		return ERR_PTR(-EINVAL);
+
 	elems = kzalloc(struct_size(elems, elem, num_elems), GFP_KERNEL);
 	if (!elems)
 		return ERR_PTR(-ENOMEM);
@@ -6335,7 +6341,8 @@ static int nl80211_parse_beacon(struct cfg80211_registered_device *rdev,
 			if (IS_ERR(rnr))
 				return PTR_ERR(rnr);
 
-			if (rnr && rnr->cnt < bcn->mbssid_ies->cnt) {
+			/* RNR elements are only used with MBSSID elements */
+			if (rnr->cnt < bcn->mbssid_ies->cnt) {
 				kfree(rnr);
 				return -EINVAL;
 			}
Signature · 1 line
2.53.0
author maintainer
#581 lore raw

PATCH 580/990 dma-direct: Restore arch_dma_alloc() for the DMA_ATTR_NO_KERNEL_MAPPING case

In reply to Greg Kroah-Hartman

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

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

From: Marek Szyprowski <[email protected]>

[ Upstream commit 5e3bc6b44c8853bcc7782eac122c5baf2d02f399 ]

Commit 849facea92fa ("dma-direct: simplify the DMA_ATTR_NO_KERNEL_MAPPING handling") moved the DMA_ATTR_NO_KERNEL_MAPPING shortcut in dma_direct_alloc() in front of the arch_dma_alloc() call. Architectures providing their own DMA coherent allocator (CONFIG_ARCH_HAS_DMA_ALLOC) therefore no longer see such requests. ARM 32bit is one of such. Lack of the call to arch_dma_alloc() results in the lack of proper cache management on HighMem pages.

Take the dma-direct shortcut only for coherent devices or when the architecture doesn't provide arch_dma_alloc(). While touching this, move that check into separate function to avoid duplication in alloc and free paths.

Fixes 849facea92fa ("dma-direct: simplify the DMA_ATTR_NO_KERNEL_MAPPING handling")
Assisted-by Claude Opus 5.5 <[email protected]>
[ sashal: Adapted the helper's attribute check to use force_dma_unencrypted() instead of the newer __DMA_ATTR_ALLOC_CC_SHARED flag, which this tree lacks. ]
---
 kernel/dma/direct.c | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)
kernel/dma/direct.c +17 -4
index cc334eb94b33d..11960210266fb 100644
@@ -181,6 +181,21 @@ static struct page *dma_direct_alloc_from_pool(struct device *dev, size_t size,
 	return page;
 }
 
+/*
+ * Check if the allocation can skip the kernel mapping and return the page
+ * pointer as the cookie.
+ */
+static bool dma_direct_use_no_mapping(struct device *dev, unsigned long attrs)
+{
+	if (!(attrs & DMA_ATTR_NO_KERNEL_MAPPING))
+		return false;
+	if (force_dma_unencrypted(dev) || is_swiotlb_for_alloc(dev))
+		return false;
+	if (IS_ENABLED(CONFIG_ARCH_HAS_DMA_ALLOC) && !dev_is_dma_coherent(dev))
+		return false;
+	return true;
+}
+
 static void *dma_direct_alloc_no_mapping(struct device *dev, size_t size,
 		dma_addr_t *dma_handle, gfp_t gfp)
 {
@@ -210,8 +225,7 @@ void *dma_direct_alloc(struct device *dev, size_t size,
 	if (attrs & DMA_ATTR_NO_WARN)
 		gfp |= __GFP_NOWARN;
 
-	if ((attrs & DMA_ATTR_NO_KERNEL_MAPPING) &&
-	    !force_dma_unencrypted(dev) && !is_swiotlb_for_alloc(dev))
+	if (dma_direct_use_no_mapping(dev, attrs))
 		return dma_direct_alloc_no_mapping(dev, size, dma_handle, gfp);
 
 	if (!dev_is_dma_coherent(dev)) {
@@ -314,8 +328,7 @@ void dma_direct_free(struct device *dev, size_t size,
 {
 	unsigned int page_order = get_order(size);
 
-	if ((attrs & DMA_ATTR_NO_KERNEL_MAPPING) &&
-	    !force_dma_unencrypted(dev) && !is_swiotlb_for_alloc(dev)) {
+	if (dma_direct_use_no_mapping(dev, attrs)) {
 		/* cpu_addr is a struct page cookie, not a kernel address */
 		dma_free_contiguous(dev, cpu_addr, size);
 		return;
Signature · 1 line
2.53.0
author maintainer
#582 lore raw

PATCH 581/990 cxl/port: Attach endpoints to a dport under the lock that pins it

In reply to Greg Kroah-Hartman

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

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

From: Dave Jiang <[email protected]>

[ Upstream commit bcda00c78d075340fe30cb6c980507fac711e7d1 ]

devm_cxl_enumerate_ports() and add_port_attach_ep() look up or create a dport under its port's device lock, drop the lock, then pass the dport to cxl_add_ep(). add_ep() reads dport->port before taking the lock, and cxl_gpf_port_setup() reads and writes the dport with no lock held.

A concurrent cxl_detach_ep() for another memdev below the same port can free the dport in that window: it calls del_dports() under the port lock when the last endpoint leaves. The enumerating memdev then dereferences freed memory.

Attach the endpoint and set up GPF while the port lock from the lookup is still held. Make add_ep() assert that lock instead of taking it. Under the lock, a dport found in port->dports is still live, since removal erases it from the xarray before freeing it.

[ dj: Added kdoc update from Alison. ]

Fixes de516b40116e ("cxl/port: Record dport in endpoint references")
Assisted-by LLM
[ sashal: Replaced the dport lookup's lock guard with a single guard(device)(&port->dev) in the helper because port_to_host() doesn't exist here, so upstream's two-lock scheme was dropped. ]
---
 drivers/cxl/core/port.c | 121 +++++++++++++++++++++-------------------
 1 file changed, 65 insertions(+), 56 deletions(-)
drivers/cxl/core/port.c +65 -56
index b9a585f64b8ab..9c9fcea02816f 100644
@@ -1383,7 +1383,7 @@ static int add_ep(struct cxl_ep *new)
 {
 	struct cxl_port *port = new->dport->port;
 
-	guard(device)(&port->dev);
+	device_lock_assert(&port->dev);
 	if (port->dead)
 		return -ENXIO;
 
@@ -1399,6 +1399,11 @@ static int add_ep(struct cxl_ep *new)
  * Intermediate CXL ports are scanned based on the arrival of endpoints.
  * When those endpoints depart the port can be destroyed once all
  * endpoints that care about that port have been removed.
+ *
+ * Context: Caller must hold the device lock of @dport->port, which pins
+ *          @dport, across the lookup of @dport and this call. @dport->port
+ *          is never the CXL root port, whose dports are pinned by its
+ *          uport_dev instead.
  */
 static int cxl_add_ep(struct cxl_dport *dport, struct device *ep_dev)
 {
@@ -1727,13 +1732,15 @@ static struct cxl_dport *probe_dport(struct cxl_port *port,
 	return drv->add_dport(port, dport_dev);
 }
 
-static struct cxl_dport *devm_cxl_create_port(struct device *ep_dev,
-					      struct cxl_port *parent_port,
-					      struct cxl_dport *parent_dport,
-					      struct device *uport_dev,
-					      struct device *dport_dev)
+static int devm_cxl_create_port(struct device *ep_dev,
+				struct cxl_port *parent_port,
+				struct cxl_dport *parent_dport,
+				struct device *uport_dev,
+				struct device *dport_dev)
 {
 	resource_size_t component_reg_phys;
+	struct cxl_dport *dport;
+	int rc;
 
 	device_lock_assert(&parent_port->dev);
 	if (!parent_port->dev.driver) {
@@ -1750,7 +1757,7 @@ static struct cxl_dport *devm_cxl_create_port(struct device *ep_dev,
 		port = devm_cxl_add_port(&parent_port->dev, uport_dev,
 					 component_reg_phys, parent_dport);
 		if (IS_ERR(port))
-			return ERR_CAST(port);
+			return PTR_ERR(port);
 
 		/*
 		 * retry to make sure a port is found. a port device
@@ -1758,7 +1765,7 @@ static struct cxl_dport *devm_cxl_create_port(struct device *ep_dev,
 		 */
 		port = find_cxl_port_by_uport(uport_dev);
 		if (!port)
-			return ERR_PTR(-ENODEV);
+			return -ENODEV;
 
 		dev_dbg(ep_dev, "created port %s:%s\n",
 			dev_name(&port->dev), dev_name(port->uport_dev));
@@ -1767,11 +1774,25 @@ static struct cxl_dport *devm_cxl_create_port(struct device *ep_dev,
 		 * Port was created before right before this function is
 		 * called. Signal the caller to deal with it.
 		 */
-		return ERR_PTR(-EAGAIN);
+		return -EAGAIN;
 	}
 
+	/* @dport is only valid while @port's lock is held */
 	guard(device)(&port->dev);
-	return probe_dport(port, dport_dev);
+	dport = probe_dport(port, dport_dev);
+	if (IS_ERR(dport))
+		return PTR_ERR(dport);
+
+	rc = cxl_add_ep(dport, ep_dev);
+	if (rc == -EBUSY) {
+		/*
+		 * "can't" happen, but this error code means
+		 * something to the caller, so translate it.
+		 */
+		rc = -ENXIO;
+	}
+
+	return rc;
 }
 
 static int add_port_attach_ep(struct cxl_memdev *cxlmd,
@@ -1779,7 +1800,7 @@ static int add_port_attach_ep(struct cxl_memdev *cxlmd,
 			      struct device *dport_dev)
 {
 	struct device *dparent = grandparent(dport_dev);
-	struct cxl_dport *dport, *parent_dport;
+	struct cxl_dport *parent_dport;
 	int rc;
 
 	if (is_cxl_host_bridge(dparent)) {
@@ -1808,46 +1829,51 @@ static int add_port_attach_ep(struct cxl_memdev *cxlmd,
 				return PTR_ERR(parent_dport);
 		}
 
-		dport = devm_cxl_create_port(&cxlmd->dev, parent_port,
-					     parent_dport, uport_dev,
-					     dport_dev);
-		if (IS_ERR(dport)) {
-			/* Port or dport already exists, restart iteration */
-			if (PTR_ERR(dport) == -EAGAIN || PTR_ERR(dport) == -EBUSY)
-				return 0;
-			return PTR_ERR(dport);
-		}
+		rc = devm_cxl_create_port(&cxlmd->dev, parent_port,
+					  parent_dport, uport_dev, dport_dev);
 	}
 
-	rc = cxl_add_ep(dport, &cxlmd->dev);
-	if (rc == -EBUSY) {
-		/*
-		 * "can't" happen, but this error code means
-		 * something to the caller, so translate it.
-		 */
-		rc = -ENXIO;
-	}
+	/* Port or dport already exists, restart iteration */
+	if (rc == -EAGAIN || rc == -EBUSY)
+		return 0;
 
 	return rc;
 }
 
-static struct cxl_dport *find_or_add_dport(struct cxl_port *port,
-					   struct device *dport_dev)
+static int find_or_add_dport_attach_ep(struct cxl_memdev *cxlmd,
+				       struct cxl_port *port,
+				       struct device *dport_dev)
 {
 	struct cxl_dport *dport;
+	int rc;
 
-	device_lock_assert(&port->dev);
+	guard(device)(&port->dev);
 	dport = cxl_find_dport_by_dev(port, dport_dev);
 	if (!dport) {
 		dport = probe_dport(port, dport_dev);
 		if (IS_ERR(dport))
-			return dport;
+			return PTR_ERR(dport);
 
 		/* New dport added, restart iteration */
-		return ERR_PTR(-EAGAIN);
+		return -EAGAIN;
 	}
 
-	return dport;
+	/* @dport is only valid while @port's lock is held */
+	rc = cxl_add_ep(dport, &cxlmd->dev);
+
+	/*
+	 * If the endpoint already exists in the port's list,
+	 * that's ok, it was added on a previous pass.
+	 * Otherwise, retry in add_port_attach_ep() after taking
+	 * the parent_port lock as the current port may be being
+	 * reaped.
+	 */
+	if (rc && rc != -EBUSY)
+		return rc;
+
+	cxl_gpf_port_setup(dport);
+
+	return 0;
 }
 
 int devm_cxl_enumerate_ports(struct cxl_memdev *cxlmd)
@@ -1876,7 +1902,6 @@ int devm_cxl_enumerate_ports(struct cxl_memdev *cxlmd)
 	for (iter = dev; iter; iter = grandparent(iter)) {
 		struct device *dport_dev = grandparent(iter);
 		struct device *uport_dev;
-		struct cxl_dport *dport;
 
 		if (is_cxl_host_bridge(dport_dev))
 			return 0;
@@ -1903,29 +1928,13 @@ int devm_cxl_enumerate_ports(struct cxl_memdev *cxlmd)
 			 * RP port enumerated by cxl_acpi without dport will
 			 * have the dport added here.
 			 */
-			scoped_guard(device, &port->dev) {
-				dport = find_or_add_dport(port, dport_dev);
-				if (IS_ERR(dport)) {
-					if (PTR_ERR(dport) == -EAGAIN)
-						goto retry;
-					return PTR_ERR(dport);
-				}
-			}
-
-			rc = cxl_add_ep(dport, &cxlmd->dev);
-
-			/*
-			 * If the endpoint already exists in the port's list,
-			 * that's ok, it was added on a previous pass.
-			 * Otherwise, retry in add_port_attach_ep() after taking
-			 * the parent_port lock as the current port may be being
-			 * reaped.
-			 */
-			if (rc && rc != -EBUSY)
+			rc = find_or_add_dport_attach_ep(cxlmd, port,
+							 dport_dev);
+			if (rc == -EAGAIN)
+				goto retry;
+			if (rc)
 				return rc;
 
-			cxl_gpf_port_setup(dport);
-
 			/* Any more ports to add between this one and the root? */
 			if (!dev_is_cxl_root_child(&port->dev))
 				continue;
Signature · 1 line
2.53.0
author maintainer
#583 lore raw

PATCH 582/990 ALSA: hda/realtek: Fix mute LEDs on HP ENVY 17-cr1xxx

In reply to Greg Kroah-Hartman

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

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

From: Maksim Krasutski <[email protected]>

[ Upstream commit dd83323e4d5e22bd04f7506a9ec33533465c8393 ]

The HP ENVY Laptop 17-cr1xxx with subsystem ID 103c:8be8 uses an ALC245 codec and two CS35L41 I2C speaker amplifiers. Its existing quirk configures the amplifiers but does not enable the speaker and microphone mute LED handlers.

Select ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS to retain the amplifier setup and enable both mute indicators.

The equivalent change was tested on an HP ENVY 17-cr1xxx running Kubuntu 26.04.1 with kernel 7.0.0-38-generic. Both keyboard mute indicators were confirmed working.

Fixes aa8e3ef4fe53 ("ALSA: hda/realtek: Add quirks for various HP ENVY models")
Assisted-by LLM
[ sashal: Adjusted context lines: the neighbouring 0x8be9 quirk entry differs in this tree, so only the 0x8be8 line was changed to the HP mute-LEDs fixup. ]
---
 sound/hda/codecs/realtek/alc269.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/hda/codecs/realtek/alc269.c +1 -1
index ba850cb119ec6..6ee95ae0e8f67 100644
@@ -7106,7 +7106,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x103c, 0x8be5, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be6, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be7, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2),
-	SND_PCI_QUIRK(0x103c, 0x8be8, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2),
+	SND_PCI_QUIRK(0x103c, 0x8be8, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS),
 	SND_PCI_QUIRK(0x103c, 0x8be9, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8bf0, "HP", ALC236_FIXUP_HP_GPIO_LED),
 	SND_PCI_QUIRK(0x103c, 0x8bfd, "HP Pavilion 15-eg3xxx", ALC287_FIXUP_HP_GPIO_LED),
Signature · 1 line
2.53.0
author maintainer
#584 lore raw

PATCH 583/990 RDMA/rtrs-clt: Fix recv repost to satisfy ib_drain_rq

In reply to Greg Kroah-Hartman

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

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

From: Quanye Yang <[email protected]>

[ Upstream commit 3255d6b83491574b115806ec958d8f6ca090fa9c ]

On disconnect the client error recovery path calls ib_drain_qp(), which requires one free RQ slot and that no recv WQEs are posted while the queue is being drained.

When the server is loaded with always_invalidate=N, the path does not advertise RTRS_MSG_NEW_RKEY_F. A client-requested invalidation is then a standalone SEND_WITH_INV. The recv completion path did not repost that WQE; it posted two empty recv WQEs later, when the RDMA-with-IMM response carried RTRS_IO_RSP_W_INV_IMM. If the invalidate receive never arrived, each such response increased RQ occupancy by one until ib_post_recv() started returning -ENOMEM and __ib_drain_rq() failed with:

failed to drain recv queue: -12

Repost one empty recv WQE for every receive completion, including SEND_WITH_INV completions on the always_invalidate=N path, and only while the path is still connected so CQ polling cannot race with ib_drain_qp(). Size IO connection RQs to 2 * queue_depth + 1 to match the posted recv count and leave the drain slot.

Tested with a synthetic RTRS client flooding unpaired RTRS_IO_RSP_W_INV_IMM messages; error recovery no longer triggers __ib_drain_rq() warnings.

Fixes 6a98d71daea1 ("RDMA/rtrs: client: main functionality")
[ sashal: Adjusted context for the older error-log format and the min_t() form of the max_recv_wr computation, then applied the same repost and queue_depth * 2 + 1 changes. ]
---
 drivers/infiniband/ulp/rtrs/rtrs-clt.c | 45 +++++++++-----------------
 1 file changed, 15 insertions(+), 30 deletions(-)
drivers/infiniband/ulp/rtrs/rtrs-clt.c +15 -30
index dbce23eabcfd1..3525508fe0321 100644
@@ -582,25 +582,21 @@ static struct ib_cqe io_comp_cqe = {
 	.done = rtrs_clt_rdma_done
 };
 
-/*
- * Post x2 empty WRs: first is for this RDMA with IMM,
- * second is for RECV with INV, which happened earlier.
- */
-static int rtrs_post_recv_empty_x2(struct rtrs_con *con, struct ib_cqe *cqe)
+static int rtrs_clt_repost_recv(struct rtrs_clt_con *con)
 {
-	struct ib_recv_wr wr_arr[2], *wr;
-	int i;
+	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
+	int err;
 
-	memset(wr_arr, 0, sizeof(wr_arr));
-	for (i = 0; i < ARRAY_SIZE(wr_arr); i++) {
-		wr = &wr_arr[i];
-		wr->wr_cqe  = cqe;
-		if (i)
-			/* Chain backwards */
-			wr->next = &wr_arr[i - 1];
-	}
+	if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED)
+		return 0;
 
-	return ib_post_recv(con->qp, wr, NULL);
+	err = rtrs_post_recv_empty(&con->c, &io_comp_cqe);
+	if (err) {
+		rtrs_err(con->c.path, "rtrs_post_recv_empty(): %pe\n",
+			 ERR_PTR(err));
+		rtrs_rdma_error_recovery(con);
+	}
+	return err;
 }
 
 static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc)
@@ -661,19 +657,7 @@ static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc)
 			rtrs_wrn(con->c.path, "Unknown IMM type %u\n",
 				  imm_type);
 		}
-		if (w_inval)
-			/*
-			 * Post x2 empty WRs: first is for this RDMA with IMM,
-			 * second is for RECV with INV, which happened earlier.
-			 */
-			err = rtrs_post_recv_empty_x2(&con->c, &io_comp_cqe);
-		else
-			err = rtrs_post_recv_empty(&con->c, &io_comp_cqe);
-		if (err) {
-			rtrs_err(con->c.path, "rtrs_post_recv_empty(): %d\n",
-				  err);
-			rtrs_rdma_error_recovery(con);
-		}
+		rtrs_clt_repost_recv(con);
 		break;
 	case IB_WC_RECV:
 		/*
@@ -689,6 +673,7 @@ static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc)
 
 			return  rtrs_clt_rkey_rsp_done(con, wc);
 		}
+		rtrs_clt_repost_recv(con);
 		break;
 	case IB_WC_RDMA_WRITE:
 		/*
@@ -1710,7 +1695,7 @@ static int create_con_cq_qp(struct rtrs_clt_con *con)
 			      /* QD * (REQ + RSP + FR REGS or INVS) + drain */
 			      clt_path->queue_depth * 4 + 1);
 		max_recv_wr = min_t(int, wr_limit,
-			      clt_path->queue_depth * 3 + 1);
+			      clt_path->queue_depth * 2 + 1);
 		max_send_sge = 2;
 	}
 	atomic_set(&con->c.sq_wr_avail, max_send_wr);
Signature · 1 line
2.53.0
author maintainer
#585 lore raw

PATCH 584/990 RDMA/core: Clear driver_udata before destroying objects in rdma_core

In reply to Greg Kroah-Hartman

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

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

From: Jacob Moroni <[email protected]>

[ Upstream commit d37e98844afea39a9614cac0de837701263c90f7 ]

When uobject creation fails while copying user output data (i.e., after the HW object has been created), it calls rdma_alloc_abort_uobject() with hw_obj_valid=true which then invokes the object's destroy callback, but passes the uverbs_attr_bundle from the original creation command.

The issue is that drivers are expected to validate the udata and return an error if there's unexpected content, and data from the wrong command counts as "unexpected content", so this ends up causing the driver's destroy call to fail.

A similar issue exists in the rereg_mr path when a new MR is created and the old one is destroyed.

Fix this by clearing driver_udata before invoking the driver's destroy method.

Fixes 6e0954b11c05 ("RDMA/uverbs: Allow drivers to create a new HW object during rereg_mr")
Fixes 0ac8903cbbe6 ("RDMA/core: Allow the ioctl layer to abort a fully created uobject")
[ sashal: Backport keeps only the two rdma_core.c call-site hunks and drops the helper move to an inline, the create_qp() change and the NULL-attrs handling, since the helper stays a plain function in uverbs_cmd.c here. ]
---
 drivers/infiniband/core/rdma_core.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/infiniband/core/rdma_core.c +2 -0
index 18918f4633614..9503c7e90bd87 100644
@@ -688,6 +688,7 @@ void rdma_assign_uobject(struct ib_uobject *to_uobj, struct ib_uobject *new_uobj
 	 * If this fails then the uobject is still completely valid (though with
 	 * a new ID) and we leak it until context close.
 	 */
+	uverbs_get_cleared_udata(attrs);
 	uverbs_destroy_uobject(to_uobj, RDMA_REMOVE_DESTROY, attrs);
 }
 
@@ -703,6 +704,7 @@ void rdma_alloc_abort_uobject(struct ib_uobject *uobj,
 	int ret;
 
 	if (hw_obj_valid) {
+		uverbs_get_cleared_udata(attrs);
 		ret = uobj->uapi_object->type_class->destroy_hw(
 			uobj, RDMA_REMOVE_ABORT, attrs);
 		/*
Signature · 1 line
2.53.0
author maintainer
#586 lore raw

PATCH 585/990 dmaengine: ste_dma40: Preserve the LCPA I/O address space

In reply to Greg Kroah-Hartman

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

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

From: Linus Walleij <[email protected]>

[ Upstream commit 42c31fec1ca76b8b5f7759def122d418dff2cd4b ]

The LCPA area is mapped with devm_ioremap(), but lcpa_base and the per-channel lcpa pointer lack __iomem annotations. This loses the I/O address space and makes sparse warn when d40_current_addr() assigns LCPA register addresses to its __iomem pointers.

Annotate both pointers and the LCPA argument of d40_log_lli_lcpa_write() to preserve the I/O address space from the mapping to the register accessors. This also fixes the existing LCPA read and write warnings without changing the generated code.

---
 drivers/dma/ste_dma40.c    | 4 ++--
 drivers/dma/ste_dma40_ll.c | 8 ++++----
 drivers/dma/ste_dma40_ll.h | 2 +-
 3 files changed, 7 insertions(+), 7 deletions(-)
drivers/dma/ste_dma40.c +2 -2
index 2c83eb05faa16..6699689deecae 100644
@@ -509,7 +509,7 @@ struct d40_chan {
 	u32				 src_def_cfg;
 	u32				 dst_def_cfg;
 	struct d40_def_lcsp		 log_def;
-	struct d40_log_lli_full		*lcpa;
+	struct d40_log_lli_full __iomem	*lcpa;
 	/* Runtime reconfiguration */
 	dma_addr_t			runtime_addr;
 	enum dma_transfer_direction	runtime_direction;
@@ -617,7 +617,7 @@ struct d40_base {
 	/* Physical half channels */
 	struct d40_phy_res		 *phy_res;
 	struct d40_lcla_pool		  lcla_pool;
-	void				 *lcpa_base;
+	void __iomem			 *lcpa_base;
 	dma_addr_t			  phy_lcpa;
 	resource_size_t			  lcpa_size;
 	struct kmem_cache		 *desc_slab;
drivers/dma/ste_dma40_ll.c +4 -4
index 4c489b126cb27..3be7f5b1abb08 100644
@@ -333,10 +333,10 @@ static void d40_log_lli_link(struct d40_log_lli *lli_dst,
 		(dlos << D40_MEM_LCSP1_SLOS_POS);
 }
 
-void d40_log_lli_lcpa_write(struct d40_log_lli_full *lcpa,
-			   struct d40_log_lli *lli_dst,
-			   struct d40_log_lli *lli_src,
-			   int next, unsigned int flags)
+void d40_log_lli_lcpa_write(struct d40_log_lli_full __iomem *lcpa,
+			    struct d40_log_lli *lli_dst,
+			    struct d40_log_lli *lli_src,
+			    int next, unsigned int flags)
 {
 	d40_log_lli_link(lli_dst, lli_src, next, flags);
 
drivers/dma/ste_dma40_ll.h +1 -1
index 55090cb310579..ca9d076493610 100644
@@ -455,7 +455,7 @@ int d40_log_sg_to_lli(struct scatterlist *sg,
 		      u32 lcsp13, /* src or dst*/
 		      u32 data_width1, u32 data_width2);
 
-void d40_log_lli_lcpa_write(struct d40_log_lli_full *lcpa,
+void d40_log_lli_lcpa_write(struct d40_log_lli_full __iomem *lcpa,
 			    struct d40_log_lli *lli_dst,
 			    struct d40_log_lli *lli_src,
 			    int next, unsigned int flags);
Signature · 1 line
2.53.0
author maintainer
#587 lore raw

PATCH 586/990 net: devmem: check uid and netns in net_devmem_get_binding()

In reply to Greg Kroah-Hartman

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

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

From: Kaifeng Wang <[email protected]>

[ Upstream commit 3a82195416fd71fdd6cb4ff80f611ec28073be16 ]

NETDEV_CMD_BIND_TX is unprivileged, and dmabuf binding IDs are allocated from a single global xarray. Currently net_devmem_get_binding() looks up the binding by ID without checking whether the sending socket belongs to the same user or network namespace that created the binding.

Record the creating netlink socket's network namespace and UID on the binding, and verify both in net_devmem_get_binding() before checking the route destination device. Return -EINVAL on mismatch so callers cannot distinguish non-existent IDs from bindings owned by other users.

Fixes bd61848900bf ("net: devmem: Implement TX path")
[ sashal: Kept this branch's simpler net_devmem_bind_dmabuf() signature, adding nl_sk without the vdev/niov_shift parameters or the netkit bind-device logic, and adjusted the struct hunk context. ]
---
 net/core/devmem.c      | 7 ++++++-
 net/core/devmem.h      | 5 +++++
 net/core/netdev-genl.c | 6 ++++--
 3 files changed, 15 insertions(+), 3 deletions(-)
net/core/devmem.c +6 -1
index 16ce197cb0faf..9b937d426cb9a 100644
@@ -180,6 +180,7 @@ net_devmem_bind_dmabuf(struct net_device *dev,
 		       struct device *dma_dev,
 		       enum dma_data_direction direction,
 		       unsigned int dmabuf_fd, struct netdev_nl_sock *priv,
+		       const struct sock *nl_sk,
 		       struct netlink_ext_ack *extack)
 {
 	struct net_devmem_dmabuf_binding *binding;
@@ -207,6 +208,8 @@ net_devmem_bind_dmabuf(struct net_device *dev,
 	}
 
 	binding->dev = dev;
+	write_pnet(&binding->net, sock_net(nl_sk));
+	binding->uid = sk_uid(nl_sk);
 	xa_init_flags(&binding->bound_rxqs, XA_FLAGS_ALLOC);
 
 	refcount_set(&binding->ref, 1);
@@ -374,7 +377,9 @@ struct net_devmem_dmabuf_binding *net_devmem_get_binding(struct sock *sk,
 	int err = 0;
 
 	binding = net_devmem_lookup_dmabuf(dmabuf_id);
-	if (!binding || !binding->tx_vec) {
+	if (!binding || !binding->tx_vec ||
+	    !net_eq(sock_net(sk), read_pnet(&binding->net)) ||
+	    !uid_eq(sk_uid(sk), binding->uid)) {
 		err = -EINVAL;
 		goto out_err;
 	}
net/core/devmem.h +5 -0
index 101150d761af2..674279180dc8d 100644
@@ -10,6 +10,7 @@
 #ifndef _NET_DEVMEM_H
 #define _NET_DEVMEM_H
 
+#include <net/net_namespace.h>
 #include <net/netmem.h>
 #include <net/netdev_netlink.h>
 
@@ -21,6 +22,8 @@ struct net_devmem_dmabuf_binding {
 	struct sg_table *sgt;
 	struct net_device *dev;
 	struct gen_pool *chunk_pool;
+	possible_net_t net;
+	kuid_t uid;
 	/* Protect dev */
 	struct mutex lock;
 
@@ -88,6 +91,7 @@ net_devmem_bind_dmabuf(struct net_device *dev,
 		       struct device *dma_dev,
 		       enum dma_data_direction direction,
 		       unsigned int dmabuf_fd, struct netdev_nl_sock *priv,
+		       const struct sock *nl_sk,
 		       struct netlink_ext_ack *extack);
 struct net_devmem_dmabuf_binding *net_devmem_lookup_dmabuf(u32 id);
 void net_devmem_unbind_dmabuf(struct net_devmem_dmabuf_binding *binding);
@@ -175,6 +179,7 @@ net_devmem_bind_dmabuf(struct net_device *dev,
 		       enum dma_data_direction direction,
 		       unsigned int dmabuf_fd,
 		       struct netdev_nl_sock *priv,
+		       const struct sock *nl_sk,
 		       struct netlink_ext_ack *extack)
 {
 	return ERR_PTR(-EOPNOTSUPP);
net/core/netdev-genl.c +4 -2
index 77042ac6d0428..d42e4c4d7a7d3 100644
@@ -1004,7 +1004,8 @@ int netdev_nl_bind_rx_doit(struct sk_buff *skb, struct genl_info *info)
 	}
 
 	binding = net_devmem_bind_dmabuf(netdev, dma_dev, DMA_FROM_DEVICE,
-					 dmabuf_fd, priv, info->extack);
+					 dmabuf_fd, priv, NETLINK_CB(skb).sk,
+					 info->extack);
 	if (IS_ERR(binding)) {
 		err = PTR_ERR(binding);
 		goto err_rxq_bitmap;
@@ -1097,7 +1098,8 @@ int netdev_nl_bind_tx_doit(struct sk_buff *skb, struct genl_info *info)
 
 	dma_dev = netdev_queue_get_dma_dev(netdev, 0);
 	binding = net_devmem_bind_dmabuf(netdev, dma_dev, DMA_TO_DEVICE,
-					 dmabuf_fd, priv, info->extack);
+					 dmabuf_fd, priv, NETLINK_CB(skb).sk,
+					 info->extack);
 	if (IS_ERR(binding)) {
 		err = PTR_ERR(binding);
 		goto err_unlock_netdev;
Signature · 1 line
2.53.0
author maintainer
#588 lore raw

PATCH 587/990 drm/panfrost: Fix PM refcnt and autosuspend issues at device probe/remove

In reply to Greg Kroah-Hartman

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

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

From: Adrián Larumbe <[email protected]>

[ Upstream commit e9672bf9382ff80be21d586f88e50339b85f5766 ]

During device probe(), failure to do a PM get() will leave the usage_count set to 0, which is the value assigned at device creation time. That means when the autosuspend delay expires, runtime suspend callback won't be invoked, so the device will remain powered on forever.

On top of that, failure to call PM put() during device unplug means Panfrost device's PM usage_count increases monotonically for every new module reload.

The outcome of both of the above meant that:

- Devfreq OPP transition notifications would be printed all the time, even when no jobs are being submitted. This quickly fills the kernel ring buffer with junk.
- Because MMU interrupts are only enabled when the device is reset, the very first job targeting the tiler heap BO after device probe() would always time out, since the driver's PM runtime resume callback would not be invoked.

To fix the above:
- Manually adjust the PM refcnt at device probe and removal time.
- Ensure pm_runtime_dont_use_autosuspend is called in the wind-down path.
- Call pm_runtime_put_autosuspend() when device is ready to accept jobs

Fixes 635430797d3f ("drm/panfrost: Rework runtime PM initialization")
Fixes 876b15d2c88d ("drm/panfrost: Fix module unload")
[ sashal: Replaced pfdev->base.dev with pfdev->dev, and placed pm_runtime_put_autosuspend() after panfrost_gem_shrinker_init() since this tree's probe has that extra step and error label. ]
---
 drivers/gpu/drm/panfrost/panfrost_drv.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/gpu/drm/panfrost/panfrost_drv.c +11 -0
index a31c5395de18c..2d49edaa9467d 100644
@@ -761,6 +761,11 @@ static int panfrost_probe(struct platform_device *pdev)
 		goto err_out0;
 	}
 
+	/* The reason we must manually set the PM status and usage counter is
+	 * we have just powered the device up but did not go through the PM
+	 * runtime resume callback, so we need to update these ourselves.
+	 */
+	pm_runtime_get_noresume(pfdev->dev);
 	pm_runtime_set_active(pfdev->dev);
 	pm_runtime_mark_last_busy(pfdev->dev);
 	pm_runtime_enable(pfdev->dev);
@@ -779,14 +784,18 @@ static int panfrost_probe(struct platform_device *pdev)
 	if (err)
 		goto err_out2;
 
+	pm_runtime_put_autosuspend(pfdev->dev);
+
 	return 0;
 
 err_out2:
 	drm_dev_unregister(ddev);
 err_out1:
+	pm_runtime_dont_use_autosuspend(pfdev->dev);
 	pm_runtime_disable(pfdev->dev);
 	panfrost_device_fini(pfdev);
 	pm_runtime_set_suspended(pfdev->dev);
+	pm_runtime_put_noidle(pfdev->dev);
 err_out0:
 	drm_dev_put(ddev);
 	return err;
@@ -801,9 +810,11 @@ static void panfrost_remove(struct platform_device *pdev)
 	panfrost_gem_shrinker_cleanup(ddev);
 
 	pm_runtime_get_sync(pfdev->dev);
+	pm_runtime_dont_use_autosuspend(pfdev->dev);
 	pm_runtime_disable(pfdev->dev);
 	panfrost_device_fini(pfdev);
 	pm_runtime_set_suspended(pfdev->dev);
+	pm_runtime_put_noidle(pfdev->dev);
 
 	drm_dev_put(ddev);
 }
Signature · 1 line
2.53.0
author maintainer
#589 lore raw

PATCH 588/990 net: stmmac: set real_num_tx_queues to max(offset + count)

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit d128212667593c548a3c67d30031063ed46c29b7 ]

tc_setup_dwmac510_mqprio() computes the number of real TX queues as the sum of the per-TC queue counts. mqprio_validate_queue_counts() only rejects out-of-bounds or overlapping ranges, so layouts with gaps or a non-zero first offset are accepted, and in those cases the sum is smaller than the highest queue referenced by the netdev TC map.

netif_set_real_num_tx_queues() then passes this too-small count to netif_setup_tc(). However stmmac_set_ndev_tcs() has already zeroed dev->prio_tc_map() through netdev_reset_tc(), so when netif_setup_tc() runs every priority maps to TC0 and only the TC0 range is checked. A layout whose TC0 range fits but where a later TC references a queue beyond the new real_num_tx_queues is left with num_tc set and its TC map pointing at queues that are no longer real, without any warning; only when TC0 itself is out of range is the mapping disabled. The real prio_tc_map is programmed later by the qdisc, after this call, so the driver cannot rely on netif_setup_tc() to catch those cases.

Compute num_tx_queues as the maximum of offset[i] + count[i] instead of the sum of the counts, so real_num_tx_queues always covers the highest queue referenced by the TC map. This is a no-op for the contiguous channel-mode layouts where offset[i] == i and count[i] == 1.

The issue has been reported by sashiko and the patch has been tested on Qualcomm RB3-Gen2 board.

---
 drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +1 -1
index 49161241d0328..bd28d0e6361d0 100644
@@ -1268,7 +1268,7 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv,
 	for (u32 tc = 0; tc < num_tc; tc++) {
 		offset = qopt->offset[tc];
 		count = qopt->count[tc];
-		num_stack_tx_queues += count;
+		num_stack_tx_queues = max(num_stack_tx_queues, offset + count);
 
 		err = netdev_set_tc_queue(ndev, tc, count, offset);
 		if (err)
Signature · 1 line
2.53.0
author maintainer
#590 lore raw

PATCH 589/990 net: stmmac: align real_num_tx_queues to mqprio configuration

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit ac1ca0c3e139a2ebef2fc6c570af6647329726f1 ]

stmmac_hw_setup() unconditionally sets the number of real TX queues to plat->tx_queues_to_use on every device open. When a tc-mqprio qdisc is offloaded the driver reduces netif_set_real_num_tx_queues() to the number of queues enabled by the offload, but the next device open reverts it to plat->tx_queues_to_use while the netdev TC map is still the one programmed by the qdisc, leaving the two inconsistent.

Track the number of TX queues enabled by the current qdisc configuration in the per-qdisc state (priv->xmit_qdisc.num_tx_queues) and use it in stmmac_hw_setup(). The field defaults to plat->tx_queues_to_use at probe time and when the mqprio qdisc is destroyed, meaning no offload is active and the number of real TX queues must match the number of queues the driver allocated, and it is updated to the offloaded queue count on a successful mqprio setup.

mqprio only validates the requested queue ranges against dev->real_num_tx_queues, which can be larger than plat->tx_queues_to_use while the interface has not been opened yet. Reject a qopt whose highest referenced queue (offset + count) exceeds plat->tx_queues_to_use, so xmit_qdisc.num_tx_queues can never be larger than the number of TX queues the driver provisions. Otherwise stmmac_hw_setup() would expose TX queues without an allocated DMA ring.

Refuse to lower the number of TX queues below the count required by the active mqprio offload in stmmac_reinit_queues(), otherwise netif_set_real_num_tx_queues() would leave real_num_tx_queues inconsistent with the netdev TC map.

The issue has been reported by sashiko and the patch has been tested on a Qualcomm RB3-Gen2 board.

Fixes 195e4f409a40 ("net: stmmac: support fp parameter of tc-mqprio")
[ sashal: Moved the queue-range check into a pre-pass before any state change, since the local mqprio setup lacks upstream's staging arrays, and used the existing num_stack_tx_queues variable. ]
---
 drivers/net/ethernet/stmicro/stmmac/stmmac.h      |  6 ++++++
 drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 12 +++++++++++-
 drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c   | 15 +++++++++++++++
 3 files changed, 32 insertions(+), 1 deletion(-)
drivers/net/ethernet/stmicro/stmmac/stmmac.h +6 -0
index 61e182278d156..7cb09679a0d97 100644
@@ -282,6 +282,12 @@ struct stmmac_priv {
 	/* Protect est parameters */
 	struct mutex est_lock;
 	struct stmmac_est *est;
+
+	struct {
+		bool enabled;
+		u32 num_tx_queues;
+	} xmit_qdisc;
+
 	struct dma_features dma_cap;
 	struct stmmac_counters mmc;
 	int hw_cap_support;
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +11 -1
index 0dc333218aa98..c4053684dec3f 100644
@@ -3552,7 +3552,7 @@ static int stmmac_hw_setup(struct net_device *dev)
 
 	/* Configure real RX and TX queues */
 	netif_set_real_num_rx_queues(dev, priv->plat->rx_queues_to_use);
-	netif_set_real_num_tx_queues(dev, priv->plat->tx_queues_to_use);
+	netif_set_real_num_tx_queues(dev, priv->xmit_qdisc.num_tx_queues);
 
 	/* Start the ball rolling... */
 	stmmac_start_all_dma(priv);
@@ -7484,6 +7484,10 @@ int stmmac_reinit_queues(struct net_device *dev, u32 rx_cnt, u32 tx_cnt)
 	struct stmmac_priv *priv = netdev_priv(dev);
 	int ret = 0, i;
 
+	if (priv->xmit_qdisc.enabled &&
+	    tx_cnt < priv->xmit_qdisc.num_tx_queues)
+		return -EINVAL;
+
 	if (netif_running(dev))
 		stmmac_release(dev);
 
@@ -7491,6 +7495,9 @@ int stmmac_reinit_queues(struct net_device *dev, u32 rx_cnt, u32 tx_cnt)
 
 	priv->plat->rx_queues_to_use = rx_cnt;
 	priv->plat->tx_queues_to_use = tx_cnt;
+	if (!priv->xmit_qdisc.enabled)
+		priv->xmit_qdisc.num_tx_queues = tx_cnt;
+
 	if (!netif_is_rxfh_configured(dev))
 		for (i = 0; i < ARRAY_SIZE(priv->rss.table); i++)
 			priv->rss.table[i] = ethtool_rxfh_indir_default(i,
@@ -7682,6 +7689,9 @@ int stmmac_dvr_probe(struct device *device,
 	ndev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT |
 			     NETDEV_XDP_ACT_XSK_ZEROCOPY;
 
+	/* Default qdisc num_tx_queues */
+	priv->xmit_qdisc.num_tx_queues = priv->plat->tx_queues_to_use;
+
 	ret = stmmac_tc_init(priv, priv);
 	if (!ret) {
 		ndev->hw_features |= NETIF_F_HW_TC;
drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +15 -0
index bd28d0e6361d0..a254644bc7b81 100644
@@ -1242,6 +1242,9 @@ static int stmmac_reset_tc_mqprio(struct net_device *ndev,
 {
 	struct stmmac_priv *priv = netdev_priv(ndev);
 
+	priv->xmit_qdisc.num_tx_queues = priv->plat->tx_queues_to_use;
+	priv->xmit_qdisc.enabled = false;
+
 	netdev_reset_tc(ndev);
 	netif_set_real_num_tx_queues(ndev, priv->plat->tx_queues_to_use);
 
@@ -1261,6 +1264,15 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv,
 	if (!num_tc)
 		return stmmac_reset_tc_mqprio(ndev, extack);
 
+	for (u32 tc = 0; tc < num_tc; tc++) {
+		if (qopt->offset[tc] + qopt->count[tc] >
+		    priv->plat->tx_queues_to_use) {
+			NL_SET_ERR_MSG_MOD(extack,
+					   "Queues exceed hw TX queues");
+			return -EINVAL;
+		}
+	}
+
 	err = netdev_set_num_tc(ndev, num_tc);
 	if (err)
 		return err;
@@ -1284,6 +1296,9 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv,
 	if (err)
 		goto err_reset_tc;
 
+	priv->xmit_qdisc.num_tx_queues = num_stack_tx_queues;
+	priv->xmit_qdisc.enabled = true;
+
 	return 0;
 
 err_reset_tc:
Signature · 1 line
2.53.0
author maintainer
#591 lore raw

PATCH 590/990 wifi: ath12k: Fix NAPI resource leaks in AHB external IRQ paths

In reply to Greg Kroah-Hartman

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

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

From: Aaradhana Sahu <[email protected]>

[ Upstream commit ebc938ba1d5ff33652013b99c7b9a74f05690336 ]

Currently, NAPI instances and their associated netdevs allocated for AHB external IRQ groups are not released when external IRQ configuration fails. They are also not freed when arch_init() fails after ath12k_ahb_config_irq() succeeds during probe, or when the driver is unloaded.

Fix this by adding a common cleanup helper to release the NAPI instances and associated netdevs. Call it from the external IRQ configuration error path, probe error path, and driver cleanup path.

Tested-on: IPQ5332 hw1.0 AHB WLAN.WBE.1.6-01275-QCAHKSWPL_SILICONZ-1

Fixes 6cee30f0da75 ("wifi: ath12k: add AHB driver support for IPQ5332")
Fixes 614c23e24ee8 ("wifi: ath12k: Support arch-specific DP device allocation")
[renamed label err_free_irq]
[ sashal: Dropped the arch_init/arch_deinit parts missing on this branch and routed the ath12k_core_init() failure in probe to the new err_free_ext_napi label. ]
---
 drivers/net/wireless/ath/ath12k/ahb.c | 41 ++++++++++++++++++++++++---
 1 file changed, 37 insertions(+), 4 deletions(-)
drivers/net/wireless/ath/ath12k/ahb.c +37 -4
index 1a1195951a140..39cb9901dbd76 100644
@@ -183,6 +183,26 @@ static void __ath12k_ahb_ext_irq_disable(struct ath12k_base *ab)
 	}
 }
 
+static void ath12k_ahb_free_napi_for_group(struct ath12k_ext_irq_grp *irq_grp)
+{
+	netif_napi_del(&irq_grp->napi);
+	free_netdev(irq_grp->napi_ndev);
+	irq_grp->napi_ndev = NULL;
+}
+
+static void ath12k_ahb_free_napi(struct ath12k_base *ab, int num_ext_irq_grp)
+{
+	int i;
+
+	for (i = 0; i < num_ext_irq_grp; i++)
+		ath12k_ahb_free_napi_for_group(&ab->ext_irq_grp[i]);
+}
+
+static void ath12k_ahb_free_ext_napi(struct ath12k_base *ab)
+{
+	ath12k_ahb_free_napi(ab, ATH12K_EXT_IRQ_GRP_NUM_MAX);
+}
+
 static void ath12k_ahb_ext_grp_enable(struct ath12k_ext_irq_grp *irq_grp)
 {
 	int i;
@@ -580,8 +600,10 @@ static int ath12k_ahb_config_ext_irq(struct ath12k_base *ab)
 		irq_grp->grp_id = i;
 
 		irq_grp->napi_ndev = alloc_netdev_dummy(0);
-		if (!irq_grp->napi_ndev)
-			return -ENOMEM;
+		if (!irq_grp->napi_ndev) {
+			ret = -ENOMEM;
+			goto free_napi_ndev;
+		}
 
 		netif_napi_add(irq_grp->napi_ndev, &irq_grp->napi,
 			       ath12k_ahb_ext_grp_napi_poll);
@@ -628,12 +650,19 @@ static int ath12k_ahb_config_ext_irq(struct ath12k_base *ab)
 					       ath12k_ahb_ext_interrupt_handler,
 					       IRQF_TRIGGER_RISING,
 					       irq_name[irq_idx], irq_grp);
-			if (ret)
+			if (ret) {
 				ath12k_warn(ab, "failed request_irq for %d\n", irq);
+				ath12k_ahb_free_napi_for_group(irq_grp);
+				goto free_napi_ndev;
+			}
 		}
 	}
 
 	return 0;
+
+free_napi_ndev:
+	ath12k_ahb_free_napi(ab, i);
+	return ret;
 }
 
 static int ath12k_ahb_config_irq(struct ath12k_base *ab)
@@ -1071,11 +1100,14 @@ static int ath12k_ahb_probe(struct platform_device *pdev)
 	ret = ath12k_core_init(ab);
 	if (ret) {
 		ath12k_err(ab, "failed to init core: %d\n", ret);
-		goto err_rproc_deconfigure;
+		goto err_free_ext_napi;
 	}
 
 	return 0;
 
+err_free_ext_napi:
+	ath12k_ahb_free_ext_napi(ab);
+
 err_rproc_deconfigure:
 	ath12k_ahb_deconfigure_rproc(ab);
 
@@ -1115,6 +1147,7 @@ static void ath12k_ahb_free_resources(struct ath12k_base *ab)
 {
 	struct platform_device *pdev = ab->pdev;
 
+	ath12k_ahb_free_ext_napi(ab);
 	ath12k_hal_srng_deinit(ab);
 	ath12k_ce_free_pipes(ab);
 	ath12k_ahb_resource_deinit(ab);
Signature · 1 line
2.53.0
author maintainer
#592 lore raw

PATCH 591/990 wifi: ath12k: avoid IDR mutation during pending mgmt TX cleanup

In reply to Greg Kroah-Hartman

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

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

From: Jiale Yao <[email protected]>

[ Upstream commit 94c7b50351fd30e1dfe1b4051197a1445d8547e1 ]

The pending management TX cleanup walks txmgmt_idr with idr_for_each(), and its callback removes the current entry. This can invalidate the radix-tree iterator retained by idr_for_each().

Use idr_for_each_entry() so every iteration starts with a fresh lookup. Continue to remove each entry under txmgmt_idr_lock before freeing its skb, preventing concurrent TX completion from finding a stale skb pointer.

Fixes d889913205cf ("wifi: ath12k: driver for Qualcomm Wi-Fi 7 devices")
[ sashal: adjusted context lines in core.c, mac.c and mac.h to match the older tree; the functional change is identical to upstream. ]
---
 drivers/net/wireless/ath/ath12k/core.c |  3 +--
 drivers/net/wireless/ath/ath12k/mac.c  | 12 ++++++------
 drivers/net/wireless/ath/ath12k/mac.h  |  2 +-
 3 files changed, 8 insertions(+), 9 deletions(-)
drivers/net/wireless/ath/ath12k/core.c +1 -2
index dc969b2516ea0..8a11ff7fb58fc 100644
@@ -1468,8 +1468,7 @@ static void ath12k_core_pre_reconfigure_recovery(struct ath12k_base *ab)
 			complete_all(&ar->regd_update_completed);
 
 			wake_up(&ar->dp.tx_empty_waitq);
-			idr_for_each(&ar->txmgmt_idr,
-				     ath12k_mac_tx_mgmt_pending_free, ar);
+			ath12k_mac_tx_mgmt_pending_free(ar);
 			idr_destroy(&ar->txmgmt_idr);
 			wake_up(&ar->txmgmt_empty_waitq);
 
drivers/net/wireless/ath/ath12k/mac.c +6 -6
index b9c943b219546..13a7d60c50c7c 100644
@@ -8476,13 +8476,13 @@ static void ath12k_mac_tx_mgmt_free(struct ath12k *ar, int buf_id)
 	ath12k_mgmt_over_wmi_tx_drop(ar, msdu);
 }
 
-int ath12k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx)
+void ath12k_mac_tx_mgmt_pending_free(struct ath12k *ar)
 {
-	struct ath12k *ar = ctx;
-
-	ath12k_mac_tx_mgmt_free(ar, buf_id);
+	struct sk_buff *msdu;
+	int buf_id;
 
-	return 0;
+	idr_for_each_entry(&ar->txmgmt_idr, msdu, buf_id)
+		ath12k_mac_tx_mgmt_free(ar, buf_id);
 }
 
 static void ath12k_mac_vif_txmgmt_cleanup(struct ath12k *ar,
@@ -13977,7 +13977,7 @@ static struct wiphy_iftype_ext_capab ath12k_iftypes_ext_capa[] = {
 
 static void ath12k_mac_cleanup_unregister(struct ath12k *ar)
 {
-	idr_for_each(&ar->txmgmt_idr, ath12k_mac_tx_mgmt_pending_free, ar);
+	ath12k_mac_tx_mgmt_pending_free(ar);
 	idr_destroy(&ar->txmgmt_idr);
 
 	kfree(ar->mac.sbands[NL80211_BAND_2GHZ].channels);
drivers/net/wireless/ath/ath12k/mac.h +1 -1
index 1f689e367c8a1..0d75fae5c7bf7 100644
@@ -172,7 +172,7 @@ struct ath12k *ath12k_mac_get_ar_by_pdev_id(struct ath12k_base *ab, u32 pdev_id)
 
 void ath12k_mac_drain_tx(struct ath12k *ar);
 void ath12k_mac_peer_cleanup_all(struct ath12k *ar);
-int ath12k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx);
+void ath12k_mac_tx_mgmt_pending_free(struct ath12k *ar);
 enum rate_info_bw ath12k_mac_bw_to_mac80211_bw(enum ath12k_supported_bw bw);
 enum ath12k_supported_bw ath12k_mac_mac80211_bw_to_ath12k_bw(enum rate_info_bw bw);
 enum hal_encrypt_type ath12k_dp_tx_get_encrypt_type(u32 cipher);
Signature · 1 line
2.53.0
author maintainer
#593 lore raw

PATCH 592/990 bnge: skip dev_addr when building the VNIC unicast list

In reply to Greg Kroah-Hartman

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

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

From: Vikas Gupta <[email protected]>

[ Upstream commit 0b3fc7fe6f3f68569b9f9139893491b61a4b45b9 ]

The default VNIC programs the device's MAC as L2 filter 0 in bnge_init_chip() via bnge_hwrm_set_vnic_filter(bn, 0, 0, dev_addr). bnge_cfg_rx_mode() then walks dev->uc and programs each unicast address as a further L2 filter, without excluding dev_addr.

Skip dev_addr when building uc_list, since it is already installed as filter 0. As dev_addr now takes neither a uc_list slot nor an l2_filters[] slot, count only the non-dev_addr entries for the uc_list overflow check too, otherwise an input such as {dev_addr, A, B, C} would needlessly fall back to promiscuous mode even though A, B and C fit in exact-match filters. bnge_uc_list_updated() applies the same skip and count so the change detection stays consistent and does not loop.

This issue was caught by Sashiko (nipa).

Tested on Thor Ultra device.

Fixes 9afad4a17174 ("bng_en: Configure default VNIC")
[ sashal: Adapted to the older API: kept dev-based netdev_for_each_uc_addr() iteration and locking in bnge_cfg_def_vnic() instead of the upstream uc/snapshot parameters and bnge_cfg_rx_mode(). ]
---
 .../net/ethernet/broadcom/bnge/bnge_netdev.c  | 27 +++++++++++++------
 1 file changed, 19 insertions(+), 8 deletions(-)
drivers/net/ethernet/broadcom/bnge/bnge_netdev.c +19 -8
index 02be751f3d8fc..d1c55ac9318f2 100644
@@ -1670,18 +1670,19 @@ static bool bnge_uc_list_updated(struct bnge_net *bn)
 	struct bnge_vnic_info *vnic = &bn->vnic_info[BNGE_VNIC_DEFAULT];
 	struct net_device *dev = bn->netdev;
 	struct netdev_hw_addr *ha;
-	int off = 0;
-
-	if (netdev_uc_count(dev) != (vnic->uc_filter_count - 1))
-		return true;
+	int off = 0, count = 0;
 
 	netdev_for_each_uc_addr(ha, dev) {
+		if (ether_addr_equal(ha->addr, dev->dev_addr))
+			continue;
+		if (count >= vnic->uc_filter_count - 1)
+			return true;
 		if (!ether_addr_equal(ha->addr, vnic->uc_list + off))
 			return true;
-
 		off += ETH_ALEN;
+		count++;
 	}
-	return false;
+	return count != vnic->uc_filter_count - 1;
 }
 
 static bool bnge_promisc_ok(struct bnge_net *bn)
@@ -1693,9 +1694,9 @@ static int bnge_cfg_def_vnic(struct bnge_net *bn)
 {
 	struct bnge_vnic_info *vnic = &bn->vnic_info[BNGE_VNIC_DEFAULT];
 	struct net_device *dev = bn->netdev;
+	int i, off = 0, rc, uc_count = 0;
 	struct bnge_dev *bd = bn->bd;
 	struct netdev_hw_addr *ha;
-	int i, off = 0, rc;
 	bool uc_update;
 
 	netif_addr_lock_bh(dev);
@@ -1715,10 +1716,20 @@ static int bnge_cfg_def_vnic(struct bnge_net *bn)
 	vnic->uc_filter_count = 1;
 
 	netif_addr_lock_bh(dev);
-	if (netdev_uc_count(dev) > (BNGE_MAX_UC_ADDRS - 1)) {
+	/* dev_addr is already programmed as L2 filter 0, so it takes neither a
+	 * uc_list slot nor an l2_filters[] slot. Count only the entries that
+	 * will actually be programmed so the overflow check matches the fill
+	 * loop below (and bnge_uc_list_updated()).
+	 */
+	netdev_for_each_uc_addr(ha, dev)
+		if (!ether_addr_equal(ha->addr, dev->dev_addr))
+			uc_count++;
+	if (uc_count > BNGE_MAX_UC_ADDRS - 1) {
 		vnic->rx_mask |= CFA_L2_SET_RX_MASK_REQ_MASK_PROMISCUOUS;
 	} else {
 		netdev_for_each_uc_addr(ha, dev) {
+			if (ether_addr_equal(ha->addr, dev->dev_addr))
+				continue;
 			memcpy(vnic->uc_list + off, ha->addr, ETH_ALEN);
 			off += ETH_ALEN;
 			vnic->uc_filter_count++;
Signature · 1 line
2.53.0
author maintainer
#594 lore raw

PATCH 593/990 RDMA/bnxt_re: Use kvzalloc for QP table allocation

In reply to Greg Kroah-Hartman

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

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

From: Abhishek Mohapatra <[email protected]>

[ Upstream commit 724a39b36af94787d32094da87729f24a28888b7 ]

The QP table size depends on the firmware reported max_qp, so it can be large and a physically contiguous kzalloc may fail. Use kvzalloc_objs() and free it with kvfree().

Fixes 82f1f575aa13 ("RDMA/bnxt_re: Fix allocation of QP table")
[ sashal: Replaced kzalloc_objs() with kvcalloc() for the QP table allocation, since the older kcalloc() form is what this branch had and kvzalloc_objs() doesn't exist here. ]
---
 drivers/infiniband/hw/bnxt_re/qplib_res.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/infiniband/hw/bnxt_re/qplib_res.c +3 -3
index d92db77e7ed50..ad0ba952eb48d 100644
@@ -867,7 +867,7 @@ int bnxt_qplib_init_res(struct bnxt_qplib_res *res)
 
 void bnxt_qplib_free_res(struct bnxt_qplib_res *res)
 {
-	kfree(res->rcfw->qp_tbl);
+	kvfree(res->rcfw->qp_tbl);
 	bnxt_qplib_free_sgid_tbl(res, &res->sgid_tbl);
 	bnxt_qplib_free_pd_tbl(&res->pd_tbl);
 	bnxt_qplib_free_dpi_tbl(res, &res->dpi_tbl);
@@ -884,8 +884,8 @@ int bnxt_qplib_alloc_res(struct bnxt_qplib_res *res, struct net_device *netdev)
 
 	/* Allocate one extra to hold the QP1 entries */
 	rcfw->qp_tbl_size = max_t(u32, BNXT_RE_MAX_QPC_COUNT + 1, dev_attr->max_qp);
-	rcfw->qp_tbl = kcalloc(rcfw->qp_tbl_size, sizeof(struct bnxt_qplib_qp_node),
-			       GFP_KERNEL);
+	rcfw->qp_tbl = kvcalloc(rcfw->qp_tbl_size, sizeof(struct bnxt_qplib_qp_node),
+				GFP_KERNEL);
 	if (!rcfw->qp_tbl)
 		return -ENOMEM;
 
Signature · 1 line
2.53.0
author maintainer
#595 lore raw

PATCH 594/990 RDMA/bnxt_re: Unpublish QP table before freeing it

In reply to Greg Kroah-Hartman

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

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

From: Selvin Xavier <[email protected]>

[ Upstream commit 978361dd2ccff357d4fe6aac6ce057d1bfae8312 ]

bnxt_re_dev_uninit() frees the QP table before the RCFW channel is disabled, so the CREQ tasklet can still look up rcfw->qp_tbl while it is being freed.

Clear rcfw->qp_tbl under tbl_lock before freeing it, and have the QP error notification handler bail out if the table is gone.

Fixes 82f1f575aa13 ("RDMA/bnxt_re: Fix allocation of QP table")
---
 drivers/infiniband/hw/bnxt_re/qplib_rcfw.c |  4 ++++
 drivers/infiniband/hw/bnxt_re/qplib_res.c  | 10 +++++++++-
 2 files changed, 13 insertions(+), 1 deletion(-)
drivers/infiniband/hw/bnxt_re/qplib_rcfw.c +4 -0
index 4dad0cfcfa98d..a70aa6a83da3b 100644
@@ -638,6 +638,10 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw,
 		err_event = (struct creq_qp_error_notification *)qp_event;
 		qp_id = le32_to_cpu(err_event->xid);
 		spin_lock(&rcfw->tbl_lock);
+		if (!rcfw->qp_tbl) {
+			spin_unlock(&rcfw->tbl_lock);
+			break;
+		}
 		tbl_indx = map_qp_id_to_tbl_indx(qp_id, rcfw);
 		qp = rcfw->qp_tbl[tbl_indx].qp_handle;
 		if (!qp) {
drivers/infiniband/hw/bnxt_re/qplib_res.c +9 -1
index ad0ba952eb48d..5948e1f11384e 100644
@@ -867,7 +867,15 @@ int bnxt_qplib_init_res(struct bnxt_qplib_res *res)
 
 void bnxt_qplib_free_res(struct bnxt_qplib_res *res)
 {
-	kvfree(res->rcfw->qp_tbl);
+	struct bnxt_qplib_rcfw *rcfw = res->rcfw;
+	struct bnxt_qplib_qp_node *qp_tbl;
+
+	/* The CREQ tasklet may still be running; unpublish the table first */
+	spin_lock_bh(&rcfw->tbl_lock);
+	qp_tbl = rcfw->qp_tbl;
+	rcfw->qp_tbl = NULL;
+	spin_unlock_bh(&rcfw->tbl_lock);
+	kvfree(qp_tbl);
 	bnxt_qplib_free_sgid_tbl(res, &res->sgid_tbl);
 	bnxt_qplib_free_pd_tbl(&res->pd_tbl);
 	bnxt_qplib_free_dpi_tbl(res, &res->dpi_tbl);
Signature · 1 line
2.53.0
author maintainer
#596 lore raw

PATCH 595/990 Bluetooth: btintel_pcie: remove duplicate BTINTEL_PCIE_MAGIC_NUM definition

In reply to Greg Kroah-Hartman

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

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

From: Chandrashekar Devegowda <[email protected]>

[ Upstream commit 937363063afde2dce1f45d8f22514db99b9eba6b ]

Two identical definitions of BTINTEL_PCIE_MAGIC_NUM were present in btintel_pcie.c, one indented with spaces and one with a tab. Remove the space-indented duplicate and the surrounding blank lines. Kernel coding style requires tabs for indentation, so keep the tab-indented copy.

No functional change.

Assisted-by Copilot:claude-opus-4.7 sparse
Fixes 6ed83047389c ("Bluetooth: btintel_pcie: Setup buffers for firmware traces")
[ sashal: Removed the duplicate space-indented BTINTEL_PCIE_MAGIC_NUM define and one blank line, since the two defines are not adjacent in this tree and the context differed. ]
---
 drivers/bluetooth/btintel_pcie.c | 2 --
 1 file changed, 2 deletions(-)
drivers/bluetooth/btintel_pcie.c +0 -2
index 3e8c894fbf640..75bbb2bb6be55 100644
@@ -63,8 +63,6 @@ struct btintel_pcie_dev_recovery {
 #define BTINTEL_PCIE_HCI_EVT_PKT	0x00000004
 #define BTINTEL_PCIE_HCI_ISO_PKT	0x00000005
 
-#define BTINTEL_PCIE_MAGIC_NUM    0xA5A5A5A5
-
 #define BTINTEL_PCIE_BLZR_HWEXP_SIZE		1024
 #define BTINTEL_PCIE_BLZR_HWEXP_DMP_ADDR	0xB00A7C00
 
Signature · 1 line
2.53.0
author maintainer
#597 lore raw

PATCH 596/990 Bluetooth: btintel_pcie: fix PM flow for S0ix, S3 and S4

In reply to Greg Kroah-Hartman

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

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

From: Ravindra <[email protected]>

[ Upstream commit 2926eb396711f1f843a0aafee6778822f50e9021 ]

Fix two issues in the PM suspend/resume path:

1. S3 was handled the same as S0ix, keeping the controller on the D3hot-style path. That caused resume instability because S3 can remove power from the controller, unlike s2idle/S0ix. Use pm_suspend_target_state to distinguish them: D3_HOT for S0ix and D3_COLD for S3/S4. Add .restore to force FLR-based firmware recovery after S4 and S3 (PM_SUSPEND_MEM), as power is lost. S0ix resumes via a normal D0 transition.

2. During hibernation, .freeze() puts the controller into the D3cold state without any loss of power, and the flow normally continues to .poweroff(). If hibernation instead fails, .thaw() is called to bring the controller back up, and the old code routed it through btintel_pcie_resume(), which forced FLR-based firmware recovery whenever data->pm_sx_event was PM_EVENT_FREEZE. That check was
incorrect: since the controller's power was never actually removed on this failed-hibernation path, FLR-based recovery is unnecessary. Remove pm_sx_event and route .thaw through a normal D0 transition instead; FLR-based recovery is retained only in .restore, where genuine S4 power loss requires it.

Tested with:
S0ix: sudo sh -c 'echo "+40" > /sys/class/rtc/rtc0/wakealarm' && \
echo freeze | sudo tee /sys/power/state
S3: sudo rtcwake -m mem -s 60
S4: sudo rtcwake -m disk -s 60

Fixes e57362f4911b ("Bluetooth: btintel_pcie: Add support for _suspend() / _resume()")
Assisted-by GitHub-Copilot:GPT5
[ sashal: Replaced the btintel_pcie_request_reset(data, FLR) call with btintel_pcie_reset() and kept the gp0_received = false resets, because the set_dxstate retry rework is missing here. ]
---
 drivers/bluetooth/btintel_pcie.c | 45 +++++++++++++++++++++-----------
 drivers/bluetooth/btintel_pcie.h |  2 --
 2 files changed, 30 insertions(+), 17 deletions(-)
drivers/bluetooth/btintel_pcie.c +30 -15
index 75bbb2bb6be55..3799e5b20d5f7 100644
@@ -13,6 +13,7 @@
 #include <linux/wait.h>
 #include <linux/delay.h>
 #include <linux/interrupt.h>
+#include <linux/suspend.h>
 
 #include <linux/unaligned.h>
 #include <linux/devcoredump.h>
@@ -2580,10 +2581,12 @@ static int btintel_pcie_suspend_late(struct device *dev, pm_message_t mesg)
 
 	data = pci_get_drvdata(pdev);
 
-	dxstate = (mesg.event == PM_EVENT_SUSPEND ?
-		   BTINTEL_PCIE_STATE_D3_HOT : BTINTEL_PCIE_STATE_D3_COLD);
-
-	data->pm_sx_event = mesg.event;
+	/* S0ix (s2idle) uses D3_HOT; S3, freeze and hibernate use D3_COLD. */
+	if (mesg.event == PM_EVENT_SUSPEND &&
+	    pm_suspend_target_state == PM_SUSPEND_TO_IDLE)
+		dxstate = BTINTEL_PCIE_STATE_D3_HOT;
+	else
+		dxstate = BTINTEL_PCIE_STATE_D3_COLD;
 
 	data->gp0_received = false;
 
@@ -2622,7 +2625,7 @@ static int btintel_pcie_freeze(struct device *dev)
 	return btintel_pcie_suspend_late(dev, PMSG_FREEZE);
 }
 
-static int btintel_pcie_resume(struct device *dev)
+static int btintel_pcie_resume_event(struct device *dev, pm_message_t mesg)
 {
 	struct pci_dev *pdev = to_pci_dev(dev);
 	struct btintel_pcie_data *data;
@@ -2634,15 +2637,12 @@ static int btintel_pcie_resume(struct device *dev)
 
 	start = ktime_get();
 
-	/* When the system enters S4 (hibernate) mode, bluetooth device loses
-	 * power, which results in the erasure of its loaded firmware.
-	 * Consequently, function level reset (flr) is required on system
-	 * resume to bring the controller back into an operational state by
-	 * initiating a new firmware download.
+	/* S3 and S4 may cut power, erasing the firmware. Force FLR to recover
+	 * instead of a normal D0 transition.
 	 */
-
-	if (data->pm_sx_event == PM_EVENT_FREEZE ||
-	    data->pm_sx_event == PM_EVENT_HIBERNATE) {
+	if (mesg.event == PM_EVENT_RESTORE ||
+	    (mesg.event == PM_EVENT_RESUME &&
+	     pm_suspend_target_state == PM_SUSPEND_MEM)) {
 		set_bit(BTINTEL_PCIE_CORE_HALTED, &data->flags);
 		btintel_pcie_reset(data->hdev);
 		return 0;
@@ -2685,13 +2685,28 @@ static int btintel_pcie_resume(struct device *dev)
 	return 0;
 }
 
+static int btintel_pcie_resume(struct device *dev)
+{
+	return btintel_pcie_resume_event(dev, PMSG_RESUME);
+}
+
+static int btintel_pcie_restore(struct device *dev)
+{
+	return btintel_pcie_resume_event(dev, PMSG_RESTORE);
+}
+
+static int btintel_pcie_thaw(struct device *dev)
+{
+	return btintel_pcie_resume_event(dev, PMSG_THAW);
+}
+
 static const struct dev_pm_ops btintel_pcie_pm_ops = {
 	.suspend = btintel_pcie_suspend,
 	.resume = btintel_pcie_resume,
 	.freeze = btintel_pcie_freeze,
-	.thaw = btintel_pcie_resume,
+	.thaw = btintel_pcie_thaw,
 	.poweroff = btintel_pcie_hibernate,
-	.restore = btintel_pcie_resume,
+	.restore = btintel_pcie_restore,
 };
 
 static struct pci_driver btintel_pcie_driver = {
drivers/bluetooth/btintel_pcie.h +0 -2
index 481de85456e2b..43be595d20b65 100644
@@ -461,7 +461,6 @@ struct btintel_pcie_dump_header {
  * @txq: TX Queue struct
  * @rxq: RX Queue struct
  * @alive_intr_ctxt: Alive interrupt context
- * @pm_sx_event: PM event on which system got suspended
  */
 struct btintel_pcie_data {
 	struct pci_dev	*pdev;
@@ -511,7 +510,6 @@ struct btintel_pcie_data {
 	u32	alive_intr_ctxt;
 	struct btintel_pcie_dbgc	dbgc;
 	struct btintel_pcie_dump_header dmp_hdr;
-	u8	pm_sx_event;
 };
 
 static inline u32 btintel_pcie_rd_reg32(struct btintel_pcie_data *data,
Signature · 1 line
2.53.0
author maintainer
#598 lore raw

PATCH 597/990 Bluetooth: hci_event: Fix LE link drop on remote features command status

In reply to Greg Kroah-Hartman

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

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

From: Kevin Dewald <[email protected]>

[ Upstream commit 91638f53ff2b8234195ff27ec913e068269a28e9 ]

When the local controller supports peripheral-initiated features exchange, the LE Read Remote Features procedure also runs for incoming connections, and it fails with Unsupported Remote Feature (0x1a) if the central does not support that feature. hci_le_remote_feat_complete_evt() and hci_le_read_all_remote_features_evt() handle this and let the connection transition into connected state.

A controller can also return that error in the Command Status event instead. An Intel controller does so for a central that does not support peripheral-initiated features exchange, presumably because it already has the features of the central. hci_cs_le_read_remote_features() and hci_cs_le_read_all_remote_features() then confirm the connection as failed while it is still in BT_CONFIG, and the hci_conn_drop() in le_read_features_complete() disconnects it right away:

Quoted 1 line

HCI Event: LE Meta Event (0x3e) plen 31

      LE Enhanced Connection Complete (0x0a)
        Status: Success (0x00)
        Role: Peripheral (0x01)

< HCI Command: LE Read Remote Used Features (0x08|0x0016) plen 2

Quoted 1 line

HCI Event: Command Status (0x0f) plen 4

      LE Read Remote Used Features (0x08|0x0016) ncmd 1
        Status: Unsupported Remote Feature / Unsupported LMP Feature (0x1a)
  < HCI Command: Disconnect (0x01|0x0006) plen 3
        Reason: Remote User Terminated Connection (0x13)

Data the central sends afterwards is reported as:

Bluetooth: hci0: ACL packet for unknown connection handle 3585

Handle Unsupported Remote Feature in the command status the same way as in the complete events.

Fixes 0fe29fd1cd77 ("Bluetooth: Read LE remote features during connection establishment")
Fixes a106e50be74b ("Bluetooth: HCI: Add support for LL Extended Feature Set")
Assisted-by Claude:claude-opus-5.5
[ sashal: Dropped the hunk for hci_cs_le_read_all_remote_features() (function absent here) and placed the fix inside the nested if (conn) { if (conn->state == BT_CONFIG) } form of hci_cs_le_read_remote_features(). ]
---
 net/bluetooth/hci_event.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
net/bluetooth/hci_event.c +16 -0
index 3e487963eaff9..797b86f57c6db 100644
@@ -2941,6 +2941,22 @@ static void hci_cs_le_read_remote_features(struct hci_dev *hdev, u8 status)
 	conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(cp->handle));
 	if (conn) {
 		if (conn->state == BT_CONFIG) {
+			/* If the local controller supports peripheral-initiated
+			 * features exchange, but the remote controller does not,
+			 * then the controller may already return the error code
+			 * 0x1a for unsupported remote feature in the command
+			 * status.
+			 *
+			 * Handle it as hci_le_remote_feat_complete_evt() does and
+			 * allow the connection to transition into connected state.
+			 */
+			if (!conn->out &&
+			    status == HCI_ERROR_UNSUPPORTED_REMOTE_FEATURE &&
+			    (hdev->le_features[0] & HCI_LE_PERIPHERAL_FEATURES)) {
+				conn->state = BT_CONNECTED;
+				status = 0x00;
+			}
+
 			hci_connect_cfm(conn, status);
 			hci_conn_drop(conn);
 		}
Signature · 1 line
2.53.0
author maintainer
#599 lore raw

PATCH 598/990 irqchip/mst-intc: Validate the DT interrupt range

In reply to Greg Kroah-Hartman

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

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

From: Pengpeng Hou <[email protected]>

[ Upstream commit 16f25d326e5d3b9fd51bc5e3916ecbffbca63e7b ]

The driver takes an inclusive interrupt range from the device tree without checking its endpoints. A reversed range wraps the unsigned count calculation, and a range larger than MST_INTC_MAX_IRQS exceeds the controller capacity used by the driver.

Reject these ranges before calculating nr_irqs or creating the domain. Check the difference after ordering the endpoints so the validation itself cannot wrap.

The issue was found by our static-analysis tool.

Fixes ad4c938c92af ("irqchip/irq-mst: Add MStar interrupt controller support")
Assisted-by gpt 5
[ sashal: Context adjusted: the upstream range check is inserted above this tree's older kzalloc(sizeof(*cd), GFP_KERNEL) call instead of kzalloc_obj(*cd). ]
---
 drivers/irqchip/irq-mst-intc.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/irqchip/irq-mst-intc.c +3 -0
index 7f760f555a76a..d380030eda935 100644
@@ -263,6 +263,9 @@ static int __init mst_intc_of_init(struct device_node *dn,
 	    of_property_read_u32_index(dn, "mstar,irqs-map-range", 1, &irq_end))
 		return -EINVAL;
 
+	if (irq_end < irq_start || irq_end - irq_start >= MST_INTC_MAX_IRQS)
+		return -EINVAL;
+
 	cd = kzalloc(sizeof(*cd), GFP_KERNEL);
 	if (!cd)
 		return -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#600 lore raw

PATCH 599/990 pinctrl: stm32: Fix the unit of the hwspinlock timeout

In reply to Greg Kroah-Hartman

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

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

From: Ju Nan <[email protected]>

[ Upstream commit 544b3f8042dd7c18baa48dcb1a393ff8b6742322 ]

HWSPNLCK_TIMEOUT is passed to hwspin_lock_timeout_in_atomic(), whose timeout argument is in milliseconds, not microseconds:

  atomic_delay += HWSPINLOCK_RETRY_DELAY_US;
  if (atomic_delay > to * 1000)
          return -ETIMEDOUT;

The hwspinlock core documents this explicitly:

If the mode is HWLOCK_IN_ATOMIC (called from an atomic context) the timeout is handled with busy-waiting delays, hence shall not exceed few msecs.

Fixes 290a9f937e5a ("pinctrl: stm32: use the hwspin_lock_timeout_in_atomic() API")
[ sashal: Dropped the two hunks touching the skipped I/O-sync and skew-delay functions (absent here), so only the HWSPNLCK_TIMEOUT_MS rename and the five existing callers apply. ]
---
 drivers/pinctrl/stm32/pinctrl-stm32.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
drivers/pinctrl/stm32/pinctrl-stm32.c +6 -6
index 384fdc13a504b..8f9935d07e432 100644
@@ -82,7 +82,7 @@
 #define gpio_range_to_bank(chip) \
 		container_of(chip, struct stm32_gpio_bank, range)
 
-#define HWSPNLCK_TIMEOUT	1000 /* usec */
+#define HWSPNLCK_TIMEOUT_MS	1
 
 static const char * const stm32_gpio_functions[] = {
 	"gpio", "af0", "af1",
@@ -559,7 +559,7 @@ static int stm32_gpio_domain_activate(struct irq_domain *d,
 
 	if (pctl->hwlock) {
 		ret = hwspin_lock_timeout_in_atomic(pctl->hwlock,
-						    HWSPNLCK_TIMEOUT);
+						    HWSPNLCK_TIMEOUT_MS);
 		if (ret) {
 			dev_err(pctl->dev, "Can't get hwspinlock\n");
 			return ret;
@@ -896,7 +896,7 @@ static int stm32_pmx_set_mode(struct stm32_gpio_bank *bank,
 
 	if (pctl->hwlock) {
 		err = hwspin_lock_timeout_in_atomic(pctl->hwlock,
-						    HWSPNLCK_TIMEOUT);
+						    HWSPNLCK_TIMEOUT_MS);
 		if (err) {
 			dev_err(pctl->dev, "Can't get hwspinlock\n");
 			goto unlock;
@@ -1033,7 +1033,7 @@ static int stm32_pconf_set_driving(struct stm32_gpio_bank *bank,
 
 	if (pctl->hwlock) {
 		err = hwspin_lock_timeout_in_atomic(pctl->hwlock,
-						    HWSPNLCK_TIMEOUT);
+						    HWSPNLCK_TIMEOUT_MS);
 		if (err) {
 			dev_err(pctl->dev, "Can't get hwspinlock\n");
 			goto unlock;
@@ -1084,7 +1084,7 @@ static int stm32_pconf_set_speed(struct stm32_gpio_bank *bank,
 
 	if (pctl->hwlock) {
 		err = hwspin_lock_timeout_in_atomic(pctl->hwlock,
-						    HWSPNLCK_TIMEOUT);
+						    HWSPNLCK_TIMEOUT_MS);
 		if (err) {
 			dev_err(pctl->dev, "Can't get hwspinlock\n");
 			goto unlock;
@@ -1135,7 +1135,7 @@ static int stm32_pconf_set_bias(struct stm32_gpio_bank *bank,
 
 	if (pctl->hwlock) {
 		err = hwspin_lock_timeout_in_atomic(pctl->hwlock,
-						    HWSPNLCK_TIMEOUT);
+						    HWSPNLCK_TIMEOUT_MS);
 		if (err) {
 			dev_err(pctl->dev, "Can't get hwspinlock\n");
 			goto unlock;
Signature · 1 line
2.53.0
author maintainer
#601 lore raw

PATCH 600/990 dpll: zl3073x: make embedded sync follow the output carrier frequency

In reply to Greg Kroah-Hartman

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

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

From: Ivan Vecera <[email protected]>

[ Upstream commit bf6f105f2cb6477e36a9312477d0aa32a43aa13d ]

The eSync period and width are relative to the output carrier, but changing the output frequency did not update them, so eSync ran at a wrong frequency and duty cycle. For a 1 Hz carrier esync_get() returns -EOPNOTSUPP, so eSync left enabled could not be disabled.

Factor out zl3073x_out_esync_{is_enabled,enable,disable}() helpers and use them in frequency_set() to recompute the eSync period and width for the new carrier, or to disable eSync for a 1 Hz carrier.

Also compute the reported pulse width in 64 bits, as 50 * esync_n_width overflows u32 for low carrier frequencies.

Hit during development, confirmed on an oscilloscope.

Fixes ce26d7ca50a5 ("dpll: zl3073x: Add support to get/set frequency on pins")
Fixes 634ca2cb06d2 ("dpll: zl3073x: Add support to get/set esync on pins")
[ sashal: adapted new eSync helpers in out.h to open-code clock type get/set with FIELD_GET/FIELD_PREP, and rebased esync_get/esync_set onto the older open-coded form, since the clock type accessors are missing. ]
---
 drivers/dpll/zl3073x/dpll.c | 56 ++++++++++++++++++-------------------
 drivers/dpll/zl3073x/out.h  | 40 ++++++++++++++++++++++++++
 2 files changed, 67 insertions(+), 29 deletions(-)
drivers/dpll/zl3073x/dpll.c +27 -29
index c2ea96df3bcb6..75a8584e6368f 100644
@@ -771,7 +771,7 @@ zl3073x_dpll_output_pin_esync_get(const struct dpll_pin *dpll_pin,
 	const struct zl3073x_synth *synth;
 	const struct zl3073x_out *out;
 	u32 synth_freq, out_freq;
-	u8 clock_type, out_id;
+	u8 out_id;
 
 	out_id = zl3073x_output_pin_out_get(pin->id);
 	out = zl3073x_out_state_get(zldev, out_id);
@@ -794,8 +794,7 @@ zl3073x_dpll_output_pin_esync_get(const struct dpll_pin *dpll_pin,
 	esync->range = esync_freq_ranges;
 	esync->range_num = ARRAY_SIZE(esync_freq_ranges);
 
-	clock_type = FIELD_GET(ZL_OUTPUT_MODE_CLOCK_TYPE, out->mode);
-	if (clock_type != ZL_OUTPUT_MODE_CLOCK_TYPE_ESYNC) {
+	if (!zl3073x_out_esync_is_enabled(out)) {
 		/* No need to read esync data if it is not enabled */
 		esync->freq = 0;
 		esync->pulse = 0;
@@ -811,7 +810,7 @@ zl3073x_dpll_output_pin_esync_get(const struct dpll_pin *dpll_pin,
 	 * Note that half pulse width is in units of half synth cycles, which
 	 * is why it reduces down to be output_div.
 	 */
-	esync->pulse = (50 * out->esync_n_width) / out->div;
+	esync->pulse = div_u64(mul_u32_u32(50, out->esync_n_width), out->div);
 
 	return 0;
 }
@@ -828,7 +827,7 @@ zl3073x_dpll_output_pin_esync_set(const struct dpll_pin *dpll_pin,
 	struct zl3073x_dpll_pin *pin = pin_priv;
 	const struct zl3073x_synth *synth;
 	struct zl3073x_out out;
-	u8 clock_type, out_id;
+	u8 out_id;
 	u32 synth_freq;
 
 	out_id = zl3073x_output_pin_out_get(pin->id);
@@ -841,36 +840,18 @@ zl3073x_dpll_output_pin_esync_set(const struct dpll_pin *dpll_pin,
 	if (zl3073x_out_is_ndiv(&out))
 		return -EOPNOTSUPP;
 
-	/* Select clock type */
-	if (freq)
-		clock_type = ZL_OUTPUT_MODE_CLOCK_TYPE_ESYNC;
-	else
-		clock_type = ZL_OUTPUT_MODE_CLOCK_TYPE_NORMAL;
-
-	/* Update clock type in output mode */
-	out.mode &= ~ZL_OUTPUT_MODE_CLOCK_TYPE;
-	out.mode |= FIELD_PREP(ZL_OUTPUT_MODE_CLOCK_TYPE, clock_type);
-
-	/* If esync is being disabled just write mailbox and finish */
-	if (!freq)
-		goto write_mailbox;
+	if (!freq) {
+		zl3073x_out_esync_disable(&out);
+		return zl3073x_out_state_set(zldev, out_id, &out);
+	}
 
 	/* Get attached synth frequency */
 	synth = zl3073x_synth_state_get(zldev, zl3073x_out_synth_get(&out));
 	synth_freq = zl3073x_synth_freq_get(synth);
 
-	/* Compute and update esync period */
-	out.esync_n_period = synth_freq / (u32)freq / out.div;
-
-	/* Half of the period in units of 1/2 synth cycle can be represented by
-	 * the output_div. To get the supported esync pulse width of 25% of the
-	 * period the output_div can just be divided by 2. Note that this
-	 * assumes that output_div is even, otherwise some resolution will be
-	 * lost.
-	 */
-	out.esync_n_width = out.div / 2;
+	/* Enable 1PPS eSync for this pin frequency */
+	zl3073x_out_esync_enable(&out, synth_freq / out.div);
 
-write_mailbox:
 	/* Commit output configuration */
 	return zl3073x_out_state_set(zldev, out_id, &out);
 }
@@ -924,6 +905,23 @@ zl3073x_dpll_output_pin_frequency_set(const struct dpll_pin *dpll_pin,
 		/* For 50/50 duty cycle the divisor is equal to width */
 		out.width = new_div;
 
+		/* The embedded sync period and width are computed relative to
+		 * the output carrier so they have to be adjusted to follow the
+		 * new frequency.
+		 */
+		if (zl3073x_out_esync_is_enabled(&out)) {
+			if (frequency == 1) {
+				/* eSync cannot work on a 1 Hz carrier */
+				zl3073x_out_esync_disable(&out);
+			} else {
+				/* Update esync period and width according to
+				 * the new frequency.
+				 */
+				zl3073x_out_esync_enable(&out,
+							 synth_freq / out.div);
+			}
+		}
+
 		/* Commit output configuration */
 		return zl3073x_out_state_set(zldev, out_id, &out);
 	}
drivers/dpll/zl3073x/out.h +40 -0
index 318f9bb8da3a0..1f2cda4d37fcf 100644
@@ -107,4 +107,44 @@ static inline u8 zl3073x_out_synth_get(const struct zl3073x_out *out)
 	return FIELD_GET(ZL_OUTPUT_CTRL_SYNTH_SEL, out->ctrl);
 }
 
+static inline bool zl3073x_out_esync_is_enabled(const struct zl3073x_out *out)
+{
+	u8 clock_type = FIELD_GET(ZL_OUTPUT_MODE_CLOCK_TYPE, out->mode);
+
+	return clock_type == ZL_OUTPUT_MODE_CLOCK_TYPE_ESYNC;
+}
+
+static inline
+void zl3073x_out_esync_enable(struct zl3073x_out *out, u32 base_freq)
+{
+	/* Period is expressed as the number of output divider clock cycles.
+	 * So for 1 Hz the period is equal to base frequency.
+	 */
+	out->esync_n_period = base_freq;
+
+	/* Half of the period in units of 1/2 synth cycle can be represented by
+	 * the output_div. To get the supported esync pulse width of 25% of the
+	 * period the output_div can just be divided by 2. Note that this
+	 * assumes that output_div is even, otherwise some resolution will be
+	 * lost.
+	 */
+	out->esync_n_width = out->div / 2;
+
+	/* Update the clock type */
+	out->mode &= ~ZL_OUTPUT_MODE_CLOCK_TYPE;
+	out->mode |= FIELD_PREP(ZL_OUTPUT_MODE_CLOCK_TYPE,
+				ZL_OUTPUT_MODE_CLOCK_TYPE_ESYNC);
+}
+
+static inline
+void zl3073x_out_esync_disable(struct zl3073x_out *out)
+{
+	/* Just update the clock type. The eSync period and width are
+	 * ignored for this clock type.
+	 */
+	out->mode &= ~ZL_OUTPUT_MODE_CLOCK_TYPE;
+	out->mode |= FIELD_PREP(ZL_OUTPUT_MODE_CLOCK_TYPE,
+				ZL_OUTPUT_MODE_CLOCK_TYPE_NORMAL);
+}
+
 #endif /* _ZL3073X_OUT_H */
Signature · 1 line
2.53.0
author maintainer
#602 lore raw

PATCH 601/990 bpf: Dont hand out a linked element as extra element

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit ccb88db8dac8fabde58656d5d4a33711e89c480a ]

When htab_map_update_elem() replaces an element of a preallocated map, alloc_htab_elem() takes the spare element of this cpu and puts the old element into the per-cpu slot right away, long before the old element is unlinked from its bucket. The bucket lock disables interrupts, but it does not keep out an NMI, or a tracing program on the return of alloc_htab_elem(). bpf_prog_active only helps if both programs are kprobe, tracepoint or perf_event programs. A program that updates an existing key in another bucket of the same map gets to use the slot:

htab_map_update_elem(k1) tc, xdp, fentry, raw_tp, ...
alloc_htab_elem()
l_new = *pl_new
*pl_new = l_old still linked in bucket 1
<NMI>
htab_map_update_elem(k2) perf_event program
l_new = *pl_new the l_old of the outer update
hlist_nulls_add_head_rcu(l_new, bucket 2) hlist_nulls_del_rcu(k2's old element)
</NMI>
hlist_nulls_add_head_rcu(l_new, bucket 1) hlist_nulls_del_rcu(l_old)

If l_old was the first element of bucket 1, the outer add points its pprev at l_new, and the delete takes it out of bucket 1 only. l_new->next now leads into bucket 2, where l_old stays with a poisoned pprev, on which a delete of k2 crashes. If it was not the first, the delete takes it out of bucket 2: k2 is gone from the map, and the chain of bucket 1 still contains l_old, whose next pointer leads into bucket 2.

Either way a walk of bucket 1 ends on the nulls value of bucket 2. lookup_nulls_elem_raw() restarts whenever that happens, so every lookup in bucket 1 which does not find its key spins forever:

  rcu: INFO: rcu_preempt detected stalls on CPUs/tasks:
   __htab_map_lookup_elem+0x354/0x4d0

  BUG: KASAN: wild-memory-access in htab_map_delete_elem+0x30c/0x670
  Write of size 8 at addr dead000000000122 by task extra/102

An NMI between the load and the store of the slot makes both updates use the same element, with much the same result.

Empty the slot when the spare element is taken, in a way that is atomic on this cpu, and put the old element in only after it has been unlinked and its timers and the like have been cancelled. A nested update that finds the slot empty, which is the case that corrupted the map, fails with -EBUSY.

Fixes 8c290e60fa2a ("bpf: fix hashmap extra_elems logic")
[ sashal: Replaced check_and_cancel_fields() with the older check_and_free_fields() helper in htab_map_update_elem(), since the cancel helper does not exist here. ]
---
 kernel/bpf/hashtab.c | 22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)
kernel/bpf/hashtab.c +16 -6
index ffc534384f84d..95e9a760a7be3 100644
@@ -1085,11 +1085,17 @@ static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key,
 	if (prealloc) {
 		if (old_elem) {
 			/* if we're updating the existing element,
-			 * use per-cpu extra elems to avoid freelist_pop/push
+			 * use per-cpu extra elems to avoid freelist_pop/push.
+			 * The caller puts old_elem into the slot once it is
+			 * unlinked. Until then the slot is empty for an NMI
+			 * or a kprobe that updates this map on this cpu.
 			 */
 			pl_new = this_cpu_ptr(htab->extra_elems);
-			l_new = *pl_new;
-			*pl_new = old_elem;
+			l_new = READ_ONCE(*pl_new);
+			do {
+				if (!l_new)
+					return ERR_PTR(-EBUSY);
+			} while (!try_cmpxchg_local(pl_new, &l_new, NULL));
 		} else {
 			struct pcpu_freelist_node *l;
 
@@ -1251,11 +1257,15 @@ static long htab_map_update_elem(struct bpf_map *map, void *key, void *value,
 	if (l_old) {
 		hlist_nulls_del_rcu(&l_old->hash_node);
 
-		/* l_old has already been stashed in htab->extra_elems, free
-		 * its special fields before it is available for reuse.
+		/*
+		 * l_old replaces the extra element that alloc_htab_elem() took.
+		 * Free its special fields first: once it is in the
+		 * slot, the next update on this cpu can reuse it.
 		 */
-		if (htab_is_prealloc(htab))
+		if (htab_is_prealloc(htab)) {
 			check_and_free_fields(htab, l_old);
+			WRITE_ONCE(*this_cpu_ptr(htab->extra_elems), l_old);
+		}
 	}
 	htab_unlock_bucket(b, flags);
 	if (l_old && !htab_is_prealloc(htab))
Signature · 1 line
2.53.0
author maintainer
#603 lore raw

PATCH 602/990 bpf: Keep a program until its bpf_wq callback has ended

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 1e28a5e52d32b7d3f4c9fb24898774f941166d2b ]

bpf_wq_work() runs the callback under rcu_read_lock_trace() only, since the callback may sleep. The program it belongs to need not be sleepable, and such a program is freed behind a plain RCU grace period. The reference that the bpf_wq holds is dropped when the map element goes, or when another callback is set, no matter whether the work is running.

If that was the last reference the program is freed under the running callback, and the worker goes on in the freed JIT image:

  Oops: int3: 0000 [#1] SMP NOPTI
  RIP: 0010:0xffffffffc0600947

All it takes is to close the map and the program while the callback runs.

Note in the program that it has a callback that runs sleepable, and wait for an RCU Tasks Trace grace period, which implies a plain one, before such a program is freed. Let bpf_wq_work() enter its read side critical section before it reads callback_fn.

bpf_task_work holds a reference to the program until the callback is done.

Fixes 8e83da9732d9 ("bpf: add bpf_wq_start")
[ sashal: Dropped the nonexistent tramp_linked context line and the __bpf_prog_put_rcu_tasks() hunk, and used bpf_prog_runs_sleepable() in the simpler if/else of __bpf_prog_put_noref(). ]
---
 include/linux/bpf.h   | 10 ++++++++++
 kernel/bpf/helpers.c  |  9 ++++++---
 kernel/bpf/syscall.c  |  2 +-
 kernel/bpf/verifier.c |  2 ++
 4 files changed, 19 insertions(+), 4 deletions(-)
include/linux/bpf.h +10 -0
index f165743cd71f3..2d8cb15fb9ba7 100644
@@ -1619,6 +1619,7 @@ struct bpf_prog_aux {
 	bool offload_requested; /* Program is bound and offloaded to the netdev. */
 	bool attach_btf_trace; /* true if attaching to BTF-enabled raw tp */
 	bool attach_tracing_prog; /* true if tracing another tracing program */
+	bool sleepable_async_cb; /* has a bpf_wq or bpf_task_work callback */
 	bool func_proto_unreliable;
 	bool tail_call_reachable;
 	bool xdp_has_frags;
@@ -1741,6 +1742,15 @@ struct bpf_prog {
 	};
 };
 
+/*
+ * Does the program, or a callback of it, run under RCU Tasks Trace protection
+ * only, outside of any RCU read side critical section?
+ */
+static inline bool bpf_prog_runs_sleepable(const struct bpf_prog *prog)
+{
+	return prog->sleepable || prog->aux->sleepable_async_cb;
+}
+
 struct bpf_array_aux {
 	/* Programs with direct jumps into programs part of this array. */
 	struct list_head poke_progs;
kernel/bpf/helpers.c +6 -3
index 89cb7e38be764..5271bc5178ea3 100644
@@ -1214,18 +1214,21 @@ static void bpf_wq_work(struct work_struct *work)
 
 	BTF_TYPE_EMIT(struct bpf_wq);
 
+	/* keeps the program that callback_fn belongs to */
+	rcu_read_lock_trace();
+
 	callback_fn = READ_ONCE(cb->callback_fn);
 	if (!callback_fn)
-		return;
+		goto out;
 
 	key = map_key_from_value(map, value, &idx);
 
-        rcu_read_lock_trace();
-        migrate_disable();
+	migrate_disable();
 
 	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
 
 	migrate_enable();
+out:
 	rcu_read_unlock_trace();
 }
 
kernel/bpf/syscall.c +1 -1
index 79668e8441419..865107eb49467 100644
@@ -2403,7 +2403,7 @@ static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
 		btf_put(prog->aux->attach_btf);
 
 	if (deferred) {
-		if (prog->sleepable)
+		if (bpf_prog_runs_sleepable(prog))
 			call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
 		else
 			call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
kernel/bpf/verifier.c +2 -0
index b664c160b9277..55d6cf2653755 100644
@@ -10891,6 +10891,8 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 					 is_async_cb_sleepable(env, insn));
 		if (IS_ERR(async_cb))
 			return PTR_ERR(async_cb);
+		if (is_async_cb_sleepable(env, insn))
+			env->prog->aux->sleepable_async_cb = true;
 		callee = async_cb->frame[0];
 		callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1;
 
Signature · 1 line
2.53.0
author maintainer
#604 lore raw

PATCH 603/990 bpf: Count sleepable callbacks as sleepable map users

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 927c9c985f3ef4d30c086884b7e0ecb933f742ef ]

map->sleepable_refcnt tells bpf_map_fd_put_ptr() whether an inner map that is taken out of its outer map has to wait for an RCU Tasks Trace grace period as well. It counts the sleepable programs that use the outer map. The bpf_wq or bpf_task_work callback of a program that is not sleepable runs under rcu_read_lock_trace() only, and is not counted.

Such a callback can look an inner map up and keep it while user space deletes it from the outer map. The inner map is freed behind a plain RCU grace period, under the callback:

  BUG: KASAN: slab-use-after-free in array_map_update_elem+0x6bc/0x7d0

Count a program with such a callback. The maps are bound before the verifier meets the callback, so raise the count of those that are bound when it does.

Fixes 8e83da9732d9 ("bpf: add bpf_wq_start")
[ sashal: Kept the local static bool is_may_goto_insn() name in the context line instead of upstream's bpf_is_may_goto_insn(), with the new helper inserted above it. ]
---
 kernel/bpf/core.c     |  2 +-
 kernel/bpf/syscall.c  |  2 +-
 kernel/bpf/verifier.c | 17 +++++++++++++++--
 3 files changed, 17 insertions(+), 4 deletions(-)
kernel/bpf/core.c +1 -1
index bbd0f1ebd2d3c..59c87eeb07cdb 100644
@@ -2908,7 +2908,7 @@ void __bpf_free_used_maps(struct bpf_prog_aux *aux,
 	bool sleepable;
 	u32 i;
 
-	sleepable = aux->prog->sleepable;
+	sleepable = bpf_prog_runs_sleepable(aux->prog);
 	for (i = 0; i < len; i++) {
 		map = used_maps[i];
 		if (map->ops->map_poke_untrack)
kernel/bpf/syscall.c +1 -1
index 865107eb49467..a076c1bc41ac3 100644
@@ -6124,7 +6124,7 @@ static int bpf_prog_bind_map(union bpf_attr *attr)
 	/* The bpf program will not access the bpf map, but for the sake of
 	 * simplicity, increase sleepable_refcnt for sleepable program as well.
 	 */
-	if (prog->sleepable)
+	if (bpf_prog_runs_sleepable(prog))
 		atomic64_inc(&map->sleepable_refcnt);
 	memcpy(used_maps_new, used_maps_old,
 	       sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
kernel/bpf/verifier.c +15 -2
index 55d6cf2653755..ca27c14004ce3 100644
@@ -573,6 +573,19 @@ static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn
 	return false;
 }
 
+/* From here on the maps of the program count it as a sleepable user. */
+static void mark_sleepable_async_cb(struct bpf_verifier_env *env)
+{
+	int i;
+
+	if (bpf_prog_runs_sleepable(env->prog))
+		return;
+
+	env->prog->aux->sleepable_async_cb = true;
+	for (i = 0; i < env->used_map_cnt; i++)
+		atomic64_inc(&env->used_maps[i]->sleepable_refcnt);
+}
+
 static bool is_may_goto_insn(struct bpf_insn *insn)
 {
 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
@@ -10892,7 +10905,7 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 		if (IS_ERR(async_cb))
 			return PTR_ERR(async_cb);
 		if (is_async_cb_sleepable(env, insn))
-			env->prog->aux->sleepable_async_cb = true;
+			mark_sleepable_async_cb(env);
 		callee = async_cb->frame[0];
 		callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1;
 
@@ -21188,7 +21201,7 @@ static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
 	if (err)
 		return err;
 
-	if (env->prog->sleepable)
+	if (bpf_prog_runs_sleepable(env->prog))
 		atomic64_inc(&map->sleepable_refcnt);
 
 	/* hold the map. If the program is rejected by verifier,
Signature · 1 line
2.53.0
author maintainer
#605 lore raw

PATCH 604/990 bpf: Assume no bounds for buffers behind a tail call

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 7fa323d77688e8b62b2f0bf6c3208a2c96d4a5e7 ]

The bpf_map_elem, bpf_sk_storage_map and sockmap iterators hand the key and the value of an element to the program as buffers. The verifier notes how far a program reaches into them, and the iterator compares that with the map when the program is attached. A program that does not touch the buffers passes. It can tail-call another program of the same target, which gets the same context, and whose reach nobody compares with the map:

  BUG: KASAN: slab-out-of-bounds in ___bpf_prog_run+0xa46a/0xae80

The program array can be filled at any time, so there is nothing to look at when the link is made. For the same reason a program with a tail call is taken to use the whole stack and the whole packet. Take it to reach as far as can be into the buffers as well, so that these iterators refuse it with -EACCES.

Fixes d6c4503cc296 ("bpf: Implement bpf iterator for hash maps")
Fixes 5ce6e77c7edf ("bpf: Implement bpf iterator for sock local storage map")
Fixes 0365351524d7 ("net: Allow iterating sockmap and sockhash")
[ sashal: Moved the added max_rdonly_access = U32_MAX line into do_misc_fixups() in verifier.c, since this tree still has the fixups code there and not in a separate file. ]
---
 kernel/bpf/verifier.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/bpf/verifier.c +2 -0
index ca27c14004ce3..13da4dd120d74 100644
@@ -23176,6 +23176,8 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
 			if (!allow_tail_call_in_subprogs(env))
 				prog->aux->stack_depth = MAX_BPF_STACK;
 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
+			prog->aux->max_rdonly_access = U32_MAX;
+			prog->aux->max_rdwr_access = U32_MAX;
 
 			/* mark bpf_tail_call as different opcode to avoid
 			 * conditional branch in the interpreter for every normal
Signature · 1 line
2.53.0
author maintainer
#606 lore raw

PATCH 605/990 bpf: Assume no bounds for a writable tp with tail calls

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit cd0490e671d70326d70c7d36e82388939fd9b071 ]

A writable raw tracepoint hands a buffer to the program. The verifier notes how far the program reaches into it, and bpf_probe_register() refuses a program that reaches further than the tracepoint allows. A program that does not touch the buffer passes, and can tail-call one of its type that reads and writes behind it.

Take a BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE program with a tail call to reach as far as can be, as for the stack, the packet and the buffers of iterators. It cannot be attached any more. Plain raw tracepoint programs, for which the limit is zero, cannot get at the buffer, and a tail call stays within one type: they are left alone.

Fixes 9df1c28bb752 ("bpf: add writable context for raw tracepoints")

[ sashal: Moved the added max_tp_access = U32_MAX lines into do_misc_fixups() in verifier.c, since this tree still has the fixups code there and not in a separate file. ]

---
 kernel/bpf/verifier.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/bpf/verifier.c +2 -0
index 13da4dd120d74..dc7b4d0280f65 100644
@@ -23178,6 +23178,8 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
 			prog->aux->max_rdonly_access = U32_MAX;
 			prog->aux->max_rdwr_access = U32_MAX;
+			if (prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE)
+				prog->aux->max_tp_access = U32_MAX;
 
 			/* mark bpf_tail_call as different opcode to avoid
 			 * conditional branch in the interpreter for every normal
Signature · 1 line
2.53.0
author maintainer
#607 lore raw

PATCH 606/990 bpf: Free what map_free() unlinks for sleepable readers

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 5bdd61e98da5468140aff5b5abc0e8544deaf2ee ]

bpf_local_storage_map_free() takes the elements of the map off the lists of their owners, which are alive, and frees them, and the storage of an owner with its last element, behind a plain RCU grace period. Nobody uses the map any more, but the other maps of these owners are in use. A sleepable program calls the get and delete helpers under rcu_read_lock_trace() only. While it walks the list of an owner for its own map, or is about to lock the storage, the element it stands on, or the storage, can be freed under it.

Whatever else takes an element off the list of a live owner frees it behind an RCU Tasks Trace grace period, which implies a plain one. Do so in bpf_local_storage_map_free() as well. It waits for these callbacks before it frees the map.

This does not help a sleepable program that hands an owner to the helpers which nobody holds, and which may be gone by then.

Fixes dcf456c9a095 ("bpf: Fix usage of trace RCU in local storage.")
[ sashal: Replaced the upstream change in the missing bpf_selem_unlink_nofail() with flipping bpf_selem_unlink(selem, true) to false in bpf_local_storage_map_free(). ]
---
 kernel/bpf/bpf_local_storage.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/bpf/bpf_local_storage.c +1 -1
index b931fbceb54da..9fb26ae066f54 100644
@@ -890,7 +890,7 @@ void bpf_local_storage_map_free(struct bpf_map *map,
 				struct bpf_local_storage_elem, map_node))) {
 			if (busy_counter)
 				this_cpu_inc(*busy_counter);
-			bpf_selem_unlink(selem, true);
+			bpf_selem_unlink(selem, false);
 			if (busy_counter)
 				this_cpu_dec(*busy_counter);
 			cond_resched_rcu();
Signature · 1 line
2.53.0
author maintainer
#608 lore raw

PATCH 607/990 bpf: Let bpf_dynptr_write() mark a global function

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 589998616e0f9190ba6f6644a19532c5b2ba66d0 ]

The caller of a global function loses its packet pointers if the function may change packet data. That is found out by a scan for calls of the helpers which bpf_helper_changes_pkt_data() lists.

bpf_dynptr_write() is not on the list, because it depends on the type of the dynptr: check_helper_call() looks at it. The scan cannot do that, and so a global function which makes a dynptr from the skb, or gets one as an argument, and writes through it counts as harmless. The write can reallocate the head of the skb, and the caller goes on with pointers into the old one, which has been freed.

Let every call of bpf_dynptr_write() mark the function, as a tail call does. The same mark decides whether a program may replace a function.

Fixes 51081a3f25c7 ("bpf: track changes_pkt_data property for global functions")
[ sashal: Applied the same change in kernel/bpf/verifier.c instead of kernel/bpf/cfg.c, which doesn't exist here, with one differing context line (struct bpf_kfunc_call_arg_meta meta;). ]
---
 kernel/bpf/verifier.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/bpf/verifier.c +3 -1
index dc7b4d0280f65..1890c0ba642ab 100644
@@ -18471,7 +18471,9 @@ static int visit_insn(int t, struct bpf_verifier_env *env)
 			 */
 			if (ret == 0 && fp->might_sleep)
 				mark_subprog_might_sleep(env, t);
-			if (bpf_helper_changes_pkt_data(insn->imm))
+			/* nobody knows yet whether the dynptr is that of an skb */
+			if (bpf_helper_changes_pkt_data(insn->imm) ||
+			    insn->imm == BPF_FUNC_dynptr_write)
 				mark_subprog_changes_pkt_data(env, t);
 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
 			struct bpf_kfunc_call_arg_meta meta;
Signature · 1 line
2.53.0
author maintainer
#609 lore raw

PATCH 608/990 bpf: Dont take a dynptr argument for a local dynptr

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit b7f97db88948aa511bcd989978f181e1367e0e8b ]

A global function is verified on its own. A dynptr which it gets as an argument is assumed to be of type BPF_DYNPTR_TYPE_LOCAL, but the callers may pass one of any type, that of an skb for example.

The type decides whether a write through the dynptr invalidates packet pointers, and whether a slice of it is invalidated together with them. Inside of the function neither happens. It can take a packet pointer from its context argument, or a slice from the dynptr, write through the dynptr and go on using the pointer, although the write may have reallocated the head of the skb.

Assume the type of an skb dynptr instead. Nothing becomes forbidden for the dynptr itself, and a clone inherits the caution. The dynptr which the callback of bpf_user_ringbuf_drain() gets is known to be local, and stays so.

Fixes a64bfe618665 ("bpf: add support for passing dynptr pointer to global subprog")
[ sashal: Kept this branch's ARG_PTR_TO_DYNPTR | MEM_RDONLY condition and dropped the extra 0 argument to the four-argument __mark_dynptr_reg(), changing the type to BPF_DYNPTR_TYPE_SKB. ]
---
 kernel/bpf/verifier.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
kernel/bpf/verifier.c +6 -2
index 1890c0ba642ab..0d93bcdcef81a 100644
@@ -24006,8 +24006,12 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog)
 				reg->type = SCALAR_VALUE;
 				mark_reg_unknown(env, regs, i);
 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
-				/* assume unspecial LOCAL dynptr type */
-				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
+				/*
+				 * The callers may hand in a dynptr of any type.
+				 * Take it for that of an skb, so that a write
+				 * through it and its slices are treated with care.
+				 */
+				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_SKB, true, ++env->id_gen);
 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
 				reg->type = PTR_TO_MEM;
 				reg->type |= arg->arg_type &
Signature · 1 line
2.53.0
author maintainer
#610 lore raw

PATCH 609/990 locking/atomic: arc, hexagon, openrisc: Define arch_cmpxchg_local()

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit 8cebaa3be829c88a59957900f8de98fed09daefe ]

Commit ccb88db8dac8 ("bpf: Don't hand out a linked element as extra element") made alloc_htab_elem() take the per-cpu spare element with try_cmpxchg_local(), the first caller of cmpxchg_local() outside of architecture code. It doesn't build on arc, hexagon and openrisc:

include/linux/atomic/atomic-arch-fallback.h:384:27: error: implicit declaration of function 'arch_cmpxchg_local'; did you mean 'raw_cmpxchg_local'? [-Werror=implicit-function-declaration]

raw_cmpxchg_local() maps to arch_cmpxchg_local() unconditionally, but these three architectures don't define it, and unlike nios2 and microblaze they don't get it from asm-generic/cmpxchg.h either.

cmpxchg_local() only has to be atomic with respect to the local CPU, so an architecture's own arch_cmpxchg() can serve for the sizes it supports. arc uses its relaxed LLOCK/SCOND variant when ARC_HAS_LLSC is set and its atomic_ops_lock() variant otherwise, and openrisc uses its LL/SC arch_cmpxchg(), the way arm64, riscv and s390 alias theirs. The hexagon arch_cmpxchg() only handles 32-bit words, so hexagon uses the generic version that disables interrupts, like sh, sparc32 and xtensa do. Linux has no NMIs on hexagon, so that is sufficient there.

---
 arch/arc/include/asm/cmpxchg.h      | 4 ++++
 arch/hexagon/include/asm/cmpxchg.h  | 6 ++++++
 arch/openrisc/include/asm/cmpxchg.h | 2 ++
 3 files changed, 12 insertions(+)
arch/arc/include/asm/cmpxchg.h +4 -0
index 66b3743c94008..93f7153eb267a 100644
@@ -59,6 +59,8 @@
 	_prev_;								\
 })
 
+#define arch_cmpxchg_local	arch_cmpxchg_relaxed
+
 #else
 
 #define arch_cmpxchg(ptr, old, new)				        \
@@ -80,6 +82,8 @@
 	_prev_;								\
 })
 
+#define arch_cmpxchg_local	arch_cmpxchg
+
 #endif
 
 /*
arch/hexagon/include/asm/cmpxchg.h +6 -0
index 9c58fb81f7fd6..e6114e713db9f 100644
@@ -8,6 +8,8 @@
 #ifndef _ASM_CMPXCHG_H
 #define _ASM_CMPXCHG_H
 
+#include <asm-generic/cmpxchg-local.h>
+
 /*
  * __arch_xchg - atomically exchange a register and a memory location
  * @x: value to swap
@@ -72,4 +74,8 @@ __arch_xchg(unsigned long x, volatile void *ptr, int size)
 	__oldval;						\
 })
 
+#define arch_cmpxchg_local(ptr, o, n)					\
+	((__typeof__(*(ptr)))__generic_cmpxchg_local((ptr),		\
+			(unsigned long)(o), (unsigned long)(n), sizeof(*(ptr))))
+
 #endif /* _ASM_CMPXCHG_H */
arch/openrisc/include/asm/cmpxchg.h +2 -0
index 8ee151c072e41..fcf1bc8db8fe9 100644
@@ -140,6 +140,8 @@ static inline unsigned long __cmpxchg(volatile void *ptr, unsigned long old,
 					       sizeof(*(ptr)));		\
 	})
 
+#define arch_cmpxchg_local	arch_cmpxchg
+
 /*
  * This function doesn't exist, so you'll get a linker error if
  * something tries to do an invalidly-sized xchg().
Signature · 1 line
2.53.0
author maintainer
#611 lore raw

PATCH 610/990 bpf: Zero-extend the index in inlined bpf_get_func_arg()

In reply to Greg Kroah-Hartman

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

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

From: Woojin Ji <[email protected]>

[ Upstream commit 1c1dda9ba9f3af9cd511a197dcc86de2465d8fe5 ]

bpf_get_func_arg() takes a u32 index, but the inlined expansion compared only the low 32 bits of R2 with the argument count and then shifted the full 64-bit register to compute the context address. R2 is ARG_ANYTHING, so nothing guarantees that its upper bits are zero: an index of 1ULL << 32 passes the bounds check as index zero while the load is performed at ctx + (1ULL << 35).

Shift the index as a 32-bit value. When the 32-bit bounds check passes, the low 32 bits of R2 are below R0, and R0 is at most 255: the trampoline arm masks the argument count with 0xFF and the raw_tp arm uses the BTF argument count minus one, which the verifier caps at MAX_BPF_FUNC_ARGS. The 3-bit shift therefore cannot overflow and it clears the upper bits of the register. Widening the comparison instead would reject indices whose low 32 bits are valid. The check itself is unchanged, so this cannot change which programs are accepted, only the address that is computed.

Fixes f92c1e183604 ("bpf: Add get_func_[arg|ret|arg_cnt] helpers")
[ sashal: Replaced a 64-bit shift with a 32-bit one in the inlined bpf_get_func_arg() code in verifier.c, since the fixups code isn't split into its own file here. ]
---
 kernel/bpf/verifier.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/bpf/verifier.c +1 -1
index 0d93bcdcef81a..a004c95969636 100644
@@ -23475,7 +23475,7 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
 			/* Load nr_args from ctx - 8 */
 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
-			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
+			insn_buf[2] = BPF_ALU32_IMM(BPF_LSH, BPF_REG_2, 3);
 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
Signature · 1 line
2.53.0
author maintainer
#612 lore raw

PATCH 611/990 netfilter: flowtable: reset transport header after nf_flow_encap_pop()

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit 08f7882637f2db5b98f521498eeaf94770383a6e ]

nf_flow_encap_pop() pulls vlan/pppoe or ip tunnel headers and resets the network header, but leaves the transport header pointing into the removed outer header. Reset the transport header to the inner L4 header, otherwise later consumers (e.g. GSO segmentation) parse a bogus header.

Fixes 4cd91f7c290f ("netfilter: flowtable: add vlan support")
[ sashal: adjusted nf_flow_encap_pop() call context to the older two-argument form (skb, tuplehash) in the IPv6 hunk, since this tree's helper lacks the ctx parameter. ]
---
 net/netfilter/nf_flow_table_ip.c | 2 ++
 1 file changed, 2 insertions(+)
net/netfilter/nf_flow_table_ip.c +2 -0
index 041d928b0bee0..aa22d8fd39fc1 100644
@@ -410,6 +410,7 @@ static int nf_flow_offload_forward(struct nf_flowtable_ctx *ctx,
 
 	nf_flow_encap_pop(skb, tuplehash);
 	thoff -= ctx->offset;
+	skb_set_transport_header(skb, thoff);
 
 	iph = ip_hdr(skb);
 	nf_flow_nat_ip(flow, skb, thoff, dir, iph);
@@ -698,6 +699,7 @@ static int nf_flow_offload_ipv6_forward(struct nf_flowtable_ctx *ctx,
 	flow_offload_refresh(flow_table, flow, false);
 
 	nf_flow_encap_pop(skb, tuplehash);
+	skb_set_transport_header(skb, sizeof(*ip6h));
 
 	ip6h = ipv6_hdr(skb);
 	nf_flow_nat_ipv6(flow, skb, dir, ip6h);
Signature · 1 line
2.53.0
author maintainer
#613 lore raw

PATCH 612/990 cgroup/cpuset: Fix a missing isolated_cpus update in update_cpumasks_hier()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 46b885416c27214072272b85adb898ed91801062 ]

It is found that when a local isolated partition is being invalidated because its parent partition is no longer valid, the isolated_cpus cpumask may not be properly updated. Those isolated CPUs may or may not needed to be removed from isolated_cpus depending on if there is a local isolated partition ancestor that will now own those isolated CPUs instead.

Fix that by calling a new ancestor_partition() helper to return the closeset valid partition root ancestor. If that ancestor is PRS_ROOT, the isolated CPUs will have to be removed from isolated_cpus. For a PRS_ISOLATED ancestor, the isolated CPUs are checked against the ancestor's ones to see if any of them should be removed as it is possible that the invalidation of the parent may be caused by change in the effective xcpus of that ancestor. If any of the isolated CPUs should be removed, isolated_cpus_update() will be called under callback_lock.

An existing test case in test_cpuset_prs.sh is modifed and a new one added to test that.

Fixes 11e5f407b64a ("cgroup/cpuset: Keep track of CPUs in isolated partitions")
[ sashal: Selftest TEST_MATRIX rows were adapted to the older format with explicit ":S+" markers on non-leaf cpusets, while the cpuset.c changes match upstream. ]
---
 kernel/cgroup/cpuset.c                        | 57 +++++++++++++++++--
 .../selftests/cgroup/test_cpuset_prs.sh       |  6 +-
 2 files changed, 55 insertions(+), 8 deletions(-)
kernel/cgroup/cpuset.c +52 -5
index e90fb48cf0f9b..3ef103c4b68d3 100644
@@ -2232,6 +2232,25 @@ static void compute_partition_effective_cpumask(struct cpuset *cs,
 	rcu_read_unlock();
 }
 
+/*
+ * ancestor_partition - Find and return the closest valid partition root ancestor
+ * @cs: the current cpuset
+ *
+ * Return: The closet partition root ancestor cpuset
+ */
+static struct cpuset *ancestor_partition(struct cpuset *cs)
+{
+	struct cpuset *ancestor = parent_cs(cs);
+
+	/*
+	 * The top_cpuset is always a valid partition root which will stop
+	 * the loop if it is reached.
+	 */
+	while (!is_partition_valid(ancestor))
+		ancestor = parent_cs(ancestor);
+	return ancestor;
+}
+
 /*
  * update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
  * @cs:  the cpuset to consider
@@ -2334,7 +2353,10 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 		 * cpuset if the parent's effective_cpus changes.
 		 */
 		if ((cp != cs) && old_prs) {
-			switch (parent->partition_root_state) {
+			int parent_prs = parent->partition_root_state;
+			struct cpumask *del_cpus = NULL;
+
+			switch (parent_prs) {
 			case PRS_ROOT:
 			case PRS_ISOLATED:
 				update_parent = true;
@@ -2342,12 +2364,37 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 
 			default:
 				/*
-				 * When parent is not a partition root or is
-				 * invalid, child partition roots become
-				 * invalid too.
+				 * When parent is not a valid partition root,
+				 * child partition roots become invalid too.
+				 *
+				 * For a to be invalidated isolated partition,
+				 * its isolated CPUs may or may not need to be
+				 * removed from isolated_cpus depending on if
+				 * its closest partition root ancestor is a root
+				 * or isolated partition. With a PRS_ISOLATED
+				 * ancestor, the CPUs are checked against its
+				 * effective xcpus to see if any of them needed
+				 * to be removed.
 				 */
 				if (is_partition_valid(cp))
-					new_prs = -cp->partition_root_state;
+					new_prs = -old_prs;
+
+				if (old_prs == PRS_ISOLATED) {
+					struct cpuset *ancestor = ancestor_partition(cp);
+
+					if (ancestor->partition_root_state == PRS_ROOT)
+						del_cpus = cp->effective_xcpus;
+					else if (cpumask_andnot(tmp->delmask,
+								cp->effective_xcpus,
+								ancestor->effective_xcpus))
+						del_cpus = tmp->delmask;
+
+					if (del_cpus) {
+						spin_lock_irq(&callback_lock);
+						isolated_cpus_update(old_prs, new_prs, del_cpus);
+						spin_unlock_irq(&callback_lock);
+					}
+				}
 				WRITE_ONCE(cp->prs_err,
 					   is_partition_invalid(parent)
 					   ? PERR_INVPARENT : PERR_NOTPART);
tools/testing/selftests/cgroup/test_cpuset_prs.sh +3 -3
index 6f7e387f68e5b..ffa030cf1984d 100755
@@ -291,9 +291,9 @@ TEST_MATRIX=(
 								       A1:P0|A2:P2|A3:P1 2-4|2-3"
 	" C0-4:S+ C1-4:S+ C2-4     .    X2-4  X2-4:P2 X3-4:P1   .    0 A1:0-1|A2:2|A3:3-4 \
 								       A1:P0|A2:P2|A3:P1 2"
-	" C0-4:X2-4:S+ C1-4:X2-4:S+:P2 C2-4:X4:P1 \
-				   .      .      X5      .      .    0 A1:0-4|A2:1-4|A3:2-4 \
-								       A1:P0|A2:P-2|A3:P-1 ."
+	" C1-4:X2-4:S+ C2-4:X3-4:S+:P1 C3-4:X4:P2 \
+				   .      .      X5      .      .    0 A1:1-4|A2:2-4|A3:3-4 \
+								       A1:P0|A2:P-1|A3:P-2 ."
 	" C0-4:X2-4:S+ C1-4:X2-4:S+:P2 C2-4:X4:P1 \
 				   .      .      .      X1      .    0 A1:0-1|A2:2-4|A3:2-4 \
 								       A1:P0|A2:P2|A3:P-1 2-4"
Signature · 1 line
2.53.0
author maintainer
#614 lore raw

PATCH 613/990 cgroup/cpuset: Consolidate isolated_cpus_can_update() into prstate_housekeeping_conflict()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 53bbfb33b1f4fd669c5bffcb7670c4099ecbb225 ]

The isolated_cpus_can_update() and prstate_housekeeping_conflict() are checking different aspects of upcoming cpumask changes that may conflict with the current setting of the housekeeping cpumasks. There are places where both are called together. There are also places where only one of them is called. That inconsistency can contribute to missing check where invalid cpumask changes may be allowed to move forward.

Fix that by consolidating isolated_cpus_can_update() into prstate_housekeeping_conflict() and call prstate_housekeeping_conflict() in all the places where either one of them or both are called. The exception is the validate_partition() function where the prstate_housekeeping_conflict() call is removed. It is because validate_partition() is called only from partition_cpus_change() where prstate_housekeeping_conflict() will be called from either remote_cpus_update() or update_parent_effective_cpumask() with partcmd_update if not for partition invalidatation or disablement.

Now prstate_housekeeping_conflict() will be called in the following locations:
- when a partition is enabled in remote_partition_enable() or in update_parent_effective_cpumask() with partcmd_enable*.
- when a cpumask is updated in remote_cpus_update() or in update_parent_effective_cpumask() with partcmd_update.
- when a partition state changes from root to isolated or vice versa in update_prstate().

Fixes 4a74e418881f ("cgroup/cpuset: Check partition conflict with housekeeping setup")
Fixes 103b08709e8a ("cgroup/cpuset: Fail if isolated and nohz_full don't leave any housekeeping")
[ sashal: Replaced this tree's boot-isolcpus variables (have_boot_isolcpus, boot_hk_cpus) for the missing HK_TYPE_DOMAIN_BOOT housekeeping checks, with context adjusted for earlier backports. ]
---
 kernel/cgroup/cpuset.c | 147 +++++++++++++++++++++--------------------
 1 file changed, 77 insertions(+), 70 deletions(-)
kernel/cgroup/cpuset.c +77 -70
index 3ef103c4b68d3..4bda4c6b754f4 100644
@@ -1428,64 +1428,87 @@ static bool partition_xcpus_del(int old_prs, struct cpuset *parent,
 }
 
 /*
- * isolated_cpus_can_update - check for isolated & nohz_full conflicts
- * @add_cpus: cpu mask for cpus that are going to be isolated
- * @del_cpus: cpu mask for cpus that are no longer isolated, can be NULL
- * Return: false if there is conflict, true otherwise
- *
- * If nohz_full is enabled and we have isolated CPUs, their combination must
- * still leave housekeeping CPUs.
+ * prstate_housekeeping_conflict - check for partition & housekeeping conflicts
+ * @new_prs: new partition root state to be checked
+ * @parent_prs: Parent partition root state
+ * @add_cpus: additional CPUs to be added to current cpuset
+ * @del_cpus: CPUs to be removed from current cpuset, can be NULL
+ * Return: true if there is conflict, false otherwise
  *
- * TBD: Should consider merging this function into
- *      prstate_housekeeping_conflict().
+ * There are two different housekeeping conflicts to be checked:
+ * 1) If new_prs is PRS_ROOT, none of the @add_cpus can be a boot-time isolated
+ *    CPU. IOW, the whole @add_cpus must be a subset of boot_hk_cpus.
+ * 2) If nohz_full is enabled and we have isolated CPUs, their combination must
+ *    still leave housekeeping CPUs. This check is only needed if new_prs
+ *    differs from parent_prs and one of them is PRS_ISOLATED.
  */
-static bool isolated_cpus_can_update(struct cpumask *add_cpus,
-				     struct cpumask *del_cpus)
+static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
+					  struct cpumask *add_cpus,
+					  struct cpumask *del_cpus)
 {
 	cpumask_var_t full_hk_cpus;
-	int res = true;
+	int res;
 
-	if (!housekeeping_enabled(HK_TYPE_KERNEL_NOISE))
-		return true;
+	WARN_ON_ONCE(parent_prs <= 0);
+	if (!new_prs)
+		return false;
 
-	if (del_cpus && cpumask_weight_and(del_cpus,
-			housekeeping_cpumask(HK_TYPE_KERNEL_NOISE)))
+	/*
+	 * For a currently invalid partition root state, do the check assuming
+	 * that it may be converted back to valid.
+	 *
+	 * There are code paths where an invalid partition may be reverted back
+	 * to a valid partition but we still need to run the housekeeping check
+	 * before the conversion happens to make sure the switch is valid. We
+	 * can either do the negative to positive PRS switch individually in all
+	 * these code paths or do it here which I think will make the code a bit
+	 * easier to read.
+	 */
+	if (new_prs < 0)
+		new_prs = -new_prs;
+
+	if (have_boot_isolcpus && (new_prs == PRS_ROOT) &&
+	    !cpumask_subset(add_cpus, boot_hk_cpus))
 		return true;
 
-	if (!alloc_cpumask_var(&full_hk_cpus, GFP_KERNEL))
+	/*
+	 * Exit 2nd check early and return false if
+	 * 1) there is no boot time isolated nohz_full CPU
+	 * 2) parent and child has the same partition state
+	 * 3) new_prs is PRS_ROOT, parent_prs is PRS_ISOLATED and no CPU will
+	 *    be returned back to the parent.
+	 */
+	if (!housekeeping_enabled(HK_TYPE_KERNEL_NOISE) ||
+	    (new_prs == parent_prs) ||
+	    ((new_prs == PRS_ROOT) && (!del_cpus || cpumask_empty(del_cpus))))
+		return false;
+
+	/*
+	 * Now make sure that @add_cpus contains new CPUs to be isolated and
+	 * @del_cpus contains isolated CPUs to be un-isolated.
+	 * With the guards above, @add_cpus can't be NULL after the swap.
+	 */
+	if (parent_prs == PRS_ISOLATED)
+		swap(add_cpus, del_cpus);
+
+	if (del_cpus &&
+	   (cpumask_first_and_and(del_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
+				   cpu_active_mask) < nr_cpu_ids))
 		return false;
 
+	if (!alloc_cpumask_var(&full_hk_cpus, GFP_KERNEL))
+		return true;
+
 	cpumask_and(full_hk_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
 		    housekeeping_cpumask(HK_TYPE_DOMAIN));
 	cpumask_andnot(full_hk_cpus, full_hk_cpus, isolated_cpus);
 	cpumask_and(full_hk_cpus, full_hk_cpus, cpu_active_mask);
-	if (!cpumask_weight_andnot(full_hk_cpus, add_cpus))
-		res = false;
+	res = !cpumask_weight_andnot(full_hk_cpus, add_cpus);
 
 	free_cpumask_var(full_hk_cpus);
 	return res;
 }
 
-/*
- * prstate_housekeeping_conflict - check for partition & housekeeping conflicts
- * @prstate: partition root state to be checked
- * @new_cpus: cpu mask
- * Return: true if there is conflict, false otherwise
- *
- * CPUs outside of boot_hk_cpus, if defined, can only be used in an
- * isolated partition.
- */
-static bool prstate_housekeeping_conflict(int prstate, struct cpumask *new_cpus)
-{
-	if (!have_boot_isolcpus)
-		return false;
-
-	if ((prstate != PRS_ISOLATED) && !cpumask_subset(new_cpus, boot_hk_cpus))
-		return true;
-
-	return false;
-}
-
 static void update_isolation_cpumasks(bool isolcpus_updated)
 {
 	int ret;
@@ -1645,9 +1668,7 @@ static int remote_partition_enable(struct cpuset *cs, int new_prs,
 		return PERR_INVCPUS;
 	if (cpumask_intersects(tmp->new_cpus, subpartitions_cpus))
 		return PERR_NOCPUS;
-	if (((new_prs == PRS_ISOLATED) &&
-	     !isolated_cpus_can_update(tmp->new_cpus, NULL)) ||
-	    prstate_housekeeping_conflict(new_prs, tmp->new_cpus))
+	if (prstate_housekeeping_conflict(new_prs, PRS_ROOT, tmp->new_cpus, NULL))
 		return PERR_HKEEPING;
 
 	spin_lock_irq(&callback_lock);
@@ -1755,8 +1776,8 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 		else if (cpumask_intersects(tmp->addmask, subpartitions_cpus) ||
 			 cpumask_subset(top_cpuset.effective_cpus, tmp->addmask))
 			WRITE_ONCE(cs->prs_err, PERR_NOCPUS);
-		else if ((prs == PRS_ISOLATED) &&
-			 !isolated_cpus_can_update(tmp->addmask, tmp->delmask))
+		else if (prstate_housekeeping_conflict(prs, PRS_ROOT,
+						       tmp->addmask, tmp->delmask))
 			WRITE_ONCE(cs->prs_err, PERR_HKEEPING);
 		if (cs->prs_err)
 			goto invalidate;
@@ -1901,11 +1922,7 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		if (cpumask_empty(xcpus))
 			return PERR_INVCPUS;
 
-		if (prstate_housekeeping_conflict(new_prs, xcpus))
-			return PERR_HKEEPING;
-
-		if ((new_prs == PRS_ISOLATED) && (new_prs != parent_prs) &&
-		    !isolated_cpus_can_update(xcpus, NULL))
+		if (prstate_housekeeping_conflict(new_prs, parent_prs, xcpus, NULL))
 			return PERR_HKEEPING;
 
 		if (tasks_nocpu_error(parent, cs, xcpus))
@@ -1980,20 +1997,12 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		}
 
 		/*
-		 * TBD: Invalidate a currently valid child root partition may
-		 * still break isolated_cpus_can_update() rule if parent is an
-		 * isolated partition.
+		 * Check for housekeeping conflicts
 		 */
-		if (is_partition_valid(cs) && (old_prs != parent_prs)) {
-			if ((parent_prs == PRS_ROOT) &&
-			    /* Adding to parent means removing isolated CPUs */
-			    !isolated_cpus_can_update(tmp->delmask, tmp->addmask))
-				part_error = PERR_HKEEPING;
-			if ((parent_prs == PRS_ISOLATED) &&
-			    /* Adding to parent means adding isolated CPUs */
-			    !isolated_cpus_can_update(tmp->addmask, tmp->delmask))
-				part_error = PERR_HKEEPING;
-		}
+		if (is_partition_valid(cs) &&
+		    prstate_housekeeping_conflict(old_prs, parent_prs,
+						  tmp->delmask, tmp->addmask))
+			part_error = PERR_HKEEPING;
 
 		/*
 		 * The new CPUs to be removed from parent's effective CPUs
@@ -2559,10 +2568,6 @@ static enum prs_errcode validate_partition(struct cpuset *cs, struct cpuset *tri
 	if (cpumask_empty(trialcs->effective_xcpus))
 		return PERR_INVCPUS;
 
-	if (prstate_housekeeping_conflict(trialcs->partition_root_state,
-					  trialcs->effective_xcpus))
-		return PERR_HKEEPING;
-
 	if (tasks_nocpu_error(parent, cs, trialcs->effective_xcpus))
 		return PERR_NOCPUS;
 
@@ -2616,7 +2621,7 @@ static int cpus_allowed_validate_change(struct cpuset *cs, struct cpuset *trialc
  * CPU modifications may cause a partition to be disabled or require state updates.
  */
 static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs,
-					struct tmpmasks *tmp)
+				  struct tmpmasks *tmp)
 {
 	enum prs_errcode prs_err;
 
@@ -3173,13 +3178,15 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 			err = remote_partition_enable(cs, new_prs, &tmpmask);
 		}
 	} else if (old_prs && new_prs) {
+		int parent_prs = is_remote_partition(cs)
+				 ? PRS_ROOT : parent->partition_root_state;
+
 		/*
 		 * A change in load balance state only, no change in cpumasks.
 		 * Need to update isolated_cpus.
 		 */
-		if (((new_prs == PRS_ISOLATED) &&
-		     !isolated_cpus_can_update(cs->effective_xcpus, NULL)) ||
-		    prstate_housekeeping_conflict(new_prs, cs->effective_xcpus))
+		if (prstate_housekeeping_conflict(new_prs, parent_prs,
+						  cs->effective_xcpus, NULL))
 			err = PERR_HKEEPING;
 		else
 			isolcpus_updated = true;
Signature · 1 line
2.53.0
author maintainer
#615 lore raw

PATCH 614/990 cgroup/cpuset: Consider all the exclusive CPUs when doing housekeeping check

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 9527ff78a413e2b4089e78953926af77b98fd43f ]

When prstate_housekeeping_conflict() is called to perform housekeeping check with cpumask changes, the cpumask changes are passed in via add_cpus and del_cpus parameters. With this arrangement, the exclusive CPUs owned by the child partitions and not affected by the cpumask change, if any, are excluded in the analysis. The only places where there are separate add and delete masks are when the cpuset.cpus or cpuset.cpus.exclusive is being changed. In both cases, partition_cpus_change() is a good place to perform the housekeeping check.

If we allow a root partition to be created under an isolated partition, it is possible the cpumask change will still leave active housekeeping CPUs but then no housekeeping CPUs will be left when the child partitions are disabled or invalidated.

As a first step to protect against this possibility, all the exclusive CPUs of the cpuset should be considered to be owned by the current cpuset when doing housekeeping check. At the same time, we do want to know if some housekeeping CPUs are going to be removed from the isolated partition that there will be no danger of losing all the active housekeeping CPUs. So the current add_cpus paremeter is renamed as new_cpus to indicate that it includes the complete set of effective xcpus.

With the new check in partition_cpus_change(), the housekeeping check in update_parent_effective_cpumask() with partcmd_update and newmask is now duplicative and can be removed. The housekeeping check in remote_cpus_update(), however, will still be useful as this function can be called directly from update_cpumasks_hier() without going through partition_cpus_change(). The update_parent_effective_cpumask() call from update_cpumasks_hier() is partcmd_update with no cpumask which still have the housekeeping check and so is covered.

Fixes 103b08709e8a ("cgroup/cpuset: Fail if isolated and nohz_full don't leave any housekeeping")
[ sashal: Replaced the upstream HK_TYPE_DOMAIN_BOOT housekeeping checks with this tree's have_boot_isolcpus and boot_hk_cpus, keeping the add_cpus to new_cpus rename. ]
---
 kernel/cgroup/cpuset.c | 46 +++++++++++++++++++++++++-----------------
 1 file changed, 27 insertions(+), 19 deletions(-)
kernel/cgroup/cpuset.c +27 -19
index 4bda4c6b754f4..ee5ee72b8590d 100644
@@ -1431,19 +1431,19 @@ static bool partition_xcpus_del(int old_prs, struct cpuset *parent,
  * prstate_housekeeping_conflict - check for partition & housekeeping conflicts
  * @new_prs: new partition root state to be checked
  * @parent_prs: Parent partition root state
- * @add_cpus: additional CPUs to be added to current cpuset
- * @del_cpus: CPUs to be removed from current cpuset, can be NULL
+ * @new_cpus: the set of new effective xcpus in the current cpuset
+ * @del_cpus: old CPUs going to be removed from current cpuset, can be NULL
  * Return: true if there is conflict, false otherwise
  *
  * There are two different housekeeping conflicts to be checked:
- * 1) If new_prs is PRS_ROOT, none of the @add_cpus can be a boot-time isolated
- *    CPU. IOW, the whole @add_cpus must be a subset of boot_hk_cpus.
+ * 1) If new_prs is PRS_ROOT, none of the @new_cpus can be a boot-time isolated
+ *    CPU. IOW, the whole @new_cpus must be a subset of boot_hk_cpus.
  * 2) If nohz_full is enabled and we have isolated CPUs, their combination must
  *    still leave housekeeping CPUs. This check is only needed if new_prs
  *    differs from parent_prs and one of them is PRS_ISOLATED.
  */
 static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
-					  struct cpumask *add_cpus,
+					  struct cpumask *new_cpus,
 					  struct cpumask *del_cpus)
 {
 	cpumask_var_t full_hk_cpus;
@@ -1468,7 +1468,7 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 		new_prs = -new_prs;
 
 	if (have_boot_isolcpus && (new_prs == PRS_ROOT) &&
-	    !cpumask_subset(add_cpus, boot_hk_cpus))
+	    !cpumask_subset(new_cpus, boot_hk_cpus))
 		return true;
 
 	/*
@@ -1484,12 +1484,12 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 		return false;
 
 	/*
-	 * Now make sure that @add_cpus contains new CPUs to be isolated and
+	 * Now make sure that @new_cpus contains new CPUs to be isolated and
 	 * @del_cpus contains isolated CPUs to be un-isolated.
-	 * With the guards above, @add_cpus can't be NULL after the swap.
+	 * With the guards above, @new_cpus can't be NULL after the swap.
 	 */
 	if (parent_prs == PRS_ISOLATED)
-		swap(add_cpus, del_cpus);
+		swap(new_cpus, del_cpus);
 
 	if (del_cpus &&
 	   (cpumask_first_and_and(del_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
@@ -1503,7 +1503,7 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 		    housekeeping_cpumask(HK_TYPE_DOMAIN));
 	cpumask_andnot(full_hk_cpus, full_hk_cpus, isolated_cpus);
 	cpumask_and(full_hk_cpus, full_hk_cpus, cpu_active_mask);
-	res = !cpumask_weight_andnot(full_hk_cpus, add_cpus);
+	res = !cpumask_weight_andnot(full_hk_cpus, new_cpus);
 
 	free_cpumask_var(full_hk_cpus);
 	return res;
@@ -1777,7 +1777,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 			 cpumask_subset(top_cpuset.effective_cpus, tmp->addmask))
 			WRITE_ONCE(cs->prs_err, PERR_NOCPUS);
 		else if (prstate_housekeeping_conflict(prs, PRS_ROOT,
-						       tmp->addmask, tmp->delmask))
+						       excpus, tmp->delmask))
 			WRITE_ONCE(cs->prs_err, PERR_HKEEPING);
 		if (cs->prs_err)
 			goto invalidate;
@@ -1996,14 +1996,6 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 					       parent->effective_xcpus);
 		}
 
-		/*
-		 * Check for housekeeping conflicts
-		 */
-		if (is_partition_valid(cs) &&
-		    prstate_housekeeping_conflict(old_prs, parent_prs,
-						  tmp->delmask, tmp->addmask))
-			part_error = PERR_HKEEPING;
-
 		/*
 		 * The new CPUs to be removed from parent's effective CPUs
 		 * must be present.
@@ -2629,6 +2621,22 @@ static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs,
 		return;
 
 	prs_err = validate_partition(cs, trialcs);
+	if (!prs_err && !cpumask_empty(trialcs->effective_xcpus)) {
+		int prs = cs->partition_root_state;
+		int parent_prs = is_remote_partition(cs)
+			       ? PRS_ROOT : parent_cs(cs)->partition_root_state;
+		/*
+		 * Check for housekeeping conflict by passing the whole
+		 * effective_xcpus as well as those CPUs that are to be
+		 * removed from cs as delmask.
+		 */
+		cpumask_andnot(tmp->delmask, cs->effective_xcpus, trialcs->effective_xcpus);
+		if (parent_prs > 0 &&
+		    prstate_housekeeping_conflict(prs, parent_prs,
+						  trialcs->effective_xcpus, tmp->delmask))
+			prs_err = PERR_HKEEPING;
+	}
+
 	if (prs_err) {
 		WRITE_ONCE(cs->prs_err, prs_err);
 		trialcs->prs_err = prs_err;
Signature · 1 line
2.53.0
author maintainer
#616 lore raw

PATCH 615/990 cgroup/cpuset: Do housekeeping check before converting invalid partition to valid

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 2c0a5742fc459cd8416607acff4a38a1abcb2e1b ]

When a hotplug event happens or when update_cpumasks_hier() is called, an invalid partition may be converted back to valid. However check against housekeeping conflict isn't being done which can lead to a partition state that violates the housekeeping rules. Update the code to allow reviving an invalid partition only if it can pass the housekeeping check.

Fixes 4a74e418881f ("cgroup/cpuset: Check partition conflict with housekeeping setup")
---
 kernel/cgroup/cpuset.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
kernel/cgroup/cpuset.c +8 -2
index ee5ee72b8590d..4a38da24c3612 100644
@@ -2044,9 +2044,15 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 			bool exclusive = true;
 
 			/*
-			 * Convert invalid partition to valid has to
-			 * pass the cpu exclusivity test.
+			 * Convert invalid partition to valid has to pass the
+			 * cpu exclusivity test as well as the housekeeping
+			 * check.
 			 */
+			if (prstate_housekeeping_conflict(cs->partition_root_state,
+							  parent_prs, xcpus, NULL)) {
+				part_error = PERR_HKEEPING;
+				goto write_error;
+			}
 			rcu_read_lock();
 			cpuset_for_each_child(child, css, parent) {
 				if (child == cs)
Signature · 1 line
2.53.0
author maintainer
#617 lore raw

PATCH 616/990 cgroup/cpuset: Properly disabling partition when partition state switching fails

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit db27a748a399e24af715c54c12a7e928e32d15b0 ]

Before commit 103b08709e8a ("cgroup/cpuset: Fail if isolated and nohz_full don't leave any housekeeping"), the partition state can be freely switched from "root" to "isolated" and vice versa. After that commit, the switch from "root" to "isolated" can fail if it exhausts all the housekeeping CPUs. Later on, the switch from "isolated" to "root" can also fail if some of the partition CPUs are boot-time isolated by "isolcpus".

A local or remote partition is made invalid when the switch fails. However there are 2 problems with the existing invalidation code.

1) Both the subpartitions_cpus and isolated_cpus are not properly updated.
2) In the case of remote partition with remote_partition flag set, it is not cleared.

Fix this by calling the proper partition disabling function in this case.

On an x86 test system with boot option "isolcpus=10 cgroup_debug" set and more than 16 cores, the following commands were executed after boot.

  # cd /sys/fs/cgroup
  # echo +cpuset > cgroup.subtree_control
  # cat cpuset.cpus.isolated
  10
  # mkdir A
  # echo 10-12 > A/cpuset.cpus
  # echo isolated > A/cpuset.cpus.partition
  # cat A/cpuset.cpus.partition
  isolated

Before the patch:

  # echo root > A/cpuset.cpus.partition
  # cat A/cpuset.cpus.partition
  root invalid (partition config conflicts with housekeeping setup)
  # cat cpuset.cpus.isolated .__DEBUG__.cpuset.cpus.subpartitions
  10-12
  10-12

After the patch:

  # echo root > A/cpuset.cpus.partition
  # cat A/cpuset.cpus.partition
  root invalid (partition config conflicts with housekeeping setup)
  # cat cpuset.cpus.isolated .__DEBUG__.cpuset.cpus.subpartitions
  10
Fixes 4a74e418881f ("cgroup/cpuset: Check partition conflict with housekeeping setup")
Fixes 103b08709e8a ("cgroup/cpuset: Fail if isolated and nohz_full don't leave any housekeeping")
---
 kernel/cgroup/cpuset.c | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)
kernel/cgroup/cpuset.c +12 -5
index 4a38da24c3612..751ea3d6dcc0a 100644
@@ -3140,6 +3140,7 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 	struct cpuset *parent = parent_cs(cs);
 	struct tmpmasks tmpmask;
 	bool isolcpus_updated = false;
+	bool disable_partition = false;
 
 	if (old_prs == new_prs)
 		return 0;
@@ -3200,15 +3201,21 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 		 * Need to update isolated_cpus.
 		 */
 		if (prstate_housekeeping_conflict(new_prs, parent_prs,
-						  cs->effective_xcpus, NULL))
+						  cs->effective_xcpus, NULL)) {
+			disable_partition = true;
 			err = PERR_HKEEPING;
-		else
+		} else {
 			isolcpus_updated = true;
+		}
 	} else {
 		/*
 		 * Switching back to member is always allowed even if it
 		 * disables child partitions.
 		 */
+		disable_partition = true;
+	}
+
+	if (disable_partition) {
 		if (is_remote_partition(cs))
 			remote_partition_disable(cs, &tmpmask);
 		else
@@ -3217,7 +3224,7 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 
 		/*
 		 * Invalidation of child partitions will be done in
-		 * update_cpumasks_hier().
+		 * update_cpumasks_hier() below.
 		 */
 	}
 out:
@@ -3240,8 +3247,8 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 	spin_unlock_irq(&callback_lock);
 	update_isolation_cpumasks(isolcpus_updated);
 
-	/* Force update if switching back to member & update effective_xcpus */
-	update_cpumasks_hier(cs, &tmpmask, !new_prs);
+	/* Force update if partition is disabled & update effective_xcpus */
+	update_cpumasks_hier(cs, &tmpmask, disable_partition);
 
 	/* A newly created partition must have effective_xcpus set */
 	WARN_ON_ONCE(!old_prs && (new_prs > 0)
Signature · 1 line
2.53.0
author maintainer
#618 lore raw

PATCH 617/990 RDMA/mlx5: Validate priority in STEERING_ANCHOR_CREATE handler

In reply to Greg Kroah-Hartman

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

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

From: Serhat Kumral <[email protected]>

[ Upstream commit bb75e5580b15cd23ededf15683a5ad67d7b61aab ]

In MLX5_IB_METHOD_STEERING_ANCHOR_CREATE, the user-supplied u16 priority is passed directly to _get_flow_table() without an upper bound check. This can lead to out-of-bounds array accesses on dev->flow_db priority tables.

Check that priority does not exceed MLX5_IB_FLOW_LAST_PRIO before calling _get_flow_table(), matching the existing validation in raw_fs_rule_add() and mlx5_ib_create_flow().

Fixes 0c6ab0ca9a66 ("RDMA/mlx5: Expose steering anchor to userspace")
[ sashal: Kept the branch's kzalloc(sizeof(*obj), GFP_KERNEL) as context instead of upstream's kzalloc_obj(*obj), with the same 3-line priority bounds check added before it. ]
---
 drivers/infiniband/hw/mlx5/fs.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/infiniband/hw/mlx5/fs.c +3 -0
index b67994df98f2c..af3fd7781e685 100644
@@ -2999,6 +2999,9 @@ static int UVERBS_HANDLER(MLX5_IB_METHOD_STEERING_ANCHOR_CREATE)(
 	if (err)
 		return err;
 
+	if (priority > MLX5_IB_FLOW_LAST_PRIO)
+		return -EINVAL;
+
 	obj = kzalloc(sizeof(*obj), GFP_KERNEL);
 	if (!obj)
 		return -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#619 lore raw

PATCH 618/990 xsk: freeze deferred pool teardown without blocking unregister

In reply to Greg Kroah-Hartman

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

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

From: James Hilliard <[email protected]>

[ Upstream commit fece8420e76fe53ee84f0439f18d026b4c7641da ]

Deferred pool destruction calls ndo_bpf() under RTNL. system_wq is not frozen during system sleep, so that callback can run after a device has suspended and gated its clocks. Use system_freezable_wq so running destruction finishes before device suspend and new work waits until process thaw.

Keep assigned pools visible to NETDEV_UNREGISTER independently of the socket list. A released socket has already left that list, but its final pool put can queue destruction after workqueues freeze. A resume-time unregister would then wait for a device reference whose release cannot run until the resume completes.

Track assigned pools per netdev with netdev operations locking and detach remaining pools after the notifier socket walk, including copy-mode pools. This also covers leased queues without scanning pools from unrelated devices or network namespaces. Remove the entry on assignment failure and normal teardown. The deferred worker still owns the pool and later observes the cleared device pointer, avoiding a second driver detach or put.

The lifetime problem was identified by code inspection of the deferred release and system-sleep paths.

Fixes 1c1efc2af158 ("xsk: Create and free buffer pool independently from umem")
[ sashal: Replaced the missing netdev_assert_locked_ops_compat() with this tree's equivalent netdev_ops_assert_locked(), and dropped the old assertion before ndo_bpf() so it isn't duplicated. ]
---
 include/linux/netdevice.h   |  5 ++++
 include/net/xsk_buff_pool.h |  3 +++
 net/xdp/xsk.c               |  5 ++++
 net/xdp/xsk_buff_pool.c     | 46 ++++++++++++++++++++++++++++++-------
 4 files changed, 51 insertions(+), 8 deletions(-)
include/linux/netdevice.h +5 -0
index f08d17f1d2e0a..d367760b902f1 100644
@@ -2497,6 +2497,11 @@ struct net_device {
 	/* protected by rtnl_lock */
 	struct bpf_xdp_entity	xdp_state[__MAX_XDP_MODE];
 
+#ifdef CONFIG_XDP_SOCKETS
+	/** @xsk_pools: assigned AF_XDP pools, ops protected */
+	struct hlist_head	xsk_pools;
+#endif
+
 	u8 dev_addr_shadow[MAX_ADDR_LEN];
 	netdevice_tracker	linkwatch_dev_tracker;
 	netdevice_tracker	watchdog_dev_tracker;
include/net/xsk_buff_pool.h +3 -0
index a461bb63761b7..93b60d7294afb 100644
@@ -48,6 +48,8 @@ struct xsk_buff_pool {
 	struct device *dev;
 	struct net_device *netdev;
 	struct list_head xsk_tx_list;
+	/* Assigned pools, including deferred releases; ops protected. */
+	struct hlist_node dev_node;
 	/* Protects modifications to the xsk_tx_list */
 	spinlock_t xsk_tx_list_lock;
 	refcount_t users;
@@ -124,6 +126,7 @@ bool xp_put_pool(struct xsk_buff_pool *pool);
 void xp_clear_dev(struct xsk_buff_pool *pool);
 void xp_add_xsk(struct xsk_buff_pool *pool, struct xdp_sock *xs);
 void xp_del_xsk(struct xsk_buff_pool *pool, struct xdp_sock *xs);
+void xp_clear_dev_all(struct net_device *dev);
 
 /* AF_XDP, and XDP core. */
 void xp_free(struct xdp_buff_xsk *xskb);
net/xdp/xsk.c +5 -0
index 5d2067777d351..b9008668b3fd8 100644
@@ -2038,6 +2038,11 @@ static int xsk_notifier(struct notifier_block *this,
 			mutex_unlock(&xs->mutex);
 		}
 		mutex_unlock(&net->xdp.lock);
+		/*
+		 * A released socket is no longer on xdp.list. Its pool can still
+		 * hold a device reference on the frozen release workqueue.
+		 */
+		xp_clear_dev_all(dev);
 		break;
 	}
 	return NOTIFY_DONE;
net/xdp/xsk_buff_pool.c +38 -8

90 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#620 lore raw

PATCH 619/990 ip6mr: clear skb->cb[] in reg_vif_xmit()

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 238164201431a425e48dfcb8e9a59de63caf175b ]

reg_vif_xmit() hands the skb to ip6mr_cache_report() as an MRT6MSG_WHOLEPKT report. skb_realloc_headroom() copies skb->cb[] into the report, which is queued to the mroute socket, where rawv6_recvmsg() reads it as IP6CB.

By the time the pim6reg device transmits the packet, skb->cb[] is not IP6CB anymore: qdisc_pkt_len_init() overwrites iif and ra, and any qdisc installed on the device (fq, fq_codel, pie, cake...) or a tc BPF program writing skb->cb[] fills the area holding dst0, srcrt, dst1, lastopt and flags.

Since commit dd433671fef3 ("ipv6: validate extension header length before copying to cmsg") these stale offsets can no longer cause out-of-bounds reads, but the mroute socket can still receive bogus IPV6_PKTINFO ifindex and extension header ancillary data.

Clear IP6CB before building the report. The skb is freed right after, so nothing else depends on its control block.

Fixes 14fb64e1f449 ("[IPV6] MROUTE: Support PIM-SM (SSM).")
[ sashal: Kept the branch's rcu_read_lock(); line as context and inserted the upstream memset and comment after it. ]
---
 net/ipv6/ip6mr.c | 7 +++++++
 1 file changed, 7 insertions(+)
net/ipv6/ip6mr.c +7 -0
index 53837248498a6..5a49fb4ae4513 100644
@@ -629,6 +629,13 @@ static netdev_tx_t reg_vif_xmit(struct sk_buff *skb,
 	DEV_STATS_ADD(dev, tx_bytes, skb->len);
 	DEV_STATS_INC(dev, tx_packets);
 	rcu_read_lock();
+
+	/* skb->cb[] holds qdisc/tc state at this point, not IP6CB.
+	 * ip6mr_cache_report() copies it to the report delivered to
+	 * the mroute socket, where it is read as IP6CB.
+	 */
+	memset(IP6CB(skb), 0, sizeof(*IP6CB(skb)));
+
 	ip6mr_cache_report(mrt, skb, READ_ONCE(mrt->mroute_reg_vif_num),
 			   MRT6MSG_WHOLEPKT);
 	rcu_read_unlock();
Signature · 1 line
2.53.0
author maintainer
#621 lore raw

PATCH 620/990 exfat: fix used_clusters accounting during cluster allocation

In reply to Greg Kroah-Hartman

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

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

From: Chi Zhiling <[email protected]>

[ Upstream commit cb9dbf8a4e34b4fdf311598835ab4d76ed7e07c1 ]

In the current exfat_alloc_cluster(), p_chain->size is incremented as each cluster is allocated so that the partially allocated chain can be freed by __exfat_free_cluster() on the error path.

However, sbi->used_clusters is still updated only after all clusters have been allocated, while __exfat_free_cluster() unconditionally subtracts the number of freed clusters from sbi->used_clusters. Therefore, when allocation fails partway through, the partially allocated clusters are subtracted from sbi->used_clusters even though they were never added to it. This corrupts the free-space accounting and can cause sbi->used_clusters to underflow.

Increment sbi->used_clusters together with p_chain->size as each cluster is allocated. This keeps the accounting consistent with __exfat_free_cluster() on both the success and error paths.

This issue is caught by generic/476 with 256k cluster size:

Ran: generic/476
Failures: generic/476
Failed 1 of 1 tests

*** fsck.exfat output ***
ERROR: <path>: more clusters are allocated. truncate to N bytes
...
/dev/vdc: corrupted. directories 331, files 526 /dev/vdc: files corrupted 9, files fixed 0
*** end fsck.exfat output ***

Fixes d5c514b6a0c0 ("exfat: fix the newly allocated clusters are not freed in error handling")
[ sashal: Dropped the blank line after the removed sbi->used_clusters += num_alloc; because this tree's success block lacks the done: label and uses num_alloc instead of p_chain->size. ]
---
 fs/exfat/fatent.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
fs/exfat/fatent.c +1 -2
index 825083634ba2d..13a79845be016 100644
@@ -431,13 +431,12 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 			}
 		}
 		p_chain->size++;
+		sbi->used_clusters++;
 
 		last_clu = new_clu;
 
 		if (p_chain->size == num_alloc) {
 			sbi->clu_srch_ptr = hint_clu;
-			sbi->used_clusters += num_alloc;
-
 			mutex_unlock(&sbi->bitmap_lock);
 			return 0;
 		}
Signature · 1 line
2.53.0
author maintainer
#622 lore raw

PATCH 621/990 exfat: take bitmap_lock at the start of exfat_alloc_cluster()

In reply to Greg Kroah-Hartman

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

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

From: Chi Zhiling <[email protected]>

[ Upstream commit 48acff2eedef7fecdfbd39be1b6f4463a9e43e3e ]

exfat_alloc_cluster() checks sbi->used_clusters against the total number of data clusters before acquiring sbi->bitmap_lock. A concurrent allocation can update sbi->used_clusters after the check but before the lock is acquired, making the check stale. This can allow the allocation to proceed even though there are not enough free clusters, causing it to fail partway through.

Acquire sbi->bitmap_lock before checking sbi->used_clusters so that the free-space check and subsequent cluster allocation are serialized with concurrent allocations.

Fixes f55c096f62f1 ("exfat: do not zero the extended part")
---
 fs/exfat/fatent.c | 17 ++++++++++-------
 1 file changed, 10 insertions(+), 7 deletions(-)
fs/exfat/fatent.c +10 -7
index 13a79845be016..87c7823efa718 100644
@@ -355,19 +355,22 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 	struct super_block *sb = inode->i_sb;
 	struct exfat_sb_info *sbi = EXFAT_SB(sb);
 
+	mutex_lock(&sbi->bitmap_lock);
+
 	total_cnt = EXFAT_DATA_CLUSTER_COUNT(sbi);
 
 	if (unlikely(total_cnt < sbi->used_clusters)) {
 		exfat_fs_error_ratelimit(sb,
 			"%s: invalid used clusters(t:%u,u:%u)\n",
 			__func__, total_cnt, sbi->used_clusters);
-		return -EIO;
+		ret = -EIO;
+		goto unlock;
 	}
 
-	if (num_alloc > total_cnt - sbi->used_clusters)
-		return -ENOSPC;
-
-	mutex_lock(&sbi->bitmap_lock);
+	if (num_alloc > total_cnt - sbi->used_clusters) {
+		ret = -ENOSPC;
+		goto unlock;
+	}
 
 	hint_clu = p_chain->dir;
 	/* find new cluster */
@@ -437,8 +440,8 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 
 		if (p_chain->size == num_alloc) {
 			sbi->clu_srch_ptr = hint_clu;
-			mutex_unlock(&sbi->bitmap_lock);
-			return 0;
+			ret = 0;
+			goto unlock;
 		}
 
 		hint_clu = new_clu + 1;
Signature · 1 line
2.53.0
author maintainer
#623 lore raw

PATCH 622/990 ksmbd: disconnect on invalid encryption transform flags

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 0882f124ae329eefb66b00e63b9043f24c006b0e ]

MS-SMB2 3.3.5.2.1.1 requires the Flags/EncryptionAlgorithm field in an SMB2 transform header to be 0x0001. The server must disconnect the connection when it has any other value.

smb3_decrypt_req() currently ignores this field. A client with the session key can therefore send a correctly authenticated encrypted request with invalid flags and have it processed. Check the field before looking up the session key or decrypting the request. The caller aborts the connection when this check fails.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
[ sashal: Added a transform-flags check to smb3_decrypt_req() unchanged, but anchored it after the "Transform message is too small" check because the surrounding length-check code differs on this branch. ]
---
 fs/smb/server/smb2pdu.c | 6 ++++++
 1 file changed, 6 insertions(+)
fs/smb/server/smb2pdu.c +6 -0
index 53094243d456b..88f07ec22723a 100644
@@ -9651,6 +9651,12 @@ int smb3_decrypt_req(struct ksmbd_work *work)
 		return -ECONNABORTED;
 	}
 
+	if (tr_hdr->Flags != cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED)) {
+		pr_err_ratelimited("Invalid transform flags 0x%04x\n",
+				   le16_to_cpu(tr_hdr->Flags));
+		return -ECONNABORTED;
+	}
+
 	if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
 		pr_err("Transform message is broken\n");
 		return -ECONNABORTED;
Signature · 1 line
2.53.0
author maintainer
#624 lore raw

PATCH 623/990 ksmbd: cache the resolved share path for durable reconnects

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 2a90ba573d41efa82e075ba9ac532bb3ec0519c4 ]

A share configured as /a/link/b, with /a/link pointing to /real, is opened relative to share->vfs_path at /real/b. However, ksmbd_validate_name_reconnect() compares the file's d_path() result against the original /a/link/b string and rejects a valid reconnect.

Render share->vfs_path with d_path() after the existing kern_path() lookup and cache a copy in real_path along with its length. Use the resolved string for durable reconnect name validation. Keep path and path_sz as the configured spelling for existing consumers, including the volume serial calculation and path lookups.

Fixes c8efcc786146 ("ksmbd: add support for durable handles v1/v2")
[ sashal: Dropped the scoped_with_init_fs() wrapper around the share_config_resolve_path() call and the fs_struct.h include, since this tree has neither and calls the helper directly. ]
---
 fs/smb/server/mgmt/share_config.c | 43 +++++++++++++++++++++++++++++--
 fs/smb/server/mgmt/share_config.h |  2 ++
 fs/smb/server/vfs_cache.c         | 12 +++++----
 3 files changed, 50 insertions(+), 7 deletions(-)
fs/smb/server/mgmt/share_config.c +41 -2
index 8813a81ca6629..5fbc2235ab8d3 100644
@@ -8,6 +8,7 @@
 #include <linux/slab.h>
 #include <linux/rwsem.h>
 #include <linux/parser.h>
+#include <linux/dcache.h>
 #include <linux/namei.h>
 #include <linux/sched.h>
 #include <linux/mm.h>
@@ -50,6 +51,7 @@ static void kill_share(struct ksmbd_share_config *share)
 		path_put(&share->vfs_path);
 	kfree(share->name);
 	kfree(share->path);
+	kfree(share->real_path);
 	kfree(share);
 }
 
@@ -124,6 +126,43 @@ static int parse_veto_list(struct ksmbd_share_config *share,
 	return 0;
 }
 
+static int share_config_resolve_path(struct ksmbd_share_config *share)
+{
+	char *buf, *path;
+	int ret;
+
+	ret = kern_path(share->path, 0, &share->vfs_path);
+	if (ret)
+		return ret;
+
+	buf = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
+	if (!buf) {
+		ret = -ENOMEM;
+		goto out;
+	}
+
+	path = d_path(&share->vfs_path, buf, PATH_MAX);
+	if (IS_ERR(path)) {
+		ret = PTR_ERR(path);
+		goto out_buf;
+	}
+
+	path = kstrdup(path, KSMBD_DEFAULT_GFP);
+	if (!path) {
+		ret = -ENOMEM;
+		goto out_buf;
+	}
+
+	share->real_path = path;
+	share->real_path_sz = strlen(path);
+out_buf:
+	kfree(buf);
+out:
+	if (ret)
+		path_put(&share->vfs_path);
+	return ret;
+}
+
 static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work,
 						       const char *name)
 {
@@ -212,12 +251,12 @@ static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work,
 				goto out;
 			}
 
-			ret = kern_path(share->path, 0, &share->vfs_path);
+			ret = share_config_resolve_path(share);
 			ksmbd_revert_fsids(work);
 			if (ret) {
 				ksmbd_debug(SMB, "failed to access '%s'\n",
 					    share->path);
-				/* Avoid put_path() */
+				/* No path reference is retained on failure. */
 				kfree(share->path);
 				share->path = NULL;
 			}
fs/smb/server/mgmt/share_config.h +2 -0
index d4ac2dd4de204..baa9f9ed91cde 100644
@@ -16,8 +16,10 @@ struct ksmbd_work;
 struct ksmbd_share_config {
 	char			*name;
 	char			*path;
+	char			*real_path;
 
 	unsigned int		path_sz;
+	unsigned int		real_path_sz;
 	unsigned int		flags;
 	struct list_head	veto_list;
 
fs/smb/server/vfs_cache.c +7 -5
index 2621d2cffe619..b1ee76949a2ea 100644
@@ -1355,6 +1355,8 @@ void ksmbd_free_global_file_table(void)
 int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share,
 				  struct ksmbd_file *fp, char *name)
 {
+	const char *share_path = share->real_path;
+	size_t share_path_sz = share->real_path_sz;
 	char *pathname, *ab_pathname;
 	int ret = 0;
 
@@ -1371,14 +1373,14 @@ int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share,
 	if (name) {
 		size_t len = strlen(ab_pathname);
 
-		if (len == share->path_sz && !strncmp(ab_pathname, share->path, len)) {
+		if (len == share_path_sz && !strncmp(ab_pathname, share_path, len)) {
 			/* the durable fp is the share root itself */
 			if (name[0])
 				ret = -EINVAL;
-		} else if (len <= share->path_sz ||
-			   strncmp(ab_pathname, share->path, share->path_sz) ||
-			   ab_pathname[share->path_sz] != '/' ||
-			   strcmp(&ab_pathname[share->path_sz + 1], name)) {
+		} else if (len <= share_path_sz ||
+			   strncmp(ab_pathname, share_path, share_path_sz) ||
+			   ab_pathname[share_path_sz] != '/' ||
+			   strcmp(&ab_pathname[share_path_sz + 1], name)) {
 			ret = -EINVAL;
 		}
 		if (ret)
Signature · 1 line
2.53.0
author maintainer
#625 lore raw

PATCH 624/990 ksmbd: fix durable reconnects for root shares

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 25e36df831a47597c03c6239fbc71285e7d714c2 ]

When a share exports "/", ksmbd_validate_name_reconnect() expects another slash after the share path. For a file at /foo, this rejects the valid reconnect name "foo" even though the file is in the share.

Compare the requested name with the rendered file path after its leading slash when the resolved share root is "/". Keep the exact-root/empty-name check and reject rendered paths without an initial slash.

Fixes c8efcc786146 ("ksmbd: add support for durable handles v1/v2")
---
 fs/smb/server/vfs_cache.c | 4 ++++
 1 file changed, 4 insertions(+)
fs/smb/server/vfs_cache.c +4 -0
index b1ee76949a2ea..52389fff3d4a0 100644
@@ -1377,6 +1377,10 @@ int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share,
 			/* the durable fp is the share root itself */
 			if (name[0])
 				ret = -EINVAL;
+		} else if (share_path_sz == 1 && share_path[0] == '/') {
+			if (ab_pathname[0] != '/' ||
+			    strcmp(ab_pathname + 1, name))
+				ret = -EINVAL;
 		} else if (len <= share_path_sz ||
 			   strncmp(ab_pathname, share_path, share_path_sz) ||
 			   ab_pathname[share_path_sz] != '/' ||
Signature · 1 line
2.53.0
author maintainer
#626 lore raw

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

In reply to Greg Kroah-Hartman

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

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

From: Ajanesh Lal <[email protected]>

[ Upstream commit ed7995e4ec3789a90e37eb826bfccf43cc85d2fd ]

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

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

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

Fixes aa8e3ef4fe53 ("ALSA: hda/realtek: Add quirks for various HP ENVY models")
Assisted-by Claude:claude-haiku-5-5
[ sashal: Added the new enum value and fixup table entry after the tree's last entries, since the context entries the upstream patch anchors on are missing, and left out the unneeded ALC245_FIXUP_CS35L41_I2C_2_MUTE_LED additions. ]
---
 sound/hda/codecs/realtek/alc269.c | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)
sound/hda/codecs/realtek/alc269.c +16 -1
index 6ee95ae0e8f67..dbc7b56f4d42b 100644
@@ -1585,6 +1585,14 @@ static void alc245_fixup_hp_mute_led_coefbit(struct hda_codec *codec,
 	}
 }
 
+/* mute LED via COEF bit and mic-mute LED via GPIO, called directly */
+static void alc245_fixup_cs35l41_mute_micmute(struct hda_codec *codec,
+					      const struct hda_fixup *fix, int action)
+{
+	alc245_fixup_hp_mute_led_coefbit(codec, fix, action);
+	alc245_fixup_hp_gpio_led(codec, fix, action);
+}
+
 static void alc245_fixup_hp_mute_led_v1_coefbit(struct hda_codec *codec,
 					  const struct hda_fixup *fix,
 					  int action)
@@ -4045,6 +4053,7 @@ enum {
 	ALC289_FIXUP_ASUS_ZEPHYRUS_DUAL_SPK,
 	ALC256_FIXUP_VAIO_RPL_MIC_NO_PRESENCE,
 	ALC245_FIXUP_ACER_MICMUTE_LED,
+	ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED,
 };
 
 /* A special fixup for Lenovo C940 and Yoga Duet 7;
@@ -6668,6 +6677,12 @@ static const struct hda_fixup alc269_fixups[] = {
 		.v.func = alc285_fixup_hp_coef_micmute_led,
 		.chained = true,
 		.chain_id = ALC2XX_FIXUP_HEADSET_MIC,
+	},
+	[ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED] = {
+		.type = HDA_FIXUP_FUNC,
+		.v.func = alc245_fixup_cs35l41_mute_micmute,
+		.chained = true,
+		.chain_id = ALC287_FIXUP_CS35L41_I2C_2,
 	}
 };
 
@@ -7103,7 +7118,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x103c, 0x8be1, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be2, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be3, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
-	SND_PCI_QUIRK(0x103c, 0x8be5, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2),
+	SND_PCI_QUIRK(0x103c, 0x8be5, "HP Envy 16", ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED),
 	SND_PCI_QUIRK(0x103c, 0x8be6, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be7, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be8, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS),
Signature · 1 line
2.53.0
author maintainer
#627 lore raw

PATCH 626/990 perf lock contention: Filter events before creating lock_stat

In reply to Greg Kroah-Hartman

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

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

From: Ian Rogers <[email protected]>

[ Upstream commit c58d1598e79554cc8f587668ab2ebcaeb616b076 ]

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

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

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

Fixes b4a7eff93c39f985 ("perf lock contention: Add -Y/--type-filter option")
[ sashal: Used the tree's lock_contention_caller(evsel, sample, ...) signature, with the extra evsel argument, in the moved lock_stat lookup block instead of upstream's lock_contention_caller(sample, ...). ]
---
 tools/perf/builtin-lock.c | 61 +++++++++++++++++++++------------------
 1 file changed, 33 insertions(+), 28 deletions(-)
tools/perf/builtin-lock.c +33 -28
index 5585aeb97684d..66bfd9e4fe17f 100644
@@ -977,6 +977,7 @@ static int report_lock_contention_begin_event(struct evsel *evsel,
 	struct machine *machine = &session->machines.host;
 	struct map *kmap;
 	struct symbol *sym;
+	u64 *callstack = NULL;
 
 	ret = get_key_by_aggr_mode(&key, addr, evsel, sample);
 	if (ret < 0)
@@ -1012,33 +1013,6 @@ static int report_lock_contention_begin_event(struct evsel *evsel,
 		}
 	}
 
-	ls = lock_stat_find(key);
-	if (!ls) {
-		char buf[128];
-		const char *name = "";
-
-		switch (aggr_mode) {
-		case LOCK_AGGR_ADDR:
-			sym = machine__find_kernel_symbol(machine, key, &kmap);
-			if (sym)
-				name = sym->name;
-			break;
-		case LOCK_AGGR_CALLER:
-			name = buf;
-			if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0)
-				name = "Unknown";
-			break;
-		case LOCK_AGGR_CGROUP:
-		case LOCK_AGGR_TASK:
-		default:
-			break;
-		}
-
-		ls = lock_stat_findnew(key, name, flags);
-		if (!ls)
-			return -ENOMEM;
-	}
-
 	if (filters.nr_types) {
 		bool found = false;
 
@@ -1068,7 +1042,7 @@ static int report_lock_contention_begin_event(struct evsel *evsel,
 	}
 
 	if (needs_callstack()) {
-		u64 *callstack = get_callstack(sample, max_stack_depth);
+		callstack = get_callstack(sample, max_stack_depth);
 		if (callstack == NULL)
 			return -ENOMEM;
 
@@ -1076,7 +1050,38 @@ static int report_lock_contention_begin_event(struct evsel *evsel,
 			free(callstack);
 			return 0;
 		}
+	}
+
+	ls = lock_stat_find(key);
+	if (!ls) {
+		char buf[128];
+		const char *name = "";
+
+		switch (aggr_mode) {
+		case LOCK_AGGR_ADDR:
+			sym = machine__find_kernel_symbol(machine, key, &kmap);
+			if (sym)
+				name = sym->name;
+			break;
+		case LOCK_AGGR_CALLER:
+			name = buf;
+			if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0)
+				name = "Unknown";
+			break;
+		case LOCK_AGGR_CGROUP:
+		case LOCK_AGGR_TASK:
+		default:
+			break;
+		}
+
+		ls = lock_stat_findnew(key, name, flags);
+		if (!ls) {
+			free(callstack);
+			return -ENOMEM;
+		}
+	}
 
+	if (callstack) {
 		if (ls->callstack == NULL)
 			ls->callstack = callstack;
 		else
Signature · 1 line
2.53.0
author maintainer
#628 lore raw

PATCH 627/990 zram: fix short reads from block_state

In reply to Greg Kroah-Hartman

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

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

From: Pooyan Azad <[email protected]>

[ Upstream commit 372012202260db088b489ed00059c4571a602552 ]

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

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

Fixes c0265342bff4 ("zram: introduce zram memory tracking")
Cc Minchan Kim <[email protected]>
Cc Jens Axboe <[email protected]>
[ sashal: Renamed this tree's older helpers and lock (init_lock, zram_slot_lock, zram_allocated, etc.) in place of upstream's, and kept the ktime_t-based timestamp formatting instead of upstream's integer ac_time print. ]
---
 drivers/block/zram/zram_drv.c | 105 +++++++++++++++++-----------------
 1 file changed, 53 insertions(+), 52 deletions(-)
drivers/block/zram/zram_drv.c +53 -52
index ea5a9b81a310e..1ef4a15947683 100644
@@ -1134,72 +1134,73 @@ static void zram_debugfs_destroy(void)
 	debugfs_remove_recursive(zram_debugfs_root);
 }
 
-static ssize_t read_block_state(struct file *file, char __user *buf,
-				size_t count, loff_t *ppos)
+static void *zram_block_state_start(struct seq_file *seq, loff_t *pos)
 {
-	char *kbuf;
-	ssize_t index, written = 0;
-	struct zram *zram = file->private_data;
+	struct zram *zram = seq->private;
 	unsigned long nr_pages;
 
-	kbuf = kvmalloc(count, GFP_KERNEL);
-	if (!kbuf)
-		return -ENOMEM;
-
 	down_read(&zram->init_lock);
-	if (!init_done(zram)) {
-		up_read(&zram->init_lock);
-		kvfree(kbuf);
-		return -EINVAL;
-	}
+	if (!init_done(zram))
+		return ERR_PTR(-EINVAL);
 
 	nr_pages = zram->disksize >> PAGE_SHIFT;
+	if (*pos >= nr_pages)
+		return NULL;
 
-	for (index = *ppos; index < nr_pages; index++) {
-		int copied;
-		struct timespec64 ts;
+	return pos;
+}
 
-		zram_slot_lock(zram, index);
-		if (!zram_allocated(zram, index))
-			goto next;
+static void *zram_block_state_next(struct seq_file *seq, void *v, loff_t *pos)
+{
+	struct zram *zram = seq->private;
+	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
 
-		ts = ktime_to_timespec64(zram->table[index].ac_time);
-		copied = snprintf(kbuf + written, count,
-			"%12zd %12lld.%06lu %c%c%c%c%c%c\n",
-			index, (s64)ts.tv_sec,
-			ts.tv_nsec / NSEC_PER_USEC,
-			zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
-			zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
-			zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
-			zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
-			zram_get_priority(zram, index) ? 'r' : '.',
-			zram_test_flag(zram, index,
-				       ZRAM_INCOMPRESSIBLE) ? 'n' : '.');
-
-		if (count <= copied) {
-			zram_slot_unlock(zram, index);
-			break;
-		}
-		written += copied;
-		count -= copied;
-next:
-		zram_slot_unlock(zram, index);
-		*ppos += 1;
-	}
+	++*pos;
+	if (*pos >= nr_pages)
+		return NULL;
+
+	return pos;
+}
+
+static void zram_block_state_stop(struct seq_file *seq, void *v)
+{
+	struct zram *zram = seq->private;
 
 	up_read(&zram->init_lock);
-	if (copy_to_user(buf, kbuf, written))
-		written = -EFAULT;
-	kvfree(kbuf);
+}
 
-	return written;
+static int zram_block_state_show(struct seq_file *seq, void *v)
+{
+	struct zram *zram = seq->private;
+	unsigned long index = *(loff_t *)v;
+	struct timespec64 ts;
+
+	zram_slot_lock(zram, index);
+	if (zram_allocated(zram, index)) {
+		ts = ktime_to_timespec64(zram->table[index].ac_time);
+		seq_printf(seq, "%12lu %12lld.%06lu %c%c%c%c%c%c\n",
+			   index, (s64)ts.tv_sec,
+			   ts.tv_nsec / NSEC_PER_USEC,
+			   zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
+			   zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
+			   zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
+			   zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
+			   zram_get_priority(zram, index) ? 'r' : '.',
+			   zram_test_flag(zram, index,
+					  ZRAM_INCOMPRESSIBLE) ? 'n' : '.');
+	}
+	zram_slot_unlock(zram, index);
+
+	return 0;
 }
 
-static const struct file_operations proc_zram_block_state_op = {
-	.open = simple_open,
-	.read = read_block_state,
-	.llseek = default_llseek,
+static const struct seq_operations zram_block_state_sops = {
+	.start = zram_block_state_start,
+	.next = zram_block_state_next,
+	.stop = zram_block_state_stop,
+	.show = zram_block_state_show,
 };
+DEFINE_SEQ_ATTRIBUTE(zram_block_state);
 
 static void zram_debugfs_register(struct zram *zram)
 {
@@ -1209,7 +1210,7 @@ static void zram_debugfs_register(struct zram *zram)
 	zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
 						zram_debugfs_root);
 	debugfs_create_file("block_state", 0400, zram->debugfs_dir,
-				zram, &proc_zram_block_state_op);
+				zram, &zram_block_state_fops);
 }
 
 static void zram_debugfs_unregister(struct zram *zram)
Signature · 1 line
2.53.0
author maintainer
#629 lore raw

PATCH 628/990 cgroup/cpuset: Find furthest isolated ancestor for invalidated isolated partition

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 0bce85ff2cc0f7f7d8de16f5fdfc0ae7d29f21f1 ]

Commit 46b885416c27 ("cgroup/cpuset: Fix a missing isolated_cpus update in update_cpumasks_hier()") searches for the closet partition root ancestor to determine if the isolated CPUs in a to be invalidated isolation partition should be removed from isolated_cpus or not.

As reported by sashiko, this method may not work when there is a deeply nested isolated partition hierarchy. For instance, Consider a nested hierarchy A0 -> A1 -> A2 -> A3 where all four are PRS_ISOLATED:

A0: effective_xcpus = 0-4
A1: effective_xcpus = 1-4
A2: effective_xcpus = 2-4
A3: effective_xcpus = 3-4

When A1 shrinks its exclusive_cpus from 1-4 to 1-2, A2 will update it effective_xcpus to 2. A3 will find its closet partition root ancestor A2 and decides that its effective_xcpus 3-4 should be removed from isolated_cpus which is incorrect.

Address this corner case by adding a new isolated_cpus_release() helper to replace the existing ancestor_partition() helper. This new helper will search for the furthest isolated partition root ancestor to decide if some or all of its isolated CPUs should be removed from isolated_cpus and also perform the removal when appropriate.

The is_remote_partition() and is_local_partition() helpers are also moved up so they can be used in earlier functions.

There are other pre-existing problems that will still prevent the above test case to work correctly. These problems will be addressed in subsequent patches.

Fixes 46b885416c27 ("cgroup/cpuset: Fix a missing isolated_cpus update in update_cpumasks_hier()")
[ sashal: Replaced the upstream cs->remote_partition check in is_remote_partition() with this tree's remote_sibling list test, and adjusted context around the plain isolated_cpus_update(). ]
---
 kernel/cgroup/cpuset.c | 104 +++++++++++++++++++++--------------------
 1 file changed, 53 insertions(+), 51 deletions(-)
kernel/cgroup/cpuset.c +53 -51
index 751ea3d6dcc0a..54ee036020e05 100644
@@ -1348,6 +1348,16 @@ static void reset_partition_data(struct cpuset *cs)
 		cpumask_copy(cs->effective_cpus, parent->effective_cpus);
 }
 
+static inline bool is_remote_partition(struct cpuset *cs)
+{
+	return !list_empty(&cs->remote_sibling);
+}
+
+static inline bool is_local_partition(struct cpuset *cs)
+{
+	return is_partition_valid(cs) && !is_remote_partition(cs);
+}
+
 /*
  * isolated_cpus_update - Update the isolated_cpus mask
  * @old_prs: old partition_root_state
@@ -1363,6 +1373,45 @@ static void isolated_cpus_update(int old_prs, int new_prs, struct cpumask *xcpus
 		cpumask_andnot(isolated_cpus, isolated_cpus, xcpus);
 }
 
+/*
+ * isolated_cpus_release - Remove the relevant CPUs in @xcpus from isolated_cpus
+ * @cs: the current cpuset
+ * @xcpus: the set of effective xcpus to be considered for removal
+ *
+ * This function is called when an isolated partition is invalidated or when
+ * some of its effective xcpus are to be removed from isolated_cpus due to
+ * changes in parent cpuset. The given @xcpus must be modifiable as the function
+ * will update its value to determine the right set of CPUs to be removed.
+ */
+static void isolated_cpus_release(struct cpuset *cs, struct cpumask *xcpus)
+{
+	struct cpuset *ancestor = parent_cs(cs);
+	struct cpuset *iancestor = NULL;
+
+	/*
+	 * Search the furthest isolated partition root ancestor available
+	 * until top_cpuset or a remote partition root is hit.
+	 */
+	for (; ancestor; ancestor = parent_cs(ancestor)) {
+		if (ancestor->partition_root_state == PRS_ISOLATED)
+			iancestor = ancestor;
+		if (is_remote_partition(ancestor))
+			break;
+	}
+
+	/*
+	 * If a furthest isolated partition acnestor is found, use it to
+	 * determine which of the CPUs in @xcpus should be removed from
+	 * isolated_cpus. Otherwise, all of them will be removed.
+	 */
+	if (iancestor && !cpumask_andnot(xcpus, xcpus, iancestor->effective_xcpus))
+		return; /* No CPU should be removed from isolated_cpus */
+
+	spin_lock_irq(&callback_lock);
+	isolated_cpus_update(PRS_ISOLATED, PRS_ROOT, xcpus);
+	spin_unlock_irq(&callback_lock);
+}
+
 /*
  * partition_xcpus_add - Add new exclusive CPUs to partition
  * @new_prs: new partition_root_state
@@ -1621,16 +1670,6 @@ static int compute_trialcs_excpus(struct cpuset *trialcs, struct cpuset *cs)
 	return rm_siblings_excl_cpus(parent, cs, excpus);
 }
 
-static inline bool is_remote_partition(struct cpuset *cs)
-{
-	return !list_empty(&cs->remote_sibling);
-}
-
-static inline bool is_local_partition(struct cpuset *cs)
-{
-	return is_partition_valid(cs) && !is_remote_partition(cs);
-}
-
 /*
  * remote_partition_enable - Enable current cpuset as a remote partition root
  * @cs: the cpuset to update
@@ -2239,25 +2278,6 @@ static void compute_partition_effective_cpumask(struct cpuset *cs,
 	rcu_read_unlock();
 }
 
-/*
- * ancestor_partition - Find and return the closest valid partition root ancestor
- * @cs: the current cpuset
- *
- * Return: The closet partition root ancestor cpuset
- */
-static struct cpuset *ancestor_partition(struct cpuset *cs)
-{
-	struct cpuset *ancestor = parent_cs(cs);
-
-	/*
-	 * The top_cpuset is always a valid partition root which will stop
-	 * the loop if it is reached.
-	 */
-	while (!is_partition_valid(ancestor))
-		ancestor = parent_cs(ancestor);
-	return ancestor;
-}
-
 /*
  * update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
  * @cs:  the cpuset to consider
@@ -2361,7 +2381,6 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 		 */
 		if ((cp != cs) && old_prs) {
 			int parent_prs = parent->partition_root_state;
-			struct cpumask *del_cpus = NULL;
 
 			switch (parent_prs) {
 			case PRS_ROOT:
@@ -2375,32 +2394,15 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 				 * child partition roots become invalid too.
 				 *
 				 * For a to be invalidated isolated partition,
-				 * its isolated CPUs may or may not need to be
-				 * removed from isolated_cpus depending on if
-				 * its closest partition root ancestor is a root
-				 * or isolated partition. With a PRS_ISOLATED
-				 * ancestor, the CPUs are checked against its
-				 * effective xcpus to see if any of them needed
-				 * to be removed.
+				 * call return_isolated_cpus() to remove the
+				 * relevant CPUs from isolated_cpus.
 				 */
 				if (is_partition_valid(cp))
 					new_prs = -old_prs;
 
 				if (old_prs == PRS_ISOLATED) {
-					struct cpuset *ancestor = ancestor_partition(cp);
-
-					if (ancestor->partition_root_state == PRS_ROOT)
-						del_cpus = cp->effective_xcpus;
-					else if (cpumask_andnot(tmp->delmask,
-								cp->effective_xcpus,
-								ancestor->effective_xcpus))
-						del_cpus = tmp->delmask;
-
-					if (del_cpus) {
-						spin_lock_irq(&callback_lock);
-						isolated_cpus_update(old_prs, new_prs, del_cpus);
-						spin_unlock_irq(&callback_lock);
-					}
+					cpumask_copy(tmp->delmask, cp->effective_xcpus);
+					isolated_cpus_release(cp, tmp->delmask);
 				}
 				WRITE_ONCE(cp->prs_err,
 					   is_partition_invalid(parent)
Signature · 1 line
2.53.0
author maintainer
#630 lore raw

PATCH 629/990 cgroup/cpuset: Properly compute effective xcpus in update_parent_effective_cpumask()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 69a75e4f377629928bd173747b864694c2af4e1c ]

Since the introduction of cpuset.cpus.exclusive in commit e2ffe502ba45 ("cgroup/cpuset: Add cpuset.cpus.exclusive for v2"), a compute_effective_exclusive_cpumask() helper which is later renamed to compute_excpus() is added to compute the effective xcpus of a partition root. However update_parent_effective_cpumask() is not updated in all proper places to use the new helper to check if a given cpuset should remain a valid partition root. This can cause a cpuset to incorrectly remain a valid partition root even if no effective xcpus is left.

Fix that problem by using compute_excpus() to compute the effective xcpus into delmask in all cases except partcmd_disable, partcmd_invalidate or partcmd_update with newmask set and use it for tasks_nocpu_error() check as well as checking its emptiness. This enables us to catch invalid partition root more accurately in update_parent_effective_cpumask().

In the case of partcmd_update with newmask set, the passed in new effective xcpus value will directly be used in the tasks_nocpu_error() check without relying on old data in the cpuset.

For the partcmd_update with NULL newmask case, the cpu exclusivity test there is also relaxed to be performed only if exclusive_cpus is empty.

Some test case are added to test_cpuset_prs.sh for invalidating a partition root due to its effective xcpus becoming empty as well as making sure that an invalid partition can only be revived when exclusive CPUs are available agin.

Fixes e2ffe502ba45 ("cgroup/cpuset: Add cpuset.cpus.exclusive for v2")
[ sashal: Adjusted context for the older base (kept the xcpus declaration and subparts_delta lines, no PERR_ISOPARENT blocks) and added :S+ to parent cpusets in the selftest rows. ]
---
 kernel/cgroup/cpuset.c                        | 86 ++++++++++---------
 .../selftests/cgroup/test_cpuset_prs.sh       | 11 +++
 2 files changed, 56 insertions(+), 41 deletions(-)
kernel/cgroup/cpuset.c +45 -41
index 54ee036020e05..7b13381755d07 100644
@@ -1854,7 +1854,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
  * update_parent_effective_cpumask - update effective_cpus mask of parent cpuset
  * @cs:      The cpuset that requests change in partition root state
  * @cmd:     Partition root state change command
- * @newmask: Optional new cpumask for partcmd_update
+ * @newmask: Optional new effective xcpus for partcmd_update
  * @tmp:     Temporary addmask and delmask
  * Return:   0 or a partition root state error code
  *
@@ -1869,11 +1869,11 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
  * given back to parent's effective_cpus. 0 will always be returned.
  *
  * For partcmd_update, if the optional newmask is specified, the cpu list is
- * to be changed from effective_xcpus to newmask. Otherwise, effective_xcpus is
- * assumed to remain the same. The cpuset should either be a valid or invalid
- * partition root. The partition root state may change from valid to invalid
- * or vice versa. An error code will be returned if transitioning from
- * invalid to valid violates the exclusivity rule.
+ * to be changed from effective_xcpus to newmask. Otherwise, effective_xcpus
+ * will be computed and a valid partition will be invalidated if it is the new
+ * cpumask is empty. The cpuset should either be a valid or invalid partition
+ * root. The partition root state may change from valid to invalid or vice
+ * versa.
  *
  * For partcmd_invalidate, the current partition will be made invalid.
  *
@@ -1941,30 +1941,30 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 	if (!newmask && xcpus_empty(cs))
 		return PERR_CPUSEMPTY;
 
-	nocpu = tasks_nocpu_error(parent, cs, xcpus);
+	/*
+	 * Except for partcmd_disable and non-NULL newmask, use delmask
+	 * to compute the current effective xcpus value and use it for
+	 * tasks_nocpu_error check.
+	 */
+	if ((cmd != partcmd_disable) && !newmask) {
+		compute_excpus(cs, tmp->delmask);
+		nocpu = tasks_nocpu_error(parent, cs, tmp->delmask);
+	}
 
 	if ((cmd == partcmd_enable) || (cmd == partcmd_enablei)) {
-		/*
-		 * Need to call compute_excpus() in case
-		 * exclusive_cpus not set. Sibling conflict should only happen
-		 * if exclusive_cpus isn't set.
-		 */
-		xcpus = tmp->delmask;
-		if (compute_excpus(cs, xcpus))
-			WARN_ON_ONCE(!cpumask_empty(cs->exclusive_cpus));
 		new_prs = (cmd == partcmd_enable) ? PRS_ROOT : PRS_ISOLATED;
 
 		/*
 		 * Enabling partition root is not allowed if its
 		 * effective_xcpus is empty.
 		 */
-		if (cpumask_empty(xcpus))
+		if (cpumask_empty(tmp->delmask))
 			return PERR_INVCPUS;
 
-		if (prstate_housekeeping_conflict(new_prs, parent_prs, xcpus, NULL))
+		if (prstate_housekeeping_conflict(new_prs, parent_prs, tmp->delmask, NULL))
 			return PERR_HKEEPING;
 
-		if (tasks_nocpu_error(parent, cs, xcpus))
+		if (nocpu)
 			return PERR_NOCPUS;
 
 		/*
@@ -1976,17 +1976,15 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		 *
 		 * Warn if it is not the case.
 		 */
-		cpumask_and(tmp->new_cpus, xcpus, cpu_active_mask);
+		cpumask_and(tmp->new_cpus, tmp->delmask, cpu_active_mask);
 		WARN_ON_ONCE(!cpumask_subset(tmp->new_cpus, parent->effective_cpus));
-
 		deleting = true;
 		subparts_delta++;
 	} else if (cmd == partcmd_disable) {
 		/*
 		 * May need to add cpus back to parent's effective_cpus
 		 * (and maybe removed from subpartitions_cpus/isolated_cpus)
-		 * for valid partition root. xcpus may contain CPUs that
-		 * shouldn't be removed from the two global cpumasks.
+		 * for valid partition root.
 		 */
 		if (is_partition_valid(cs)) {
 			cpumask_copy(tmp->addmask, cs->effective_xcpus);
@@ -2003,8 +2001,8 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 			goto write_error;
 		}
 
-		/* Check newmask again, whether cpus are available for parent/cs */
-		nocpu |= tasks_nocpu_error(parent, cs, newmask);
+		/* Check newmask whether cpus are available for parent/cs */
+		nocpu = tasks_nocpu_error(parent, cs, newmask);
 
 		/*
 		 * partcmd_update with newmask:
@@ -2059,7 +2057,7 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		/*
 		 * partcmd_update w/o newmask
 		 *
-		 * delmask = effective_xcpus & parent->effective_cpus
+		 * delmask = newly computed effective xcpus value
 		 *
 		 * This can be called from:
 		 * 1) update_cpumasks_hier()
@@ -2071,43 +2069,49 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		 * A partition error happens when parent has tasks and all
 		 * its effective CPUs will have to be distributed out.
 		 */
-		if (nocpu) {
+		if (nocpu || cpumask_empty(tmp->delmask)) {
 			part_error = PERR_NOCPUS;
 			if (is_partition_valid(cs))
 				adding = cpumask_and(tmp->addmask,
 						xcpus, parent->effective_xcpus);
-		} else if (is_partition_invalid(cs) && !cpumask_empty(xcpus) &&
-			   cpumask_subset(xcpus, parent->effective_xcpus)) {
+		} else if (is_partition_invalid(cs)) {
 			struct cgroup_subsys_state *css;
 			struct cpuset *child;
 			bool exclusive = true;
 
 			/*
 			 * Convert invalid partition to valid has to pass the
-			 * cpu exclusivity test as well as the housekeeping
-			 * check.
+			 * cpu exclusivity test when cpuset.cpus.exclusive is
+			 * empty as well as the housekeeping check.
 			 */
 			if (prstate_housekeeping_conflict(cs->partition_root_state,
-							  parent_prs, xcpus, NULL)) {
+							  parent_prs, tmp->delmask, NULL)) {
 				part_error = PERR_HKEEPING;
 				goto write_error;
 			}
-			rcu_read_lock();
-			cpuset_for_each_child(child, css, parent) {
-				if (child == cs)
-					continue;
-				if (!cpusets_are_exclusive(cs, child)) {
-					exclusive = false;
-					break;
+			if (cpumask_empty(cs->exclusive_cpus)) {
+				rcu_read_lock();
+				cpuset_for_each_child(child, css, parent) {
+					if (child == cs)
+						continue;
+					if (!cpusets_are_exclusive(cs, child)) {
+						exclusive = false;
+						break;
+					}
 				}
+				rcu_read_unlock();
 			}
-			rcu_read_unlock();
 			if (exclusive)
-				deleting = cpumask_and(tmp->delmask,
-						xcpus, parent->effective_cpus);
+				deleting = !cpumask_empty(tmp->delmask);
 			else
 				part_error = PERR_NOTEXCL;
 		}
+		/*
+		 * When both cs and parent remain valid, parent's
+		 * compute_partition_effective_cpumask() call would have removed
+		 * cs's effective_xcpus from the parent's effective_cpus. So
+		 * there is no need to adjust parent's effective_cpus here.
+		 */
 	}
 
 write_error:
tools/testing/selftests/cgroup/test_cpuset_prs.sh +11 -0
index ffa030cf1984d..7a077f4365072 100755
@@ -291,6 +291,8 @@ TEST_MATRIX=(
 								       A1:P0|A2:P2|A3:P1 2-4|2-3"
 	" C0-4:S+ C1-4:S+ C2-4     .    X2-4  X2-4:P2 X3-4:P1   .    0 A1:0-1|A2:2|A3:3-4 \
 								       A1:P0|A2:P2|A3:P1 2"
+	"C1-6:P2:S+ C3-6:P2:S+ C3-4:P2 .      .     C5-6     .      .    0 A1:1-4|A2:5-6|A3:5-6 \
+								       A1:P2|A2:P2|A3:P-2 1-6"
 	" C1-4:X2-4:S+ C2-4:X3-4:S+:P1 C3-4:X4:P2 \
 				   .      .      X5      .      .    0 A1:1-4|A2:2-4|A3:3-4 \
 								       A1:P0|A2:P-1|A3:P-2 ."
@@ -360,6 +362,10 @@ TEST_MATRIX=(
 	# cpuset.cpus is allowed, but those extra CPUs are ignored.
 	"C2-3:P1:S+ C3:P1   .      .      .     C2-4    .      .     0 A1:|A2:2-3 A1:P1|A2:P1"
 
+	# A child cannot recover until its exclusive CPUs are available again.
+	"CX1-4:P1:S+ CX3-4:P1 .     .     X1-2     .      .      .     0 A1:1-2|A2:1-2|XA2: A1:P1|A2:P-1"
+	"CX1-4:P1:S+ CX3-4:P1 .     .  X1-2:X1-4   .      .      .     0 A1:1-2|A2:3-4|XA2:3-4 A1:P1|A2:P1"
+
 	# Taking away all CPUs from parent or itself if there are tasks
 	# will make the partition invalid.
 	"C2-3:P1:S+  C3:P1  .      .      T     C2-3    .      .     0 A1:2-3|A2:2-3 A1:P1|A2:P-1"
@@ -419,6 +425,11 @@ TEST_MATRIX=(
 	" CX1-4:S+ CX2-4:P2 .    C5-6      .     .      .   P1:C3-6  0 A1:1|A2:2-4|B1:5-6 \
 								       A1:P0|A2:P2:B1:P-1 2-4"
 
+	# A middle isolated parent shrunk below coverage: the released CPUs of
+	# an invalidated child stay isolated as a higher ancestor still covers them.
+	"CX0-4:P2:S+ CX2-4:P2:S+ CX3-4:P2 .     .     X2     .      .     0 A1:0-1,3-4|A2:2|A3:2 \
+								       A1:P2|A2:P2|A3:P-2 0-4"
+
 	#  old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS
 	#  ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ --------
 	# Failure cases:
Signature · 1 line
2.53.0
author maintainer
#631 lore raw

PATCH 630/990 cgroup/cpuset: Minor fixes to prstate_housekeeping_conflict()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 40702b2ca8fa08fb64b926d8c72a4909d0330580 ]

Commit 9527ff78a413 ("cgroup/cpuset: Consider all the exclusive CPUs when doing housekeeping check") changes the way prstate_housekeeping_conflict() is being used by considering all the exclusive xcpus to be owned by the partition when doing housekeeping check. However there are two minor issues reported by sashiko with that patch:

1) In partition_cpus_change(), prstate_housekeeping_conflict() can be called with an invalid partition root. In that case, there are no isolated CPUs that are going to be returned back to the system to become housekeeping CPUs, so the calculation of the del_cpus cpumask is meaningless.

2) The checking of del_cpus in prstate_housekeeping_conflict() to see if it can contain an active housekeeping CPU that can be returned to the system ignores the fact that an active CPU not in HK_TYPE_DOMAIN_BOOT HK cpumask will not become an active housekeeping CPU when it is released by an isolated partition.

Update the existing code to handle these two issues properly to make prstate_housekeeping_conflict() produce more accurate result.

Fixes 9527ff78a413 ("cgroup/cpuset: Consider all the exclusive CPUs when doing housekeeping check")
[ sashal: Replaced upstream's housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT) with have_boot_isolcpus ? boot_hk_cpus : cpu_possible_mask, since that housekeeping type is missing here and boot_hk_cpus is only allocated with boot isolation. ]
---
 kernel/cgroup/cpuset.c | 45 +++++++++++++++++++++++++++++-------------
 1 file changed, 31 insertions(+), 14 deletions(-)
kernel/cgroup/cpuset.c +31 -14
index 7b13381755d07..d2bedfbd533de 100644
@@ -1520,6 +1520,9 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 	    !cpumask_subset(new_cpus, boot_hk_cpus))
 		return true;
 
+	if (del_cpus && cpumask_empty(del_cpus))
+		del_cpus = NULL;
+
 	/*
 	 * Exit 2nd check early and return false if
 	 * 1) there is no boot time isolated nohz_full CPU
@@ -1528,8 +1531,7 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 	 *    be returned back to the parent.
 	 */
 	if (!housekeeping_enabled(HK_TYPE_KERNEL_NOISE) ||
-	    (new_prs == parent_prs) ||
-	    ((new_prs == PRS_ROOT) && (!del_cpus || cpumask_empty(del_cpus))))
+	    (new_prs == parent_prs) || (!del_cpus && (new_prs == PRS_ROOT)))
 		return false;
 
 	/*
@@ -1540,20 +1542,29 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 	if (parent_prs == PRS_ISOLATED)
 		swap(new_cpus, del_cpus);
 
-	if (del_cpus &&
-	   (cpumask_first_and_and(del_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
-				   cpu_active_mask) < nr_cpu_ids))
-		return false;
-
 	if (!alloc_cpumask_var(&full_hk_cpus, GFP_KERNEL))
 		return true;
 
+	/*
+	 * Check if del_cpus may contain a CPU that can become an active
+	 * housekeeping CPU again.
+	 */
+	if (del_cpus) {
+		cpumask_and(full_hk_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
+			    have_boot_isolcpus ? boot_hk_cpus : cpu_possible_mask);
+		if (cpumask_first_and_and(del_cpus, full_hk_cpus,
+					  cpu_active_mask) < nr_cpu_ids) {
+			res = false;
+			goto out;
+		}
+	}
+
 	cpumask_and(full_hk_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
 		    housekeeping_cpumask(HK_TYPE_DOMAIN));
 	cpumask_andnot(full_hk_cpus, full_hk_cpus, isolated_cpus);
 	cpumask_and(full_hk_cpus, full_hk_cpus, cpu_active_mask);
 	res = !cpumask_weight_andnot(full_hk_cpus, new_cpus);
-
+out:
 	free_cpumask_var(full_hk_cpus);
 	return res;
 }
@@ -2628,23 +2639,29 @@ static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs,
 				  struct tmpmasks *tmp)
 {
 	enum prs_errcode prs_err;
+	int parent_prs = is_remote_partition(cs)
+		       ? PRS_ROOT : parent_cs(cs)->partition_root_state;
 
 	if (cs_is_member(cs))
 		return;
 
 	prs_err = validate_partition(cs, trialcs);
-	if (!prs_err && !cpumask_empty(trialcs->effective_xcpus)) {
+	if (!prs_err && (parent_prs > 0) &&
+	    !cpumask_empty(trialcs->effective_xcpus)) {
 		int prs = cs->partition_root_state;
-		int parent_prs = is_remote_partition(cs)
-			       ? PRS_ROOT : parent_cs(cs)->partition_root_state;
+
 		/*
 		 * Check for housekeeping conflict by passing the whole
 		 * effective_xcpus as well as those CPUs that are to be
 		 * removed from cs as delmask.
 		 */
-		cpumask_andnot(tmp->delmask, cs->effective_xcpus, trialcs->effective_xcpus);
-		if (parent_prs > 0 &&
-		    prstate_housekeeping_conflict(prs, parent_prs,
+		if (prs > 0)
+			cpumask_andnot(tmp->delmask, cs->effective_xcpus,
+				       trialcs->effective_xcpus);
+		else
+			cpumask_clear(tmp->delmask);
+
+		if (prstate_housekeeping_conflict(prs, parent_prs,
 						  trialcs->effective_xcpus, tmp->delmask))
 			prs_err = PERR_HKEEPING;
 	}
Signature · 1 line
2.53.0
author maintainer
#632 lore raw

PATCH 631/990 cgroup/cpuset: Prevent recursive call of remote_cpus_update() via update_cpumasks_hier()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 10a6f00d82544a1baa901de8d28f41f28c364995 ]

Guopeng reports that changing the cpumask of a remote partition root may set the effective_cpus of the top_cpuset incorrectly. It is due to the following call sequence:

update_cpumask()
-> partition_cpus_change()

    -> remote_cpus_update()
     -> update_sibling_cpumasks()
      -> update_cpumasks_hier()
       -> remote_cpus_update()

The second remote_cpus_update() call passes in the cs->effective_xcpus instead of the trialcs->effective_xcpus of the first remote_cpus_update() call. As a result, the second call can revert what has been done in the first call leading to incorrect effective_cpus of the top_cpuset as well as subpartitions_cpus.

Fix that by adding a new remote_partition_updating flag into the cpuset structure to indicate that a remote partition is being updated and update_cpumasks_hier() should skip the whole subtree as update_cpumask() or update_exclusive_cpumask() which calls partition_cpus_change() will eventually calls update_cpumasks_hier() for that subtree anyway.

This new flag is currently set only in remote_cpus_update() to prevent recursive call of remote_cpus_update() on the same cpuset.

A test case is added to test_cpuset_prs.sh to verify this change.

Fixes f62a5d39368e ("cgroup/cpuset: Remove remote_partition_check() & make update_cpumasks_hier() handle remote partition")
[ sashal: adjusted struct field placement because remote_partition bool is missing, and added :S+ to the new selftest row to match this tree's row format. ]
---
 kernel/cgroup/cpuset-internal.h                   |  5 +++++
 kernel/cgroup/cpuset.c                            | 13 +++++++++----
 tools/testing/selftests/cgroup/test_cpuset_prs.sh |  1 +
 3 files changed, 15 insertions(+), 4 deletions(-)
kernel/cgroup/cpuset-internal.h +5 -0
index 0eb9ebd4fcb92..89acf907e7354 100644
@@ -161,6 +161,11 @@ struct cpuset {
 	/* partition root state */
 	int partition_root_state;
 
+	/*
+	 * Set to true when a remote partition is undergoing update.
+	 */
+	bool remote_partition_updating;
+
 	/*
 	 * number of SCHED_DEADLINE tasks attached to this cpuset, so that we
 	 * know when to rebuild associated root domain bandwidth information.
kernel/cgroup/cpuset.c +9 -4
index d2bedfbd533de..b63489f9d3765 100644
@@ -1833,6 +1833,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 			goto invalidate;
 	}
 
+	cs->remote_partition_updating = true;
 	spin_lock_irq(&callback_lock);
 	if (adding)
 		isolcpus_updated += partition_xcpus_add(prs, NULL, tmp->addmask);
@@ -1855,6 +1856,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 	 */
 	cpuset_update_tasks_cpumask(&top_cpuset, tmp->new_cpus);
 	update_sibling_cpumasks(&top_cpuset, NULL, tmp);
+	cs->remote_partition_updating = false;
 	return;
 
 invalidate:
@@ -2323,16 +2325,19 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 		old_prs = new_prs = cp->partition_root_state;
 
 		/*
-		 * For child remote partition root (!= cs), we need to call
-		 * remote_cpus_update() if effective_xcpus will be changed.
-		 * Otherwise, we can skip the whole subtree.
+		 * For a child remote partition with remote_partition_updating
+		 * set, we can skip the whole subtree as the this function will
+		 * be called eventually. We can also skip the subtree if the
+		 * effective_xcpus isn't going to be changed. Otherwise, we
+		 * will have to call remote_cpus_update().
 		 *
 		 * remote_cpus_update() will reuse tmp->new_cpus only after
 		 * its value is being processed.
 		 */
 		if (remote && (cp != cs)) {
 			compute_excpus(cp, tmp->new_cpus);
-			if (cpumask_equal(cp->effective_xcpus, tmp->new_cpus)) {
+			if (cp->remote_partition_updating ||
+			    cpumask_equal(cp->effective_xcpus, tmp->new_cpus)) {
 				pos_css = css_rightmost_descendant(pos_css);
 				continue;
 			}
tools/testing/selftests/cgroup/test_cpuset_prs.sh +1 -0
index 7a077f4365072..bd06324af3843 100755
@@ -277,6 +277,7 @@ TEST_MATRIX=(
 	" C0-3:S+ C1-3:S+ C2-3    C4    X2-3   X2-3  X2-3:P2 P2:C4-5 0 A3:2-3|B1:4-5 A3:P2|B1:P2 2-5"
 	" C4:X0-3:S+ X1-3:S+ X2-3  .      .      P2     .      .     0 A1:4|A2:1-3|A3:1-3 A2:P2 1-3"
 	" C4:X0-3:S+ X1-3:S+ X2-3  .      .      .      P2     .     0 A1:4|A2:4|A3:2-3 A3:P2 2-3"
+	" CX1-6:S+ C1-4:P1 .    C4-5     .    C1-3     .      .     0 A1:4-6|A2:1-3|B1:4-5 A2:P1"
 
 	# Nested remote/local partition tests
 	" C0-3:S+ C1-3:S+ C2-3   C4-5   X2-3  X2-3:P1   P2     P1    0 A1:0-1|A2:|A3:2-3|B1:4-5 \
Signature · 1 line
2.53.0
author maintainer
#633 lore raw

PATCH 632/990 cgroup/cpuset: Release invalid isolated CPUs in compute_partition_effective_cpumask()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit a7d89d92fdfbceb678d82710135d4eee2623d727 ]

It is found by sashiko that when a child isolated partition with parent root partition is invalidated in compute_partition_effective_cpumask(), the switching of the isolated exclusive CPUs from child to parent will not be reflected in isolated_cpus leading to CPU leakage. Fix that by calling isolated_cpus_update() when that happens.

Also simplify compute_partition_effective_cpumask() by doing child partition invalidation only for the special case of no more effective_cpus left in a populated parent. The other case doesn't actually warrant invalidation at this stage and subsequent iteration in update_cpumasks_hier() and update_parent_effective_cpumask() for that child should handle that.

Also drop the make_partition_invalid() helper by inlining it into compute_partition_effective_cpumask() as it is the only caller.

A new test case is add to test_cpuset_prs.sh to verify this.

Fixes 11e5f407b64a ("cgroup/cpuset: Keep track of CPUs in isolated partitions")
[ sashal: Kept the existing nr_subparts decrement and reset lines in the context, and added the explicit ":S+" to the new selftest row to match this tree's test-matrix syntax. ]
---
 kernel/cgroup/cpuset.c                        | 46 +++++++------------
 .../selftests/cgroup/test_cpuset_prs.sh       |  4 ++
 2 files changed, 21 insertions(+), 29 deletions(-)
kernel/cgroup/cpuset.c +17 -29
index b63489f9d3765..084cee4e789d5 100644
@@ -170,15 +170,6 @@ static inline bool cs_is_member(const struct cpuset *cs)
 	return cs->partition_root_state == PRS_MEMBER;
 }
 
-/*
- * Callers should hold callback_lock to modify partition_root_state.
- */
-static inline void make_partition_invalid(struct cpuset *cs)
-{
-	if (cs->partition_root_state > 0)
-		cs->partition_root_state = -cs->partition_root_state;
-}
-
 /*
  * Send notification event of whenever partition_root_state changes.
  */
@@ -2234,8 +2225,6 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
  * or update_cpumasks_hier() where parent and children are modified
  * successively, we don't need to call update_parent_effective_cpumask()
  * and the child's effective_cpus will be updated in later iterations.
- *
- * Note that rcu_read_lock() is assumed to be held.
  */
 static void compute_partition_effective_cpumask(struct cpuset *cs,
 						struct cpumask *new_ecpus)
@@ -2247,15 +2236,16 @@ static void compute_partition_effective_cpumask(struct cpuset *cs,
 	WARN_ON_ONCE(!is_partition_valid(cs));
 
 	/*
-	 * Check child partition roots to see if they should be
-	 * invalidated when
-	 *  1) child effective_xcpus not a subset of new
-	 *     excluisve_cpus
-	 *  2) All the effective_cpus will be used up and cp
-	 *     has tasks
+	 * Check child partition roots to see if they should be invalidated
+	 * when all the effective_cpus will be used up and cs is populated.
+	 * It is better to sacrifice a child partition root than invalidating
+	 * the whole subtree.
+	 *
+	 * Return early if the effective_cpus is already empty.
 	 */
 	compute_excpus(cs, new_ecpus);
-	cpumask_and(new_ecpus, new_ecpus, cpu_active_mask);
+	if (!cpumask_and(new_ecpus, new_ecpus, cpu_active_mask))
+		return;
 
 	rcu_read_lock();
 	cpuset_for_each_child(child, css, cs) {
@@ -2267,22 +2257,20 @@ static void compute_partition_effective_cpumask(struct cpuset *cs,
 		 * partition root.
 		 */
 		WARN_ON_ONCE(is_remote_partition(child));
-		WRITE_ONCE(child->prs_err, 0);
-		if (!cpumask_subset(child->effective_xcpus,
-				    cs->effective_xcpus))
-			WRITE_ONCE(child->prs_err, PERR_INVCPUS);
-		else if (populated &&
-			 cpumask_subset(new_ecpus, child->effective_xcpus))
-			WRITE_ONCE(child->prs_err, PERR_NOCPUS);
-
-		if (child->prs_err) {
+		if (populated && cpumask_subset(new_ecpus, child->effective_xcpus)) {
 			int old_prs = child->partition_root_state;
+			int parent_prs = cs->partition_root_state;
 
 			/*
-			 * Invalidate child partition
+			 * Invalidate child partition and update isolated_cpus
+			 * if necessary.
 			 */
 			spin_lock_irq(&callback_lock);
-			make_partition_invalid(child);
+			WRITE_ONCE(child->prs_err, PERR_NOCPUS);
+			if ((old_prs == PRS_ISOLATED) && (parent_prs == PRS_ROOT))
+				isolated_cpus_update(PRS_ISOLATED, PRS_ROOT,
+						     child->effective_xcpus);
+			child->partition_root_state = -old_prs;
 			cs->nr_subparts--;
 			child->nr_subparts = 0;
 			spin_unlock_irq(&callback_lock);
tools/testing/selftests/cgroup/test_cpuset_prs.sh +4 -0
index bd06324af3843..9a1590e630e6b 100755
@@ -431,6 +431,10 @@ TEST_MATRIX=(
 	"CX0-4:P2:S+ CX2-4:P2:S+ CX3-4:P2 .     .     X2     .      .     0 A1:0-1,3-4|A2:2|A3:2 \
 								       A1:P2|A2:P2|A3:P-2 0-4"
 
+	# When an isolated partition child with root partition parent is invalidated,
+	# its effective xcpus will be removed from isolated_cpus.
+	"C1-4:P1:S+ C3-4:P2 .      .    T:C3-4   .      .      .     0 A1:3-4|A2:3-4 A1:P1|A2:P-2 ."
+
 	#  old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS
 	#  ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ --------
 	# Failure cases:
Signature · 1 line
2.53.0
author maintainer
#634 lore raw

PATCH 633/990 cgroup/cpuset: Release invalid isolated CPUs with a shrunk root partition parent

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit ec0254b9eb49ebc9383dc3ae5cb69c8606f88499 ]

It is also reported by sashiko that there may be leakages of isolated CPUs when a root partition parent shrinks its effective_xcpus with isolated partition children. Leakage here means that isolated_cpus may contain extra CPUs that are not in any isolated partitions and not boot time isolated. Those CPUs cannot be used in any isolated partitions anymore.

There are 2 different cases here. The effective_xcpus becomes empty and the isolated partition should be invalidated in this case. Alternatively some of its effective_xcpus are not in parent's effective xcpus but still have some valid effective_xcpus left. The isolated partition can remain valid. In both cases, the invalid isolated CPUs will have to be released from isolated_cpus if appropriate.

Fix that by calling isolated_cpus_release() to release those isolated CPUs from isolated_cpus.

New test cases are added to test_cpuset_prs.sh to test this.

Fixes 11e5f407b64a ("cgroup/cpuset: Keep track of CPUs in isolated partitions")
[ sashal: Test-matrix rows use this tree's explicit :S+ syntax, and a stray # comment line was added by conflict resolution; the cpuset.c change itself matches upstream apart from line offsets. ]
---
 kernel/cgroup/cpuset.c                           | 16 +++++++++++++++-
 .../testing/selftests/cgroup/test_cpuset_prs.sh  |  7 +++++++
 2 files changed, 22 insertions(+), 1 deletion(-)
kernel/cgroup/cpuset.c +15 -1
index 084cee4e789d5..91a3fa0cf801a 100644
@@ -2072,8 +2072,22 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		 *
 		 * A partition error happens when parent has tasks and all
 		 * its effective CPUs will have to be distributed out.
+		 *
+		 * For an isolated partition with a shrunk root partition parent
+		 * we may need to return some or all of its isolated CPUs.
 		 */
-		if (nocpu || cpumask_empty(tmp->delmask)) {
+		nocpu |= cpumask_empty(tmp->delmask);
+		if ((parent_prs == PRS_ROOT) && (old_prs == PRS_ISOLATED)) {
+			cpumask_clear(tmp->addmask);
+			if (nocpu)
+				cpumask_copy(tmp->addmask, cs->effective_xcpus);
+			else if (!cpumask_subset(cs->effective_xcpus, parent->effective_xcpus))
+				cpumask_andnot(tmp->addmask, cs->effective_xcpus,
+							     parent->effective_xcpus);
+			if (!cpumask_empty(tmp->addmask))
+				isolated_cpus_release(cs, tmp->addmask);
+		}
+		if (nocpu) {
 			part_error = PERR_NOCPUS;
 			if (is_partition_valid(cs))
 				adding = cpumask_and(tmp->addmask,
tools/testing/selftests/cgroup/test_cpuset_prs.sh +7 -0
index 9a1590e630e6b..25eef20c17466 100755
@@ -435,6 +435,13 @@ TEST_MATRIX=(
 	# its effective xcpus will be removed from isolated_cpus.
 	"C1-4:P1:S+ C3-4:P2 .      .    T:C3-4   .      .      .     0 A1:3-4|A2:3-4 A1:P1|A2:P-2 ."
 
+	# When a root partition parent with an isolated partition child is shrunk
+	# so that its effective xcpus is no longer a superset of its child effective
+	# xcpus, the invalid isolated CPUs should be removed from cpuset.cpus.isolated.
+	"C1-4:P1:S+ C3-4:P2 .      .    T:C4-6   .      .      .     0 A1:5-6|A2:4 A1:P1|A2:P2 4"
+	"C1-4:P1:S+ C1-2:P2 .      .    T:C4-6   .      .      .     0 A1:4-6|A2:4-6 A1:P1|A2:P-2 ."
+
+	#
 	#  old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS
 	#  ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ --------
 	# Failure cases:
Signature · 1 line
2.53.0
author maintainer
#635 lore raw

PATCH 634/990 ksmbd: use the resolved share path for the share root

In reply to Greg Kroah-Hartman

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

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

From: Denis Kulikov <[email protected]>

[ Upstream commit 03b47bdc9ac8e9dacbf1d66a1dfc54b328e283f2 ]

If the share path is a mount point and crossmnt is not set (crossmnt = no, or ksmbd-tools that predate the option), the share root looks empty to
clients: QUERY_DIRECTORY on it returns only "." and "..". Files created in the root go to the mounted filesystem, but a directory query cannot find them afterwards, so e.g. "rm" of a file that was just uploaded fails with STATUS_NO_SUCH_FILE.

An empty name refers to the share root. For it, ksmbd_vfs_path_lookup() looks up share_conf->path again starting from its parent, and the mount on the last component is not followed, which gives the directory covered by the mount. All other names are looked up relative to share_conf->vfs_path, which was resolved through the mount when the share was set up.

share_conf->vfs_path already refers to the share root, so return a reference to it instead of looking the path up again.

Fixes 74d7970febf7 ("ksmbd: fix racy issue from using ->d_parent and ->d_name")
[ sashal: Adapted the context to this branch's older ksmbd_vfs_path_lookup(), keeping do_lock and the getname_kernel() filename handling instead of for_remove and CLASS(filename_kernel). ]
---
 fs/smb/server/vfs.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
fs/smb/server/vfs.c +5 -4
index a3db77b3c2728..466a0853dc486 100644
@@ -82,12 +82,13 @@ static int ksmbd_vfs_path_lookup(struct ksmbd_share_config *share_conf,
 		if (do_lock)
 			return -EINVAL;
 
-		pathname = share_conf->path;
-		root_share_path = NULL;
-	} else {
-		flags |= LOOKUP_BENEATH;
+		*path = share_conf->vfs_path;
+		path_get(path);
+		return 0;
 	}
 
+	flags |= LOOKUP_BENEATH;
+
 	filename = getname_kernel(pathname);
 	if (IS_ERR(filename))
 		return PTR_ERR(filename);
Signature · 1 line
2.53.0
author maintainer
#636 lore raw

PATCH 635/990 sched_ext: Reject rq-lock-taking kfuncs in tracing programs

In reply to Greg Kroah-Hartman

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

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

From: Junbin Zhang <[email protected]>

[ Upstream commit b07a7450f6ef98c79ebd450a92fc4bb6b8f1e02e ]

scx_bpf_cpuperf_set() and scx_bpf_cidperf_set() are members of scx_kfunc_ids_any, which is registered for BPF_PROG_TYPE_TRACING. A tracing program can run in a context which already holds the target rq lock, in which case scx_cpuperf_set() attempts to acquire the same lock again:

  __schedule()
    rq_lock(rq);                          /* rq->__lock is held */
    trace_sched_switch();
      BPF tracing program
        scx_bpf_cpuperf_set(smp_processor_id(), 1024);
          scx_cpuperf_set();
            locked_rq = scx_locked_rq(); /* NULL */
            rq_lock_irqsave(rq, &rf);    /* same lock */

scx_locked_rq() only tracks rq locks held during SCX callback invocations, so it cannot detect an rq lock held by the surrounding kernel code.

The deadlock can be reproduced with two BPF programs. The first is a minimal SCX scheduler, which only needs to be registered and enabled:

  SEC(".struct_ops.link")
  struct sched_ext_ops minimal_ops = {
          .name = "minimal",
  };

The second is a tracing program attached to tp_btf/sched_switch, which fires from __schedule() with rq->__lock already held:

  SEC("tp_btf/sched_switch")
  int BPF_PROG(on_sched_switch, bool preempt, struct task_struct *prev,
               struct task_struct *next, unsigned int prev_state)
  {
          scx_bpf_cpuperf_set(bpf_get_smp_processor_id(), 1024);
          return 0;
  }

With both programs attached, the next context switch on any CPU deadlocks that CPU. Lockdep reports:

WARNING: possible recursive locking detected
7.3.0-rc7 #3 Not tainted
swapper/3/0 is trying to acquire lock:
(&rq->__lock){-.-.}-{2:2}, at: raw_spin_rq_lock_nested+0x1e/0x30

but task is already holding lock:
(&rq->__lock){-.-.}-{2:2}, at: __schedule+0xeb/0x1430

   Possible unsafe locking scenario:
         CPU0
         ----
    lock(&rq->__lock);
    lock(&rq->__lock);

    *** DEADLOCK ***
  Call Trace:
   <TASK>
   print_deadlock_bug.cold+0xc0/0xd0
   __lock_acquire+0x12fa/0x1b80
   lock_acquire+0xd1/0x2f0
   _raw_spin_lock_nested+0x32/0x40
   raw_spin_rq_lock_nested+0x1e/0x30
   scx_cpuperf_set+0x1e9/0x310
   scx_bpf_cpuperf_set+0x9b/0x230
   bpf_prog_..._on_sched_switch+0x3d/0x41
   bpf_trace_run4+0x125/0x450
   __traceiter_sched_switch+0x4b/0x70
   __schedule+0x94a/0x1430
   schedule_idle+0x26/0x50
   cpu_startup_entry+0x2d/0x30
   start_secondary+0xfc/0x100
   </TASK>

The CPU remains locked up with interrupts disabled. scx_bpf_cidperf_set() is similarly affected, as it resolves the CID through scx_cid_to_cpu() before reaching the same rq-locking path.

There is no reliable way for these kfuncs to determine whether the surrounding tracing context already holds an rq lock. Reject calls to both kfuncs from tracing programs at verification time, while preserving their availability to SCX struct_ops and syscall programs.

Fixes a11d6784d731 ("sched_ext: Fix missing rq lock in scx_bpf_cpuperf_set()")
[ sashal: Replaced the tracing-visible scx_kfunc_context_filter() check with a separate BTF kfunc set for scx_bpf_cpuperf_set(), registered only for struct_ops and syscall programs, and dropped the cid variant. ]
---
 kernel/sched/ext.c | 24 +++++++++++++++++++++++-
 1 file changed, 23 insertions(+), 1 deletion(-)
kernel/sched/ext.c +23 -1
index af5828f093045..b3a6d60709403 100644
@@ -7013,7 +7013,6 @@ BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_TRUSTED_ARGS)
 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_TRUSTED_ARGS)
 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap)
 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur)
-BTF_ID_FLAGS(func, scx_bpf_cpuperf_set)
 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
@@ -7036,6 +7035,25 @@ static const struct btf_kfunc_id_set scx_kfunc_set_any = {
 	.set			= &scx_kfunc_ids_any,
 };
 
+/*
+ * Kfuncs which may take the rq lock on their unlocked path.
+ *
+ * A tracing program can execute in any kernel context, including ones which
+ * already hold the rq lock (e.g. sched_switch). scx_locked_rq() only tracks
+ * rq locks taken for SCX callbacks, so from such a context it returns NULL
+ * and these kfuncs would acquire the already held rq lock again and deadlock
+ * the CPU. They cannot be made safe for tracing programs, so keep them off
+ * the tracing hook.
+ */
+BTF_KFUNCS_START(scx_kfunc_ids_no_tracing)
+BTF_ID_FLAGS(func, scx_bpf_cpuperf_set)
+BTF_KFUNCS_END(scx_kfunc_ids_no_tracing)
+
+static const struct btf_kfunc_id_set scx_kfunc_set_no_tracing = {
+	.owner			= THIS_MODULE,
+	.set			= &scx_kfunc_ids_no_tracing,
+};
+
 static int __init scx_init(void)
 {
 	int ret;
@@ -7065,6 +7083,10 @@ static int __init scx_init(void)
 					     &scx_kfunc_set_any)) ||
 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
 					     &scx_kfunc_set_any)) ||
+	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
+					     &scx_kfunc_set_no_tracing)) ||
+	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
+					     &scx_kfunc_set_no_tracing)) ||
 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
 					     &scx_kfunc_set_any))) {
 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
Signature · 1 line
2.53.0
author maintainer
#637 lore raw

PATCH 636/990 net-sysfs: reject a one-entry RPS flow table

In reply to Greg Kroah-Hartman

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

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

From: Dudu Lu <[email protected]>

[ Upstream commit 24927bdf0f62f63470a065c21d80fff7e4e9f207 ]

store_rps_dev_flow_table_cnt() accepts rps_flow_cnt == 1. For count == 1 the round-up loop leaves mask == 0, which is stored as log == 0 in the tag (tag_ptr |= ilog2(mask) + 1). get_rps_cpu() then calls rfs_slot() -> hash_32(hash, rps_tag_to_log(tag_ptr)) with log == 0:

include/linux/hash.h:68

	return __hash_32(val) >> (32 - bits);   /* bits == 0 -> shift by 32 */

The shift by 32 is undefined and yields the full 32-bit hash, which is used to index the one-entry rps_dev_flow[] table unchecked:

  UBSAN: shift-out-of-bounds in ./include/linux/hash.h:68:24
  shift exponent 32 is too large for 32-bit type 'unsigned int'
   __ubsan_handle_shift_out_of_bounds+0x11c/0x208
   get_rps_cpu+0x12fc/0x1344
   netif_rx_internal+0x1e0/0x4d4

rps_dev_flow[] is then read (rflow->cpu) and written (last_qtail) out of bounds on the packet path. Require at least two entries.

Fixes f3483c8e1da6 ("net: rfs: hash function change")
[ sashal: Context lines adapted to the older overflow checks and vmalloc code; the added if (!mask) return -EINVAL; block is otherwise identical to upstream. ]
---
 net/core/net-sysfs.c | 8 ++++++++
 1 file changed, 8 insertions(+)
net/core/net-sysfs.c +8 -0
index 3a3a92f3a314c..e408f0b6786b7 100644
@@ -1101,6 +1101,14 @@ static ssize_t store_rps_dev_flow_table_cnt(struct netdev_rx_queue *queue,
 		 */
 		while ((mask | (mask >> 1)) != mask)
 			mask |= (mask >> 1);
+
+		/* Require at least two entries. A one-entry table rounds up
+		 * to mask == 0, which encodes log == 0 in the tag.
+		 * get_rps_cpu() then computes hash_32(hash, 0), a shift by 32.
+		 */
+		if (!mask)
+			return -EINVAL;
+
 		/* On 64 bit arches, must check mask fits in table->mask (u32),
 		 * and on 32bit arches, must check
 		 * RPS_DEV_FLOW_TABLE_SIZE(mask + 1) doesn't overflow.
Signature · 1 line
2.53.0