[PATCH v3 1/2] livepatch: Protect the per-CPU stack buffer in klp_check_stack()

From: Yafang Shao

Date: Thu Nov 26 2026 - 02:28:59 EST


klp_check_stack() stores the unwound stack into a per-CPU buffer and
requires preemption to be disabled. It currently relies on the caller for
that. However, on PREEMPT_RT even read_lock(&tasklist_lock) is a sleeping
lock. Therefore, we must disable preempt explicitly in klp_check_stack().

Reported-by: sashiko-bot <sashiko-bot@xxxxxxxxxx>
Closes: https://lore.kernel.org/live-patching/sashiko-outbox-228569@xxxxxxxxxx/
Signed-off-by: Yafang Shao <laoar.shao@xxxxxxxxx>
---
kernel/livepatch/transition.c | 30 ++++++++++++++++++++++--------
1 file changed, 22 insertions(+), 8 deletions(-)

diff --git a/kernel/livepatch/transition.c b/kernel/livepatch/transition.c
index 2351a19ac2a9..4739fc170f48 100644
--- a/kernel/livepatch/transition.c
+++ b/kernel/livepatch/transition.c
@@ -253,17 +253,27 @@ static int klp_check_stack_func(struct klp_func *func, unsigned long *entries,
*/
static int klp_check_stack(struct task_struct *task, const char **oldname)
{
- unsigned long *entries = this_cpu_ptr(klp_stack_entries);
+ unsigned long *entries;
struct klp_object *obj;
struct klp_func *func;
- int ret, nr_entries;
+ int nr_entries;
+ int ret = 0;

- /* Protect 'klp_stack_entries' */
- lockdep_assert_preemption_disabled();
+ /*
+ * The unwound stack is stored in a per-CPU buffer, so preemption
+ * must be disabled. Do not rely on the callers for that: on
+ * PREEMPT_RT even read_lock(&tasklist_lock) is a sleeping lock.
+ * When called via task_call_func(), this is nested inside its
+ * raw spinlock and is a no-op.
+ */
+ preempt_disable();
+ entries = this_cpu_ptr(klp_stack_entries);

ret = stack_trace_save_tsk_reliable(task, entries, MAX_STACK_ENTRIES);
- if (ret < 0)
- return -EINVAL;
+ if (ret < 0) {
+ ret = -EINVAL;
+ goto out;
+ }
nr_entries = ret;

klp_for_each_object(klp_transition_patch, obj) {
@@ -273,12 +283,16 @@ static int klp_check_stack(struct task_struct *task, const char **oldname)
ret = klp_check_stack_func(func, entries, nr_entries);
if (ret) {
*oldname = func->old_name;
- return -EADDRINUSE;
+ ret = -EADDRINUSE;
+ goto out;
}
}
}

- return 0;
+ ret = 0;
+out:
+ preempt_enable();
+ return ret;
}

static int klp_check_and_switch_task(struct task_struct *task, void *arg)
--
2.52.0