mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH v4 0/3] livepatch: Do not lose exiting tasks during a transition
@ 2026-11-26 16:41 Binoy Ravindran via B4 Relay
  2026-11-26 16:41 ` [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists Binoy Ravindran via B4 Relay
                   ` (2 more replies)
  0 siblings, 3 replies; 14+ messages in thread
From: Binoy Ravindran via B4 Relay @ 2026-11-26 16:41 UTC (permalink / raw)
  To: Paul E. McKenney, Frederic Weisbecker, Neeraj Upadhyay,
	Joel Fernandes, Josh Triplett, Boqun Feng, Uladzislau Rezki,
	Steven Rostedt, Mathieu Desnoyers, Lai Jiangshan, Zqiang,
	Josh Poimboeuf, Miroslav Benes, Petr Mladek, Joe Lawrence,
	Song Liu, Ingo Molnar, Jiri Kosina
  Cc: rcu, linux-kernel, live-patching, Yafang Shao, Jaidev Shastri,
	Binoy Ravindran

After exit_notify(), a self-reaping task is unhashed from the task list
but keeps running the rest of do_exit(). The livepatch transition walks
the task list, so it can complete while such a task still runs code from
a patch module that atomic replace is about to free. Yafang Shao and
Petr Mladek discussed this race in [1], and Josh Poimboeuf suggested a
similar approach in [2]. The race is hard to hit, but any livepatch that
replaces a function on the exit path can reach it, for example a fix to
do_exit() itself.

Every exiting task is on an RCU-tasks exit list from
exit_tasks_rcu_start(), before exit_notify(), until
exit_tasks_rcu_finish(). Patch 1 adds helpers to visit the tasks on
these lists. Patch 2 makes every transition step, including reverse and
force, visit them too. After exit_tasks_rcu_finish(), do_exit() runs
with preemption disabled until the task's final switch. Patch 2 waits
that stretch out with klp_synchronize_transition() before
func->transition is set and before the transition completes. The exit
path itself is unchanged. Patch 3, suggested by Yafang, makes LIVEPATCH
select TASKS_RCU, which every livepatch kernel already builds, so that
the exit lists are always there.

Tested on v7.4-rc2, x86-64, under QEMU/KVM, with two klp-build
livepatches that each replace do_exit() and replace each other ten times
per run, and a debug-only 2 s sleep after exit_notify(). Without the
series, 9 of 12 runs crashed; with it, all 12 completed their 120
replace cycles. With lockdep, PROVE_RCU and DEBUG_ATOMIC_SLEEP enabled,
the series ran 180 replace cycles, 120 of them with the sleep, with no
reports. Without the sleep, 20,000 replace cycles with the series, in
both the default and preempt=full modes, completed without a fault.
Transition times matched v7.4-rc2 alone: medians of 7 ms (default) and
11 ms (preempt=full) against 8 ms, and 90th and 99th percentiles of
about 1.6 s and 1.8 s in both. Each commit builds without new warnings
with and without CONFIG_LIVEPATCH. A reproducer and the logs are
available on request.

checkpatch.pl in v7.4-rc2 reports the Assisted-by: trailer as
non-standard. The trailer follows
Documentation/process/coding-assistants.rst.

[1] https://lore.kernel.org/all/20250127063526.76687-1-laoar.shao@gmail.com/
[2] https://lore.kernel.org/live-patching/20250124010848.pdcxokfsk2ngrowl@jpoimboe/

---
Changes in v4:
- Wait out the do_exit() tail with klp_synchronize_transition() again,
  as in v2. synchronize_rcu() can return while the dying task still runs
  traceable code in __schedule(), because the quiescent state is
  reported before switch_to() (Sashiko). This also restores the v2
  transition times.
- Keep klp_try_switch_exiting_tasks() from v3 (Yafang Shao).
- Link to v3: https://patch.msgid.link/20261125-klp-series-v3-v3-0-b1e0f79af331@vt.edu

Changes in v3:
- Wait out the do_exit() tail with synchronize_rcu() instead of
  klp_synchronize_transition(), as rcu_tasks_postgp() does
  (Yafang Shao). With preempt=full this raises the median transition
  time in our test from 8 ms to 0.8 s; the 90th and 99th
  percentiles stay about the same. See the test notes above.
- Replace the callback-based snapshot walk, which had a single user,
  with klp_try_switch_exiting_tasks() (Yafang Shao).
- Link to v2: https://patch.msgid.link/20261124-klp-series-v3-v2-0-50d20829a337@vt.edu

Changes in v2:
- Walk the exit lists under tasklist_lock and skip tasks that are
  still hashed, so that each task is visited exactly once (Sashiko).
- Call klp_synchronize_transition() after initializing the transition,
  before func->transition is set, and before completing it, to wait
  out tasks past exit_tasks_rcu_finish() (Sashiko).
- Document rtp_exit_cursor in the kernel-doc comment (Sashiko).
- Add patch 3, which makes LIVEPATCH select TASKS_RCU (Yafang Shao).
- Test on v7.4-rc2 instead of v6.12.1, including lockdep and
  natural-timing runs.
- Link to v1: https://patch.msgid.link/20261123-klp-series-v3-v1-0-427c95811d9b@vt.edu

To: "Paul E. McKenney" <paulmck@kernel.org>
To: Frederic Weisbecker <frederic@kernel.org>
To: Neeraj Upadhyay <neeraj.upadhyay@kernel.org>
To: Joel Fernandes <joelagnelf@nvidia.com>
To: Josh Triplett <josh@joshtriplett.org>
To: Boqun Feng <boqun@kernel.org>
To: Uladzislau Rezki <urezki@gmail.com>
To: Steven Rostedt <rostedt@goodmis.org>
To: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
To: Lai Jiangshan <jiangshanlai@gmail.com>
To: Zqiang <qiang.zhang@linux.dev>
To: Josh Poimboeuf <jpoimboe@kernel.org>
To: Miroslav Benes <mbenes@suse.cz>
To: Petr Mladek <pmladek@suse.com>
To: Joe Lawrence <joe.lawrence@redhat.com>
To: Song Liu <song@kernel.org>
To: Ingo Molnar <mingo@kernel.org>
To: Jiri Kosina <jikos@kernel.org>
Cc: rcu@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Cc: live-patching@vger.kernel.org
Cc: Yafang Shao <laoar.shao@gmail.com>
Cc: Jaidev Shastri <jaidevshastri@vt.edu>

---
Binoy Ravindran (3):
      rcu-tasks: Add helpers to visit tasks on the exit lists
      livepatch: Include exiting tasks in the transition
      livepatch: Select TASKS_RCU

 include/linux/rcupdate.h      |   9 ++++
 kernel/livepatch/Kconfig      |   1 +
 kernel/livepatch/transition.c | 102 ++++++++++++++++++++++++++++++++++++++++++
 kernel/rcu/tasks.h            |  69 +++++++++++++++++++++++++---
 4 files changed, 175 insertions(+), 6 deletions(-)
---
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
change-id: 20261123-klp-series-v3-d52796c0590f

Best regards,
--  
Binoy Ravindran <binoy@vt.edu>



^ permalink raw reply	[flat|nested] 14+ messages in thread

* [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists
  2026-11-26 16:41 [PATCH v4 0/3] livepatch: Do not lose exiting tasks during a transition Binoy Ravindran via B4 Relay
@ 2026-11-26 16:41 ` Binoy Ravindran via B4 Relay
  2026-11-26 18:52   ` Petr Mladek
  2026-11-30 17:42   ` Paul E. McKenney
  2026-11-26 16:41 ` [PATCH v4 2/3] livepatch: Include exiting tasks in the transition Binoy Ravindran via B4 Relay
  2026-11-26 16:41 ` [PATCH v4 3/3] livepatch: Select TASKS_RCU Binoy Ravindran via B4 Relay
  2 siblings, 2 replies; 14+ messages in thread
From: Binoy Ravindran via B4 Relay @ 2026-11-26 16:41 UTC (permalink / raw)
  To: Paul E. McKenney, Frederic Weisbecker, Neeraj Upadhyay,
	Joel Fernandes, Josh Triplett, Boqun Feng, Uladzislau Rezki,
	Steven Rostedt, Mathieu Desnoyers, Lai Jiangshan, Zqiang,
	Josh Poimboeuf, Miroslav Benes, Petr Mladek, Joe Lawrence,
	Song Liu, Ingo Molnar, Jiri Kosina
  Cc: rcu, linux-kernel, live-patching, Yafang Shao, Jaidev Shastri,
	Binoy Ravindran

From: Binoy Ravindran <binoy@vt.edu>

A task joins its CPU's RCU-tasks exit list in exit_tasks_rcu_start(),
before exit_notify() unhashes it from the task list, and leaves it in
exit_tasks_rcu_finish(), after do_exit() has disabled preemption for the
final switch. Once exit_notify() has unhashed it, the task is no longer
found by for_each_process_thread(), but it still runs do_exit() and may
sleep there. Code that must reach every task that can still be
descheduled, such as the livepatch transition, has no way to find it.

Add two helpers. rcu_tasks_visit_exiting() calls a function on each
task on the exit lists under the list locks, without allocating.
rcu_tasks_snapshot_exiting() copies the tasks into a caller-supplied
array with a reference held on each, for callers that must sleep or take
other locks while examining them. Without CONFIG_TASKS_RCU there are no
exit lists, and the helpers do nothing.

rcu_tasks_postscan() keeps its place in an exit list with a bare
list_head while it drops the lock to reschedule, relying on nobody else
traversing the list. Move that cursor into struct rcu_tasks_percpu,
next to the list it marks, so that the new helpers can recognize and
skip it. Only the grace-period kthread runs postscan, one CPU's list at
a time, so one cursor per CPU suffices.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Binoy Ravindran <binoy@vt.edu>
---
 include/linux/rcupdate.h |  9 +++++++
 kernel/rcu/tasks.h       | 69 +++++++++++++++++++++++++++++++++++++++++++-----
 2 files changed, 72 insertions(+), 6 deletions(-)

diff --git a/include/linux/rcupdate.h b/include/linux/rcupdate.h
index 3f74ae6d6e1f..55b8b4a0fa94 100644
--- a/include/linux/rcupdate.h
+++ b/include/linux/rcupdate.h
@@ -214,6 +214,15 @@ static inline void exit_tasks_rcu_start(void) { }
 static inline void exit_tasks_rcu_finish(void) { }
 #endif /* #else #ifdef CONFIG_TASKS_RCU_GENERIC */
 
+typedef void (*rcu_tasks_exiting_fn_t)(struct task_struct *t, void *arg);
+#ifdef CONFIG_TASKS_RCU
+void rcu_tasks_visit_exiting(rcu_tasks_exiting_fn_t fn, void *arg);
+int rcu_tasks_snapshot_exiting(struct task_struct **buf, int max);
+#else
+static inline void rcu_tasks_visit_exiting(rcu_tasks_exiting_fn_t fn, void *arg) { }
+static inline int rcu_tasks_snapshot_exiting(struct task_struct **buf, int max) { return 0; }
+#endif
+
 /**
  * cond_resched_tasks_rcu_qs - Report potential quiescent states to RCU
  *
diff --git a/kernel/rcu/tasks.h b/kernel/rcu/tasks.h
index fcac7361ec51..b5fa5a3a8503 100644
--- a/kernel/rcu/tasks.h
+++ b/kernel/rcu/tasks.h
@@ -33,6 +33,8 @@ typedef void (*postgp_func_t)(struct rcu_tasks *rtp);
  * @barrier_q_head: RCU callback for barrier operation.
  * @rtp_blkd_tasks: List of tasks blocked as readers.
  * @rtp_exit_list: List of tasks in the latter portion of do_exit().
+ * @rtp_exit_cursor: Placeholder that rcu_tasks_postscan() parks on @rtp_exit_list
+ *	while it drops the lock, so that exit-list walkers can skip it.
  * @cpu: CPU number corresponding to this entry.
  * @index: Index of this CPU in rtpcp_array of the rcu_tasks structure.
  * @rtpp: Pointer to the rcu_tasks structure.
@@ -49,6 +51,7 @@ struct rcu_tasks_percpu {
 	struct rcu_head barrier_q_head;
 	struct list_head rtp_blkd_tasks;
 	struct list_head rtp_exit_list;
+	struct list_head rtp_exit_cursor;
 	int cpu;
 	int index;
 	struct rcu_tasks *rtpp;
@@ -1068,7 +1071,6 @@ static void rcu_tasks_postscan(struct list_head *hop)
 		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rcu_tasks.rtpcpu, cpu);
 		struct task_struct *t;
 		struct task_struct *t1;
-		struct list_head tmp;
 
 		raw_spin_lock_irq_rcu_node(rtpcp);
 		list_for_each_entry_safe(t, t1, &rtpcp->rtp_exit_list, rcu_tasks_exit_list) {
@@ -1081,14 +1083,15 @@ static void rcu_tasks_postscan(struct list_head *hop)
 				continue;
 
 			// Keep our place in the list while pausing.
-			// Nothing else traverses this list, so adding a
-			// bare list_head is OK.
-			list_add(&tmp, &t->rcu_tasks_exit_list);
+			// The cursor lives in rtpcp so that the exit-list
+			// visitors can recognize and skip it.
+			list_add(&rtpcp->rtp_exit_cursor, &t->rcu_tasks_exit_list);
 			raw_spin_unlock_irq_rcu_node(rtpcp);
 			cond_resched(); // For CONFIG_PREEMPT=n kernels
 			raw_spin_lock_irq_rcu_node(rtpcp);
-			t1 = list_entry(tmp.next, struct task_struct, rcu_tasks_exit_list);
-			list_del(&tmp);
+			t1 = list_entry(rtpcp->rtp_exit_cursor.next, struct task_struct,
+					rcu_tasks_exit_list);
+			list_del(&rtpcp->rtp_exit_cursor);
 			j = jiffies + 1;
 		}
 		raw_spin_unlock_irq_rcu_node(rtpcp);
@@ -1332,6 +1335,60 @@ void exit_tasks_rcu_finish(void)
 	raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
 }
 
+/*
+ * Call fn on every task on the exit lists, in place, with the per-CPU list
+ * lock held and interrupts disabled. fn must not sleep. Does not allocate.
+ * These are the tasks that have passed exit_tasks_rcu_start() but not
+ * exit_tasks_rcu_finish(). Once exit_notify() has run they are no longer on
+ * the task list, but they still run do_exit() and may sleep there.
+ */
+void rcu_tasks_visit_exiting(rcu_tasks_exiting_fn_t fn, void *arg)
+{
+	int cpu;
+	unsigned long flags;
+	struct task_struct *t;
+
+	for_each_possible_cpu(cpu) {
+		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rcu_tasks.rtpcpu, cpu);
+
+		raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
+		list_for_each_entry(t, &rtpcp->rtp_exit_list, rcu_tasks_exit_list) {
+			if (&t->rcu_tasks_exit_list == &rtpcp->rtp_exit_cursor)
+				continue;
+			fn(t, arg);
+		}
+		raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
+	}
+}
+
+/*
+ * Copy up to max tasks on the exit lists into buf, taking a reference on
+ * each. Returns the number of tasks on the lists, which may exceed max.
+ */
+int rcu_tasks_snapshot_exiting(struct task_struct **buf, int max)
+{
+	int cpu, n = 0;
+	unsigned long flags;
+	struct task_struct *t;
+
+	for_each_possible_cpu(cpu) {
+		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rcu_tasks.rtpcpu, cpu);
+
+		raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
+		list_for_each_entry(t, &rtpcp->rtp_exit_list, rcu_tasks_exit_list) {
+			if (&t->rcu_tasks_exit_list == &rtpcp->rtp_exit_cursor)
+				continue;
+			if (n < max) {
+				get_task_struct(t);
+				buf[n] = t;
+			}
+			n++;
+		}
+		raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
+	}
+	return n;
+}
+
 #else /* #ifdef CONFIG_TASKS_RCU */
 void exit_tasks_rcu_start(void) { }
 void exit_tasks_rcu_finish(void) { }

-- 
2.39.5



^ permalink raw reply	[flat|nested] 14+ messages in thread

* [PATCH v4 2/3] livepatch: Include exiting tasks in the transition
  2026-11-26 16:41 [PATCH v4 0/3] livepatch: Do not lose exiting tasks during a transition Binoy Ravindran via B4 Relay
  2026-11-26 16:41 ` [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists Binoy Ravindran via B4 Relay
@ 2026-11-26 16:41 ` Binoy Ravindran via B4 Relay
  2026-11-27 16:10   ` Petr Mladek
  2026-11-26 16:41 ` [PATCH v4 3/3] livepatch: Select TASKS_RCU Binoy Ravindran via B4 Relay
  2 siblings, 1 reply; 14+ messages in thread
From: Binoy Ravindran via B4 Relay @ 2026-11-26 16:41 UTC (permalink / raw)
  To: Paul E. McKenney, Frederic Weisbecker, Neeraj Upadhyay,
	Joel Fernandes, Josh Triplett, Boqun Feng, Uladzislau Rezki,
	Steven Rostedt, Mathieu Desnoyers, Lai Jiangshan, Zqiang,
	Josh Poimboeuf, Miroslav Benes, Petr Mladek, Joe Lawrence,
	Song Liu, Ingo Molnar, Jiri Kosina
  Cc: rcu, linux-kernel, live-patching, Yafang Shao, Jaidev Shastri,
	Binoy Ravindran

From: Binoy Ravindran <binoy@vt.edu>

The transition walks tasks with for_each_process_thread(). A
self-reaping task is unhashed in exit_notify() but keeps running the rest
of do_exit(), so the walk never sees it. The transition can then
complete, and with atomic replace the previous patch module can be
freed, while that task is still executing, or about to return into, the
previous module's copy of a patched function. This is the race discussed
in the thread linked below.

An exiting task is on an RCU-tasks exit list from exit_tasks_rcu_start(),
before exit_notify(), until exit_tasks_rcu_finish(). Make every step of
a transition also visit the tasks on these lists, using the helpers from
the previous patch. klp_init_transition(), klp_start_transition(),
klp_complete_transition(), klp_reverse_transition() and
klp_force_transition() only set fields and flags. They walk the exit
lists in place, under tasklist_lock, and skip tasks that are still
hashed, so that each task is visited exactly once.
klp_try_complete_transition() may inspect a task's stack, so it takes a
snapshot with a reference on each task. If the snapshot cannot be
allocated, or more tasks start exiting than it has room for, the
transition is treated as incomplete and retried. An exiting task must
therefore switch, like any other task, before the transition can
complete.

After exit_tasks_rcu_finish() the task may be on neither list, but it
can still run patched code until its final switch. do_exit() disables
preemption before exit_tasks_rcu_finish(), so from then on the task
cannot sleep, be preempted or migrate, and the next context switch on
its CPU is its last. klp_synchronize_transition() returns only after
every online CPU has switched context, so it waits out every task in this
stretch. synchronize_rcu() is not enough here: __schedule() reports the
RCU quiescent state in rcu_note_context_switch(), before switch_to(), so
it can return while the task still runs traceable code in __schedule().
Call it in two places:

- In klp_init_transition(), after patch_state has been set on every
  task and before func->transition is set. An exiting task that the
  walks did not visit had left the exit lists before or during them,
  so it is gone before any function enters the transition.

- In klp_try_complete_transition(), before klp_complete_transition().
  A task that left the exit lists unswitched after the snapshot is gone
  before func->transition is cleared and before the previous patch can
  be freed.

Covering the initialization and completion steps matters as well:
otherwise an exiting task keeps a stale patch_state from an earlier
transition, which can equal the new target. Likewise, the reverse path
clears TIF_PATCH_PENDING on exiting tasks and the force path updates
their patch state, so neither leaves an exiting task behind.
klp_send_signals() is not extended: a task that has passed exit_notify()
never returns to user space, so a fake signal cannot help it switch.

The exit lists exist only with CONFIG_TASKS_RCU, which every kernel
that can enable LIVEPATCH builds today. A following patch makes
LIVEPATCH select it.

Tested on v7.4-rc2, x86-64, under QEMU/KVM. Two klp-build livepatches
that each replace do_exit() replace each other ten times per run while
self-reaping tasks exit continuously, with a debug-only msleep() after
exit_notify() to widen the window. Without this series, 9 of 12 runs
crashed executing freed module memory after the previous patch was
removed. With it, all 12 runs completed their 120 replace cycles
without a fault. Without the delay, both kernels completed 60 cycles
without a fault.

Fixes: d83a7cb375ee ("livepatch: change to a per-task consistency model")
Link: https://lore.kernel.org/all/20250127063526.76687-1-laoar.shao@gmail.com/
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Binoy Ravindran <binoy@vt.edu>
---
 kernel/livepatch/transition.c | 102 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 102 insertions(+)

diff --git a/kernel/livepatch/transition.c b/kernel/livepatch/transition.c
index 2351a19ac2a9..2b13b0b04eeb 100644
--- a/kernel/livepatch/transition.c
+++ b/kernel/livepatch/transition.c
@@ -10,6 +10,7 @@
 #include <linux/cpu.h>
 #include <linux/stacktrace.h>
 #include <linux/static_call.h>
+#include <linux/slab.h>
 #include "core.h"
 #include "patch.h"
 #include "transition.h"
@@ -74,6 +75,54 @@ static void klp_synchronize_transition(void)
 	schedule_on_each_cpu(klp_sync);
 }
 
+/*
+ * Tasks past exit_notify() are off the task list but still run do_exit() and its
+ * callees, possibly from this patch's or a replaced patch's code, so the
+ * transition must cover them too. The try step inspects stacks, which needs a
+ * reference on each task, so klp_try_switch_exiting_tasks() works on a
+ * snapshot of the exit lists.
+ *
+ * The other steps run with tasklist_lock held and skip tasks that are still
+ * hashed, so every task is visited exactly once: an exiting task can be on
+ * both lists until release_task() unhashes it.
+ */
+static void klp_exiting_init(struct task_struct *t, void *arg)
+{
+	if (pid_alive(t))
+		return;	/* still on the task list: already visited */
+	t->patch_state = *(int *)arg;
+}
+
+static void klp_exiting_start(struct task_struct *t, void *arg)
+{
+	if (pid_alive(t))
+		return;	/* still on the task list: already visited */
+	if (t->patch_state != klp_target_state)
+		set_tsk_thread_flag(t, TIF_PATCH_PENDING);
+}
+
+static void klp_exiting_complete(struct task_struct *t, void *arg)
+{
+	if (pid_alive(t))
+		return;	/* still on the task list: already visited */
+	clear_tsk_thread_flag(t, TIF_PATCH_PENDING);
+	t->patch_state = KLP_TRANSITION_IDLE;
+}
+
+static void klp_exiting_clear_pending(struct task_struct *t, void *arg)
+{
+	if (pid_alive(t))
+		return;	/* still on the task list: already visited */
+	clear_tsk_thread_flag(t, TIF_PATCH_PENDING);
+}
+
+static void klp_exiting_force(struct task_struct *t, void *arg)
+{
+	if (pid_alive(t))
+		return;	/* still on the task list: already visited */
+	klp_update_patch_state(t);
+}
+
 /*
  * The transition to the target patch state is complete.  Clean up the data
  * structures.
@@ -123,6 +172,7 @@ static void klp_complete_transition(void)
 		WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING));
 		task->patch_state = KLP_TRANSITION_IDLE;
 	}
+	rcu_tasks_visit_exiting(klp_exiting_complete, NULL);
 	read_unlock(&tasklist_lock);
 
 	for_each_possible_cpu(cpu) {
@@ -419,6 +469,35 @@ static void klp_send_signals(void)
 	read_unlock(&tasklist_lock);
 }
 
+/*
+ * Try to switch every task on the exit lists. Returns false if one of them
+ * could not be switched yet, or if the snapshot could not be taken in full.
+ */
+static bool klp_try_switch_exiting_tasks(void)
+{
+	struct task_struct **xt;
+	bool complete = true;
+	int i, n, max;
+
+	/*
+	 * Size the array from a count taken now, plus slack for tasks that
+	 * start exiting before the copy is made. If even more arrive, report
+	 * an incomplete walk: klp_try_complete_transition() runs again later.
+	 */
+	max = rcu_tasks_snapshot_exiting(NULL, 0) + 64;
+	xt = kvmalloc_array(max, sizeof(*xt), GFP_KERNEL);
+	if (!xt)
+		return false;
+	n = rcu_tasks_snapshot_exiting(xt, max);
+	for (i = 0; i < min(n, max); i++) {
+		if (!klp_try_switch_task(xt[i]))
+			complete = false;
+		put_task_struct(xt[i]);
+	}
+	kvfree(xt);
+	return complete && n <= max;
+}
+
 /*
  * Try to switch all remaining tasks to the target patch state by walking the
  * stacks of sleeping tasks and looking for any to-be-patched or
@@ -450,6 +529,8 @@ void klp_try_complete_transition(void)
 		if (!klp_try_switch_task(task))
 			complete = false;
 	read_unlock(&tasklist_lock);
+	if (!klp_try_switch_exiting_tasks())
+		complete = false;
 
 	/*
 	 * Ditto for the idle "swapper" tasks.
@@ -489,6 +570,13 @@ void klp_try_complete_transition(void)
 	/* Done!  Now cleanup the data structures. */
 	klp_resched_disable();
 	patch = klp_transition_patch;
+	/*
+	 * A task can leave the exit lists unswitched after the snapshot. It
+	 * runs with preemption disabled until its final switch, so wait until
+	 * every CPU has switched context. synchronize_rcu() is not enough:
+	 * __schedule() reports the quiescent state before switch_to().
+	 */
+	klp_synchronize_transition();
 	klp_complete_transition();
 
 	/*
@@ -526,6 +614,7 @@ void klp_start_transition(void)
 	for_each_process_thread(g, task)
 		if (task->patch_state != klp_target_state)
 			set_tsk_thread_flag(task, TIF_PATCH_PENDING);
+	rcu_tasks_visit_exiting(klp_exiting_start, NULL);
 	read_unlock(&tasklist_lock);
 
 	/*
@@ -579,6 +668,7 @@ void klp_init_transition(struct klp_patch *patch, int state)
 		WARN_ON_ONCE(task->patch_state != KLP_TRANSITION_IDLE);
 		task->patch_state = initial_state;
 	}
+	rcu_tasks_visit_exiting(klp_exiting_init, &initial_state);
 	read_unlock(&tasklist_lock);
 
 	/*
@@ -590,6 +680,16 @@ void klp_init_transition(struct klp_patch *patch, int state)
 		task->patch_state = initial_state;
 	}
 
+	/*
+	 * A task that has passed exit_tasks_rcu_finish() is on neither list but
+	 * may still call patched code until its final switch, which it makes
+	 * with preemption disabled. This returns only after every CPU has
+	 * switched context, so every such task is gone. synchronize_rcu() is
+	 * not enough: __schedule() reports the quiescent state before
+	 * switch_to().
+	 */
+	klp_synchronize_transition();
+
 	/*
 	 * Enforce the order of the task->patch_state initializations and the
 	 * func->transition updates to ensure that klp_ftrace_handler() doesn't
@@ -642,6 +742,7 @@ void klp_reverse_transition(void)
 	read_lock(&tasklist_lock);
 	for_each_process_thread(g, task)
 		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
+	rcu_tasks_visit_exiting(klp_exiting_clear_pending, NULL);
 	read_unlock(&tasklist_lock);
 
 	for_each_possible_cpu(cpu)
@@ -714,6 +815,7 @@ void klp_force_transition(void)
 	read_lock(&tasklist_lock);
 	for_each_process_thread(g, task)
 		klp_update_patch_state(task);
+	rcu_tasks_visit_exiting(klp_exiting_force, NULL);
 	read_unlock(&tasklist_lock);
 
 	for_each_possible_cpu(cpu)

-- 
2.39.5



^ permalink raw reply	[flat|nested] 14+ messages in thread

* [PATCH v4 3/3] livepatch: Select TASKS_RCU
  2026-11-26 16:41 [PATCH v4 0/3] livepatch: Do not lose exiting tasks during a transition Binoy Ravindran via B4 Relay
  2026-11-26 16:41 ` [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists Binoy Ravindran via B4 Relay
  2026-11-26 16:41 ` [PATCH v4 2/3] livepatch: Include exiting tasks in the transition Binoy Ravindran via B4 Relay
@ 2026-11-26 16:41 ` Binoy Ravindran via B4 Relay
  2 siblings, 0 replies; 14+ messages in thread
From: Binoy Ravindran via B4 Relay @ 2026-11-26 16:41 UTC (permalink / raw)
  To: Paul E. McKenney, Frederic Weisbecker, Neeraj Upadhyay,
	Joel Fernandes, Josh Triplett, Boqun Feng, Uladzislau Rezki,
	Steven Rostedt, Mathieu Desnoyers, Lai Jiangshan, Zqiang,
	Josh Poimboeuf, Miroslav Benes, Petr Mladek, Joe Lawrence,
	Song Liu, Ingo Molnar, Jiri Kosina
  Cc: rcu, linux-kernel, live-patching, Yafang Shao, Jaidev Shastri,
	Binoy Ravindran

From: Binoy Ravindran <binoy@vt.edu>

The transition finds exiting tasks through the RCU-tasks exit lists,
which exist only with CONFIG_TASKS_RCU. Every kernel that can enable
LIVEPATCH already builds TASKS_RCU. TASKS_RCU defaults to
NEED_TASKS_RCU && PREEMPTION. LIVEPATCH depends on dynamic ftrace, so
FUNCTION_TRACER is set, and it selects NEED_TASKS_RCU. Every
architecture that selects HAVE_LIVEPATCH also selects
ARCH_HAS_PREEMPT_LAZY, which rules out PREEMPT_VOLUNTARY, and none
selects ARCH_NO_PREEMPT, which PREEMPT_NONE requires, so PREEMPTION is
always set.

Select TASKS_RCU explicitly, so that the dependency is documented and
holds even if those defaults change. This changes no configuration
today.

Suggested-by: Yafang Shao <laoar.shao@gmail.com>
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Binoy Ravindran <binoy@vt.edu>
---
 kernel/livepatch/Kconfig | 1 +
 1 file changed, 1 insertion(+)

diff --git a/kernel/livepatch/Kconfig b/kernel/livepatch/Kconfig
index 4c0a9c18d0b2..683d6993e207 100644
--- a/kernel/livepatch/Kconfig
+++ b/kernel/livepatch/Kconfig
@@ -12,6 +12,7 @@ config LIVEPATCH
 	depends on KALLSYMS_ALL
 	depends on HAVE_LIVEPATCH
 	depends on !TRIM_UNUSED_KSYMS
+	select TASKS_RCU
 	help
 	  Say Y here if you want to support kernel live patching.
 	  This option has no runtime impact until a kernel "patch"

-- 
2.39.5



^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists
  2026-11-26 16:41 ` [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists Binoy Ravindran via B4 Relay
@ 2026-11-26 18:52   ` Petr Mladek
  2026-11-27 18:56     ` Ravindran, Binoy
  2026-11-30 17:42   ` Paul E. McKenney
  1 sibling, 1 reply; 14+ messages in thread
From: Petr Mladek @ 2026-11-26 18:52 UTC (permalink / raw)
  To: binoy
  Cc: Paul E. McKenney, Frederic Weisbecker, Neeraj Upadhyay,
	Joel Fernandes, Josh Triplett, Boqun Feng, Uladzislau Rezki,
	Steven Rostedt, Mathieu Desnoyers, Lai Jiangshan, Zqiang,
	Josh Poimboeuf, Miroslav Benes, Joe Lawrence, Song Liu,
	Ingo Molnar, Jiri Kosina, rcu, linux-kernel, live-patching,
	Yafang Shao, Jaidev Shastri

On Thu 2026-11-26 11:41:32, Binoy Ravindran via B4 Relay wrote:
> From: Binoy Ravindran <binoy@vt.edu>
> 
> A task joins its CPU's RCU-tasks exit list in exit_tasks_rcu_start(),
> before exit_notify() unhashes it from the task list, and leaves it in
> exit_tasks_rcu_finish(), after do_exit() has disabled preemption for the
> final switch. Once exit_notify() has unhashed it, the task is no longer
> found by for_each_process_thread(), but it still runs do_exit() and may
> sleep there. Code that must reach every task that can still be
> descheduled, such as the livepatch transition, has no way to find it.
> 
> Add two helpers. rcu_tasks_visit_exiting() calls a function on each
> task on the exit lists under the list locks, without allocating.
> rcu_tasks_snapshot_exiting() copies the tasks into a caller-supplied
> array with a reference held on each, for callers that must sleep or take
> other locks while examining them. Without CONFIG_TASKS_RCU there are no
> exit lists, and the helpers do nothing.

Nit: I would be nice to make the commit messages better human readable.
     The dense paragraphs generated by AI are not easy to read. I mean
     something like:

Add two helpers:

  1. rcu_tasks_visit_exiting() allows to do a quick operation on
     all exiting processes. It will be needed, for example, for...

  2. rcu_tasks_snapshot_exiting() ...


> rcu_tasks_postscan() keeps its place in an exit list with a bare
> list_head while it drops the lock to reschedule, relying on nobody else
> traversing the list. Move that cursor into struct rcu_tasks_percpu,
> next to the list it marks, so that the new helpers can recognize and
> skip it. Only the grace-period kthread runs postscan, one CPU's list at
> a time, so one cursor per CPU suffices.
> 
> --- a/kernel/rcu/tasks.h
> +++ b/kernel/rcu/tasks.h
> @@ -33,6 +33,8 @@ typedef void (*postgp_func_t)(struct rcu_tasks *rtp);
>   * @barrier_q_head: RCU callback for barrier operation.
>   * @rtp_blkd_tasks: List of tasks blocked as readers.
>   * @rtp_exit_list: List of tasks in the latter portion of do_exit().
> + * @rtp_exit_cursor: Placeholder that rcu_tasks_postscan() parks on @rtp_exit_list
> + *	while it drops the lock, so that exit-list walkers can skip it.
>   * @cpu: CPU number corresponding to this entry.
>   * @index: Index of this CPU in rtpcp_array of the rcu_tasks structure.
>   * @rtpp: Pointer to the rcu_tasks structure.
> @@ -49,6 +51,7 @@ struct rcu_tasks_percpu {
>  	struct rcu_head barrier_q_head;
>  	struct list_head rtp_blkd_tasks;
>  	struct list_head rtp_exit_list;
> +	struct list_head rtp_exit_cursor;
>  	int cpu;
>  	int index;
>  	struct rcu_tasks *rtpp;
> @@ -1068,7 +1071,6 @@ static void rcu_tasks_postscan(struct list_head *hop)
>  		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rcu_tasks.rtpcpu, cpu);
>  		struct task_struct *t;
>  		struct task_struct *t1;
> -		struct list_head tmp;
>  
>  		raw_spin_lock_irq_rcu_node(rtpcp);
>  		list_for_each_entry_safe(t, t1, &rtpcp->rtp_exit_list, rcu_tasks_exit_list) {
> @@ -1081,14 +1083,15 @@ static void rcu_tasks_postscan(struct list_head *hop)
>  				continue;
>  
>  			// Keep our place in the list while pausing.
> -			// Nothing else traverses this list, so adding a
> -			// bare list_head is OK.
> -			list_add(&tmp, &t->rcu_tasks_exit_list);
> +			// The cursor lives in rtpcp so that the exit-list
> +			// visitors can recognize and skip it.
> +			list_add(&rtpcp->rtp_exit_cursor, &t->rcu_tasks_exit_list);
>  			raw_spin_unlock_irq_rcu_node(rtpcp);
>  			cond_resched(); // For CONFIG_PREEMPT=n kernels
>  			raw_spin_lock_irq_rcu_node(rtpcp);
> -			t1 = list_entry(tmp.next, struct task_struct, rcu_tasks_exit_list);
> -			list_del(&tmp);
> +			t1 = list_entry(rtpcp->rtp_exit_cursor.next, struct task_struct,
> +					rcu_tasks_exit_list);
> +			list_del(&rtpcp->rtp_exit_cursor);
>  			j = jiffies + 1;
>  		}
>  		raw_spin_unlock_irq_rcu_node(rtpcp);
> @@ -1332,6 +1335,60 @@ void exit_tasks_rcu_finish(void)
>  	raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
>  }
>  
> +/*
> + * Call fn on every task on the exit lists, in place, with the per-CPU list
> + * lock held and interrupts disabled. fn must not sleep. Does not allocate.
> + * These are the tasks that have passed exit_tasks_rcu_start() but not
> + * exit_tasks_rcu_finish(). Once exit_notify() has run they are no longer on
> + * the task list, but they still run do_exit() and may sleep there.
> + */
> +void rcu_tasks_visit_exiting(rcu_tasks_exiting_fn_t fn, void *arg)
> +{
> +	int cpu;
> +	unsigned long flags;
> +	struct task_struct *t;
> +
> +	for_each_possible_cpu(cpu) {
> +		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rcu_tasks.rtpcpu, cpu);
> +
> +		raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
> +		list_for_each_entry(t, &rtpcp->rtp_exit_list, rcu_tasks_exit_list) {
> +			if (&t->rcu_tasks_exit_list == &rtpcp->rtp_exit_cursor)
> +				continue;
> +			fn(t, arg);

Is it acceptable to process all entries while keeping the raw_spin_lock()?

rcu_tasks_postscan() contains the trick with the @tmp/@rtp_exit_cursor
list_head to be able to release the spin lock while walking the list.

You might argue that our fn() is short. But rcu_tasks_postscan() calls
rcu_tasks_pertask() in the loop and it seems to be quite simple as well.

IMHO, a better approach would be to make rcu_tasks_postscan() generic
function to do an operation on the rcu_tasks_exit_list and release
the spin lock regularly. The operation should be defined via a *fn
passed as a parameter.

I mean to allow to use the same RT-friendly for-cycle in both RCU
and livepatching code paths.

We might need more cursors. One for the RCU code path and
another for the livepatching code path.

It will be tricky. But it will remove the hack with copying the list
of exiting processes into a temporary allocated array. The allocation
and copying is problematic on its own. IMHO, it might cause a livelock
when many processes are exiting...

Best Regards,
Petr

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH v4 2/3] livepatch: Include exiting tasks in the transition
  2026-11-26 16:41 ` [PATCH v4 2/3] livepatch: Include exiting tasks in the transition Binoy Ravindran via B4 Relay
@ 2026-11-27 16:10   ` Petr Mladek
  2026-11-27 19:30     ` Ravindran, Binoy
  0 siblings, 1 reply; 14+ messages in thread
From: Petr Mladek @ 2026-11-27 16:10 UTC (permalink / raw)
  To: binoy
  Cc: Paul E. McKenney, Frederic Weisbecker, Neeraj Upadhyay,
	Joel Fernandes, Josh Triplett, Boqun Feng, Uladzislau Rezki,
	Steven Rostedt, Mathieu Desnoyers, Lai Jiangshan, Zqiang,
	Josh Poimboeuf, Miroslav Benes, Joe Lawrence, Song Liu,
	Ingo Molnar, Jiri Kosina, rcu, linux-kernel, live-patching,
	Yafang Shao, Jaidev Shastri

On Thu 2026-11-26 11:41:33, Binoy Ravindran via B4 Relay wrote:
> From: Binoy Ravindran <binoy@vt.edu>
> 
> The transition walks tasks with for_each_process_thread(). A
> self-reaping task is unhashed in exit_notify() but keeps running the rest
> of do_exit(), so the walk never sees it. The transition can then
> complete, and with atomic replace the previous patch module can be
> freed, while that task is still executing, or about to return into, the
> previous module's copy of a patched function. This is the race discussed
> in the thread linked below.

I would use [1] to reference the discussion, see below.

> An exiting task is on an RCU-tasks exit list from exit_tasks_rcu_start(),
> before exit_notify(), until exit_tasks_rcu_finish(). Make every step of
> a transition also visit the tasks on these lists, using the helpers from
> the previous patch.

I would start another paragraph here.

> klp_init_transition(), klp_start_transition(),
> klp_complete_transition(), klp_reverse_transition() and
> klp_force_transition() only set fields and flags. They walk the exit
> lists in place, under tasklist_lock, and skip tasks that are still
> hashed, so that each task is visited exactly once.

I was confused by the meaning of "tasks still hashed".

Later I realized that it pointed to __unhash_process() function.
I heard about this function for the first time. I have never
met a term "hashed process" before. I never needed to study pids this
deeply.

Honestly, I think that "hashed task" is a term invented by LLMS.
It does not mean much. It is just a "poorly" chosen helper
function name in kernel/exit.c. There is no counter part
in kernel/fork.c...

Instead, I would write something like: "skip tasks which are still
accessible via the for_each_process_thread() walk, so that each
task is visited only once."

BTW: Would it hurt to process the same task twice?

     I think that it should not be a big deal. It looks like an
     optimization. But the dependence between pid_alive(),
     for_each_process_thread(), and task_list lock is pretty
     tricky. I am not sure if it is worth relying on it.

Also I would start another paragraph here.

> klp_try_complete_transition() may inspect a task's stack, so it takes a
> snapshot with a reference on each task. If the snapshot cannot be
> allocated, or more tasks start exiting than it has room for, the
> transition is treated as incomplete and retried. An exiting task must
> therefore switch, like any other task, before the transition can
> complete.
> 
> Fixes: d83a7cb375ee ("livepatch: change to a per-task consistency model")
> Link: https://lore.kernel.org/all/20250127063526.76687-1-laoar.shao@gmail.com/

This points to the cover letter of a patchset. Many things were
discussed there. It might be better to mention here the mail
where the discussion about livepatching do_exit() started.

Also I would use:

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

instead of "Link: " so that [1] can be used as a reference in
the text above.

> Assisted-by: Claude:claude-opus-5-5

This is not needed.

> Signed-off-by: Binoy Ravindran <binoy@vt.edu>
> --- a/kernel/livepatch/transition.c
> +++ b/kernel/livepatch/transition.c
> @@ -74,6 +75,54 @@ static void klp_synchronize_transition(void)
>  	schedule_on_each_cpu(klp_sync);
>  }
>  
> +/*
> + * Tasks past exit_notify() are off the task list but still run do_exit() and its
> + * callees, possibly from this patch's or a replaced patch's code, so the
> + * transition must cover them too. The try step inspects stacks, which needs a
> + * reference on each task, so klp_try_switch_exiting_tasks() works on a
> + * snapshot of the exit lists.
> + *
> + * The other steps run with tasklist_lock held and skip tasks that are still
> + * hashed, so every task is visited exactly once: an exiting task can be on
> + * both lists until release_task() unhashes it.

I would be more explicit here.

  * Important: Both for_each_process_thread() and rcu_tasks_exit_list
  *	must be traversed under tasklist_lock. It prevents calling
  *	__unhash_process() so that pid_alive() can be used to detect
  *	whether the task has already been proceed in
  *	for_each_process_thread() cycle.

But as I have said, I am not sure of it is worth it.

> + */
> +static void klp_exiting_init(struct task_struct *t, void *arg)
> +{
> +	if (pid_alive(t))
> +		return;	/* still on the task list: already visited */
> +	t->patch_state = *(int *)arg;
> +}
> +
> +static void klp_exiting_start(struct task_struct *t, void *arg)
> +{
> +	if (pid_alive(t))
> +		return;	/* still on the task list: already visited */
> +	if (t->patch_state != klp_target_state)
> +		set_tsk_thread_flag(t, TIF_PATCH_PENDING);
> +}
> +
> +static void klp_exiting_complete(struct task_struct *t, void *arg)
> +{
> +	if (pid_alive(t))
> +		return;	/* still on the task list: already visited */
> +	clear_tsk_thread_flag(t, TIF_PATCH_PENDING);
> +	t->patch_state = KLP_TRANSITION_IDLE;
> +}
> +
> +static void klp_exiting_clear_pending(struct task_struct *t, void *arg)

The name of other callbacks seems to follow the name of the function
where they are called. This one is called in klp_reverse_transition()
so I would call it:

	klp_exiting_reverse();

> +{
> +	if (pid_alive(t))
> +		return;	/* still on the task list: already visited */
> +	clear_tsk_thread_flag(t, TIF_PATCH_PENDING);
> +}
> +
> +static void klp_exiting_force(struct task_struct *t, void *arg)
> +{
> +	if (pid_alive(t))
> +		return;	/* still on the task list: already visited */
> +	klp_update_patch_state(t);
> +}

That said, the names look a bit confusing. It feels like these
callbacks are initializing, starting, completing, ... some exit.

I would use:

   + prefix: "klp_exit_task_*" to make it more clear
	that it is manipulating a task in some exit state.

   + same suffix as the caller, .e.g "init_transition" to
	make it clear which stage of the transition it
	manipulates.

So, rename:

  + klp_exiting_init	 -> klp_exit_task_init_transition
  + klp_exiting_start	 -> klp_exit_task_start_transition
  + klp_exiting_complete -> klp_exit_task_complete_transition
  ...


> +
>  /*
>   * The transition to the target patch state is complete.  Clean up the data
>   * structures.
> @@ -123,6 +172,7 @@ static void klp_complete_transition(void)
>  		WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING));
>  		task->patch_state = KLP_TRANSITION_IDLE;
>  	}
> +	rcu_tasks_visit_exiting(klp_exiting_complete, NULL);
>  	read_unlock(&tasklist_lock);
>  
>  	for_each_possible_cpu(cpu) {
> @@ -419,6 +469,35 @@ static void klp_send_signals(void)
>  	read_unlock(&tasklist_lock);
>  }
>  
> +/*
> + * Try to switch every task on the exit lists. Returns false if one of them
> + * could not be switched yet, or if the snapshot could not be taken in full.
> + */
> +static bool klp_try_switch_exiting_tasks(void)
> +{
> +	struct task_struct **xt;
> +	bool complete = true;
> +	int i, n, max;
> +
> +	/*
> +	 * Size the array from a count taken now, plus slack for tasks that
> +	 * start exiting before the copy is made. If even more arrive, report
> +	 * an incomplete walk: klp_try_complete_transition() runs again later.
> +	 */
> +	max = rcu_tasks_snapshot_exiting(NULL, 0) + 64;
> +	xt = kvmalloc_array(max, sizeof(*xt), GFP_KERNEL);
> +	if (!xt)
> +		return false;
> +	n = rcu_tasks_snapshot_exiting(xt, max);
> +	for (i = 0; i < min(n, max); i++) {
> +		if (!klp_try_switch_task(xt[i]))
> +			complete = false;
> +		put_task_struct(xt[i]);
> +	}
> +	kvfree(xt);
> +	return complete && n <= max;
> +}

I did not check this function. I think that we will do it another way,
see my reply to the 1st patch.

>  /*
>   * Try to switch all remaining tasks to the target patch state by walking the
>   * stacks of sleeping tasks and looking for any to-be-patched or
> @@ -450,6 +529,8 @@ void klp_try_complete_transition(void)
>  		if (!klp_try_switch_task(task))
>  			complete = false;
>  	read_unlock(&tasklist_lock);
> +	if (!klp_try_switch_exiting_tasks())
> +		complete = false;
>  
>  	/*
>  	 * Ditto for the idle "swapper" tasks.
> @@ -489,6 +570,13 @@ void klp_try_complete_transition(void)
>  	/* Done!  Now cleanup the data structures. */
>  	klp_resched_disable();
>  	patch = klp_transition_patch;
> +	/*
> +	 * A task can leave the exit lists unswitched after the snapshot. It
> +	 * runs with preemption disabled until its final switch, so wait until
> +	 * every CPU has switched context.

Just imagine that you see this comment 2 years from now without
the fresh context. "exit list" sounds a bit vague. Also "the snapshot"
is a term that was not mentioned anywhere else.

I would be more precise. I suggest something like:

	* There might still be tasks which were already removed from
	* rcu_tasks_exit_list and were not checked above. They run with
	* the preemption disabled until they finally stop in TASK_DEAD state.
	* Make sure that they stopped running and will never run again.

Now the question is why we need to call it here and not,
for example, in klp_start_transition() or klp_reverse_transition().

IMHO, we need it here to avoid removing the ftrace trampolines and
the livepatch module when the code still might be in use.

BTW: Do we need it in all situations, for example, when the 1st
     livepatch gets enabled? In this case, nothing is removed.

Anyway, we should explain in the comment why exactly we need
the synchronization here.

> synchronize_rcu() is not enough:
> +	 * __schedule() reports the quiescent state before switch_to().

I would say that synchronize_rcu() is not enough by definition.
We are waiting for tasks which are not longer visible for RCU.

But I agree that the comment above rcu_tasks_postgp() might be confusing.
I guess that RCU does not care about tracking the rest of __schedule().

So, it makes sense to keep the comment here. I would just add it into
a separate paragraph (after an empty line).

> +	 */
> +	klp_synchronize_transition();

Hmm, I would move this up, above the comment: "/* Done!  Now cleanup
the data structures. */". Let's be on the safe side and
make sure that all tasks are safe before we start the clean up...

Or is there any reason why it is done here?

>  	klp_complete_transition();
>  
>  	/*
> @@ -526,6 +614,7 @@ void klp_start_transition(void)
>  	for_each_process_thread(g, task)
>  		if (task->patch_state != klp_target_state)
>  			set_tsk_thread_flag(task, TIF_PATCH_PENDING);
> +	rcu_tasks_visit_exiting(klp_exiting_start, NULL);
>  	read_unlock(&tasklist_lock);
>  
>  	/*
> @@ -579,6 +668,7 @@ void klp_init_transition(struct klp_patch *patch, int state)
>  		WARN_ON_ONCE(task->patch_state != KLP_TRANSITION_IDLE);
>  		task->patch_state = initial_state;
>  	}
> +	rcu_tasks_visit_exiting(klp_exiting_init, &initial_state);
>  	read_unlock(&tasklist_lock);
>  
>  	/*
> @@ -590,6 +680,16 @@ void klp_init_transition(struct klp_patch *patch, int state)
>  		task->patch_state = initial_state;
>  	}
>  
> +	/*
> +	 * A task that has passed exit_tasks_rcu_finish() is on neither list but
> +	 * may still call patched code until its final switch, which it makes
> +	 * with preemption disabled. This returns only after every CPU has
> +	 * switched context, so every such task is gone. synchronize_rcu() is
> +	 * not enough: __schedule() reports the quiescent state before
> +	 * switch_to().
> +	 */
> +	klp_synchronize_transition();

Why exactly do we need the synchronization here, please?

We should not need this for livepatching of do_exit(). We do not care
which do_exit() implementation is used by the about-to-die processes
at this stage.

The only problem might be if we want to livepatch a function which
is called in do_exit() after the process gets removed from the
rcu_tasks_exit_list. It might be only:

  + raw_spin_unlock_irqrestore_rcu_node()
  + lockdep_free_task()
  + do_task_dead()
  + set_special_state()
  + __schedule()

They all might start calling klp_ftrace_handler() and could need to
see consistent state current->patch_state.

But wait! If this is the problem then we might need to call
klp_synchronize_transition() in each stage which calls
rcu_tasks_visit_exiting(). Otherwise, the klp_ftrace_handler()
might see some inconsistence and trigger a WARN() or
use an inconsistent task->patch_state.

>  	/*
>  	 * Enforce the order of the task->patch_state initializations and the
>  	 * func->transition updates to ensure that klp_ftrace_handler() doesn't
> @@ -642,6 +742,7 @@ void klp_reverse_transition(void)
>  	read_lock(&tasklist_lock);
>  	for_each_process_thread(g, task)
>  		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
> +	rcu_tasks_visit_exiting(klp_exiting_clear_pending, NULL);
>  	read_unlock(&tasklist_lock);
>  
>  	for_each_possible_cpu(cpu)
> @@ -714,6 +815,7 @@ void klp_force_transition(void)
>  	read_lock(&tasklist_lock);
>  	for_each_process_thread(g, task)
>  		klp_update_patch_state(task);
> +	rcu_tasks_visit_exiting(klp_exiting_force, NULL);
>  	read_unlock(&tasklist_lock);
>  
>  	for_each_possible_cpu(cpu)

Best Regards,
Petr

PS: It is an amazing work for a newcomer.

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists
  2026-11-26 18:52   ` Petr Mladek
@ 2026-11-27 18:56     ` Ravindran, Binoy
  0 siblings, 0 replies; 14+ messages in thread
From: Ravindran, Binoy @ 2026-11-27 18:56 UTC (permalink / raw)
  To: Petr Mladek
  Cc: Paul E. McKenney, Frederic Weisbecker, Neeraj Upadhyay,
	Joel Fernandes, Josh Triplett, Boqun Feng, Uladzislau Rezki,
	Steven Rostedt, Mathieu Desnoyers, Lai Jiangshan, Zqiang,
	Josh Poimboeuf, Miroslav Benes, Joe Lawrence, Song Liu,
	Ingo Molnar, Jiri Kosina, rcu, linux-kernel, live-patching,
	Yafang Shao, Shastri, Jaidev


Hi Petr,

> Nit: I would be nice to make the commit messages better human
> readable.

Thanks. I will rewrite them in that style, with each helper in its own
numbered item.

> Is it acceptable to process all entries while keeping the
> raw_spin_lock()?

No, you are right. The walk length is unbounded when many tasks are
exiting.

> IMHO, a better approach would be to make rcu_tasks_postscan()
> generic function to do an operation on the rcu_tasks_exit_list and
> release the spin lock regularly.

Agreed. v5 will turn the lock-dropping loop in rcu_tasks_postscan()
into a helper that takes a callback, with one cursor per user, and
drop the snapshot array. The livepatch steps will not deduplicate
against the task list anymore, so they do not need to walk the exit
lists under tasklist_lock, and the lock can be dropped during the
walk.

v5 will also handle a failed schedule_on_each_cpu() rather than assume
it succeeds, and I will check the recursive-fault path in
make_task_dead(), which skips the normal exit.

Thanks,
Binoy


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH v4 2/3] livepatch: Include exiting tasks in the transition
  2026-11-27 16:10   ` Petr Mladek
@ 2026-11-27 19:30     ` Ravindran, Binoy
  0 siblings, 0 replies; 14+ messages in thread
From: Ravindran, Binoy @ 2026-11-27 19:30 UTC (permalink / raw)
  To: Petr Mladek
  Cc: Paul E. McKenney, Frederic Weisbecker, Neeraj Upadhyay,
	Joel Fernandes, Josh Triplett, Boqun Feng, Uladzislau Rezki,
	Steven Rostedt, Mathieu Desnoyers, Lai Jiangshan, Zqiang,
	Josh Poimboeuf, Miroslav Benes, Joe Lawrence, Song Liu,
	Ingo Molnar, Jiri Kosina, rcu, linux-kernel, live-patching,
	Yafang Shao, Shastri, Jaidev


Hi Petr,

Thank you for the careful review.

> I would use [1] to reference the discussion, see below.
> ...
> It might be better to mention here the mail where the discussion
> about livepatching do_exit() started.

Will do, with the paragraph breaks you suggest.

> Instead, I would write something like: "skip tasks which are still
> accessible via the for_each_process_thread() walk, so that each
> task is visited only once."

Agreed, sorry for the confusing term. But see the next point: v5 will
not need the check at all.

> BTW: Would it hurt to process the same task twice?

No. Each callback is idempotent. Setting the same patch_state twice,
or setting or clearing TIF_PATCH_PENDING twice, changes nothing. A
second klp_update_patch_state() finds the flag already cleared, and
klp_try_switch_task() returns early for a task that has already
switched. So v5 drops the pid_alive() check, together with the
dependence on tasklist_lock and __unhash_process() that you found
tricky.

Coverage does not depend on it. A task is added to the exit list in
exit_tasks_rcu_start(), before exit_notify() removes it from the task
list. So a walk of the task list followed by a walk of the exit lists
misses no task. A task that leaves the exit list before the second
walk is covered by the wait.

> Assisted-by: Claude:claude-opus-5-5
>
> This is not needed.

OK, I will drop it.

> So, rename:
>
>   + klp_exiting_init     -> klp_exit_task_init_transition
>   + klp_exiting_start    -> klp_exit_task_start_transition
>   + klp_exiting_complete -> klp_exit_task_complete_transition

Will do, with klp_exit_task_reverse_transition and
klp_exit_task_force_transition for the other two.

> I would be more precise. I suggest something like:

Thanks, I will use your text, with the synchronize_rcu() note in a
separate paragraph.

> BTW: Do we need it in all situations, for example, when the 1st
>      livepatch gets enabled? In this case, nothing is removed.

No. It is needed only when code can go away afterwards: when the
target state is KLP_UNPATCHED, or when the patch replaces others. I
can call it only in those cases, with a comment that says why. Or I
can keep it unconditional for simplicity, if you prefer.

> Hmm, I would move this up, above the comment: "/* Done!  Now cleanup
> the data structures. */".
> ...
> Or is there any reason why it is done here?

No reason. I will move it.

> Why exactly do we need the synchronization here, please?

It is about the check in klp_ftrace_handler(), as you say. Once
func->transition is set, the handler reads current->patch_state and
warns if it is KLP_TRANSITION_IDLE. A task that has already left the
exit lists is not visited by klp_init_transition(), so its state is
still IDLE. If it then calls one of the functions you listed, it hits
that warning. The wait makes sure all such tasks are gone before
func->transition is set.

> But wait! If this is the problem then we might need to call
> klp_synchronize_transition() in each stage which calls
> rcu_tasks_visit_exiting().

I think the other stages are already covered. klp_start_transition()
only sets TIF_PATCH_PENDING, which the handler does not read.
klp_reverse_transition() already calls klp_synchronize_transition().
klp_complete_transition() clears func->transition before it sets
patch_state to IDLE, and the handler reads patch_state only while
func->transition is set. klp_force_transition() gives up the
consistency check by design. I will spell this out in the comment.

> PS: It is an amazing work for a newcomer.

Thank you, that is very kind.

Thanks,
Binoy





^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists
  2026-11-26 16:41 ` [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists Binoy Ravindran via B4 Relay
  2026-11-26 18:52   ` Petr Mladek
@ 2026-11-30 17:42   ` Paul E. McKenney
  2026-11-30 18:17     ` Ravindran, Binoy
  1 sibling, 1 reply; 14+ messages in thread
From: Paul E. McKenney @ 2026-11-30 17:42 UTC (permalink / raw)
  To: binoy
  Cc: Frederic Weisbecker, Neeraj Upadhyay, Joel Fernandes,
	Josh Triplett, Boqun Feng, Uladzislau Rezki, Steven Rostedt,
	Mathieu Desnoyers, Lai Jiangshan, Zqiang, Josh Poimboeuf,
	Miroslav Benes, Petr Mladek, Joe Lawrence, Song Liu, Ingo Molnar,
	Jiri Kosina, rcu, linux-kernel, live-patching, Yafang Shao,
	Jaidev Shastri

On Thu, Nov 26, 2026 at 11:41:32AM -0500, Binoy Ravindran via B4 Relay wrote:
> From: Binoy Ravindran <binoy@vt.edu>
> 
> A task joins its CPU's RCU-tasks exit list in exit_tasks_rcu_start(),
> before exit_notify() unhashes it from the task list, and leaves it in
> exit_tasks_rcu_finish(), after do_exit() has disabled preemption for the
> final switch. Once exit_notify() has unhashed it, the task is no longer
> found by for_each_process_thread(), but it still runs do_exit() and may
> sleep there. Code that must reach every task that can still be
> descheduled, such as the livepatch transition, has no way to find it.
> 
> Add two helpers. rcu_tasks_visit_exiting() calls a function on each
> task on the exit lists under the list locks, without allocating.
> rcu_tasks_snapshot_exiting() copies the tasks into a caller-supplied
> array with a reference held on each, for callers that must sleep or take
> other locks while examining them. Without CONFIG_TASKS_RCU there are no
> exit lists, and the helpers do nothing.
> 
> rcu_tasks_postscan() keeps its place in an exit list with a bare
> list_head while it drops the lock to reschedule, relying on nobody else
> traversing the list. Move that cursor into struct rcu_tasks_percpu,
> next to the list it marks, so that the new helpers can recognize and
> skip it. Only the grace-period kthread runs postscan, one CPU's list at
> a time, so one cursor per CPU suffices.
> 
> Assisted-by: Claude:claude-opus-5-5
> Signed-off-by: Binoy Ravindran <binoy@vt.edu>

OK, I will bite...

Why not simply invoke synchronize_rcu_tasks(), after which any of the
tasks that were missed will have already exited?

							Thanx, Paul

> ---
>  include/linux/rcupdate.h |  9 +++++++
>  kernel/rcu/tasks.h       | 69 +++++++++++++++++++++++++++++++++++++++++++-----
>  2 files changed, 72 insertions(+), 6 deletions(-)
> 
> diff --git a/include/linux/rcupdate.h b/include/linux/rcupdate.h
> index 3f74ae6d6e1f..55b8b4a0fa94 100644
> --- a/include/linux/rcupdate.h
> +++ b/include/linux/rcupdate.h
> @@ -214,6 +214,15 @@ static inline void exit_tasks_rcu_start(void) { }
>  static inline void exit_tasks_rcu_finish(void) { }
>  #endif /* #else #ifdef CONFIG_TASKS_RCU_GENERIC */
>  
> +typedef void (*rcu_tasks_exiting_fn_t)(struct task_struct *t, void *arg);
> +#ifdef CONFIG_TASKS_RCU
> +void rcu_tasks_visit_exiting(rcu_tasks_exiting_fn_t fn, void *arg);
> +int rcu_tasks_snapshot_exiting(struct task_struct **buf, int max);
> +#else
> +static inline void rcu_tasks_visit_exiting(rcu_tasks_exiting_fn_t fn, void *arg) { }
> +static inline int rcu_tasks_snapshot_exiting(struct task_struct **buf, int max) { return 0; }
> +#endif
> +
>  /**
>   * cond_resched_tasks_rcu_qs - Report potential quiescent states to RCU
>   *
> diff --git a/kernel/rcu/tasks.h b/kernel/rcu/tasks.h
> index fcac7361ec51..b5fa5a3a8503 100644
> --- a/kernel/rcu/tasks.h
> +++ b/kernel/rcu/tasks.h
> @@ -33,6 +33,8 @@ typedef void (*postgp_func_t)(struct rcu_tasks *rtp);
>   * @barrier_q_head: RCU callback for barrier operation.
>   * @rtp_blkd_tasks: List of tasks blocked as readers.
>   * @rtp_exit_list: List of tasks in the latter portion of do_exit().
> + * @rtp_exit_cursor: Placeholder that rcu_tasks_postscan() parks on @rtp_exit_list
> + *	while it drops the lock, so that exit-list walkers can skip it.
>   * @cpu: CPU number corresponding to this entry.
>   * @index: Index of this CPU in rtpcp_array of the rcu_tasks structure.
>   * @rtpp: Pointer to the rcu_tasks structure.
> @@ -49,6 +51,7 @@ struct rcu_tasks_percpu {
>  	struct rcu_head barrier_q_head;
>  	struct list_head rtp_blkd_tasks;
>  	struct list_head rtp_exit_list;
> +	struct list_head rtp_exit_cursor;
>  	int cpu;
>  	int index;
>  	struct rcu_tasks *rtpp;
> @@ -1068,7 +1071,6 @@ static void rcu_tasks_postscan(struct list_head *hop)
>  		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rcu_tasks.rtpcpu, cpu);
>  		struct task_struct *t;
>  		struct task_struct *t1;
> -		struct list_head tmp;
>  
>  		raw_spin_lock_irq_rcu_node(rtpcp);
>  		list_for_each_entry_safe(t, t1, &rtpcp->rtp_exit_list, rcu_tasks_exit_list) {
> @@ -1081,14 +1083,15 @@ static void rcu_tasks_postscan(struct list_head *hop)
>  				continue;
>  
>  			// Keep our place in the list while pausing.
> -			// Nothing else traverses this list, so adding a
> -			// bare list_head is OK.
> -			list_add(&tmp, &t->rcu_tasks_exit_list);
> +			// The cursor lives in rtpcp so that the exit-list
> +			// visitors can recognize and skip it.
> +			list_add(&rtpcp->rtp_exit_cursor, &t->rcu_tasks_exit_list);
>  			raw_spin_unlock_irq_rcu_node(rtpcp);
>  			cond_resched(); // For CONFIG_PREEMPT=n kernels
>  			raw_spin_lock_irq_rcu_node(rtpcp);
> -			t1 = list_entry(tmp.next, struct task_struct, rcu_tasks_exit_list);
> -			list_del(&tmp);
> +			t1 = list_entry(rtpcp->rtp_exit_cursor.next, struct task_struct,
> +					rcu_tasks_exit_list);
> +			list_del(&rtpcp->rtp_exit_cursor);
>  			j = jiffies + 1;
>  		}
>  		raw_spin_unlock_irq_rcu_node(rtpcp);
> @@ -1332,6 +1335,60 @@ void exit_tasks_rcu_finish(void)
>  	raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
>  }
>  
> +/*
> + * Call fn on every task on the exit lists, in place, with the per-CPU list
> + * lock held and interrupts disabled. fn must not sleep. Does not allocate.
> + * These are the tasks that have passed exit_tasks_rcu_start() but not
> + * exit_tasks_rcu_finish(). Once exit_notify() has run they are no longer on
> + * the task list, but they still run do_exit() and may sleep there.
> + */
> +void rcu_tasks_visit_exiting(rcu_tasks_exiting_fn_t fn, void *arg)
> +{
> +	int cpu;
> +	unsigned long flags;
> +	struct task_struct *t;
> +
> +	for_each_possible_cpu(cpu) {
> +		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rcu_tasks.rtpcpu, cpu);
> +
> +		raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
> +		list_for_each_entry(t, &rtpcp->rtp_exit_list, rcu_tasks_exit_list) {
> +			if (&t->rcu_tasks_exit_list == &rtpcp->rtp_exit_cursor)
> +				continue;
> +			fn(t, arg);
> +		}
> +		raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
> +	}
> +}
> +
> +/*
> + * Copy up to max tasks on the exit lists into buf, taking a reference on
> + * each. Returns the number of tasks on the lists, which may exceed max.
> + */
> +int rcu_tasks_snapshot_exiting(struct task_struct **buf, int max)
> +{
> +	int cpu, n = 0;
> +	unsigned long flags;
> +	struct task_struct *t;
> +
> +	for_each_possible_cpu(cpu) {
> +		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rcu_tasks.rtpcpu, cpu);
> +
> +		raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
> +		list_for_each_entry(t, &rtpcp->rtp_exit_list, rcu_tasks_exit_list) {
> +			if (&t->rcu_tasks_exit_list == &rtpcp->rtp_exit_cursor)
> +				continue;
> +			if (n < max) {
> +				get_task_struct(t);
> +				buf[n] = t;
> +			}
> +			n++;
> +		}
> +		raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
> +	}
> +	return n;
> +}
> +
>  #else /* #ifdef CONFIG_TASKS_RCU */
>  void exit_tasks_rcu_start(void) { }
>  void exit_tasks_rcu_finish(void) { }
> 
> -- 
> 2.39.5
> 
> 

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists
  2026-11-30 17:42   ` Paul E. McKenney
@ 2026-11-30 18:17     ` Ravindran, Binoy
  2026-11-30 19:55       ` Paul E. McKenney
  0 siblings, 1 reply; 14+ messages in thread
From: Ravindran, Binoy @ 2026-11-30 18:17 UTC (permalink / raw)
  To: paulmck
  Cc: Frederic Weisbecker, Neeraj Upadhyay, Joel Fernandes,
	Josh Triplett, Boqun Feng, Uladzislau Rezki, Steven Rostedt,
	Mathieu Desnoyers, Lai Jiangshan, Zqiang, Josh Poimboeuf,
	Miroslav Benes, Petr Mladek, Joe Lawrence, Song Liu, Ingo Molnar,
	Jiri Kosina, rcu, linux-kernel, live-patching, Yafang Shao,
	Shastri, Jaidev


On Mon, Nov 30, 2026, Paul E. McKenney wrote:
> OK, I will bite...
>
> Why not simply invoke synchronize_rcu_tasks(), after which any of the
> tasks that were missed will have already exited?

That was our first attempt, and it is not enough, for two reasons.

First, the task we miss can be in a quiescent state as far as RCU Tasks
is concerned. It is sleeping voluntarily in do_exit() after
exit_notify(), with a return address into the old patch's code on its
stack. A voluntary context switch is an RCU Tasks quiescent state, and
check_holdout_task() drops a holdout as soon as its nvcsw has changed,
so the grace period can end while the task is still asleep there. When
it wakes, it returns into freed text. With synchronize_rcu_tasks()
before the free of the replaced patch and a 2 s sleep injected after
exit_notify(), 5 of 6 runs still crashed.

Second, the problem is not only the free. The transition must not
switch a task while one of its frames is in a function being patched.
The invisible task is never checked, so klp_try_complete_transition()
can finish while the task still runs the old function, and the
consistency model is broken whether or not anything is freed. A wait
at free cannot repair that, since it runs after the transition has
already completed.

So the transition itself has to see these tasks and check their
stacks, which is what the rest of this series does. In v5, which I
plan to post this week, the two helpers in this patch are replaced by
a single walk of the exit lists that can drop the list lock, using the
same cursor scheme as rcu_tasks_postscan(). If you would prefer a
different interface on the RCU side, I am happy to rework it.

Thanks,
Binoy


^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists
  2026-11-30 18:17     ` Ravindran, Binoy
@ 2026-11-30 19:55       ` Paul E. McKenney
  2026-12-01  0:29         ` Ravindran, Binoy
  0 siblings, 1 reply; 14+ messages in thread
From: Paul E. McKenney @ 2026-11-30 19:55 UTC (permalink / raw)
  To: Ravindran, Binoy
  Cc: Frederic Weisbecker, Neeraj Upadhyay, Joel Fernandes,
	Josh Triplett, Boqun Feng, Uladzislau Rezki, Steven Rostedt,
	Mathieu Desnoyers, Lai Jiangshan, Zqiang, Josh Poimboeuf,
	Miroslav Benes, Petr Mladek, Joe Lawrence, Song Liu, Ingo Molnar,
	Jiri Kosina, rcu, linux-kernel, live-patching, Yafang Shao,
	Shastri, Jaidev

On Mon, Nov 30, 2026 at 06:17:41PM +0000, Ravindran, Binoy wrote:
> 
> On Mon, Nov 30, 2026, Paul E. McKenney wrote:
> > OK, I will bite...
> >
> > Why not simply invoke synchronize_rcu_tasks(), after which any of the
> > tasks that were missed will have already exited?
> 
> That was our first attempt, and it is not enough, for two reasons.
> 
> First, the task we miss can be in a quiescent state as far as RCU Tasks
> is concerned. It is sleeping voluntarily in do_exit() after
> exit_notify(), with a return address into the old patch's code on its
> stack. A voluntary context switch is an RCU Tasks quiescent state, and
> check_holdout_task() drops a holdout as soon as its nvcsw has changed,
> so the grace period can end while the task is still asleep there. When
> it wakes, it returns into freed text. With synchronize_rcu_tasks()
> before the free of the replaced patch and a 2 s sleep injected after
> exit_notify(), 5 of 6 runs still crashed.
> 
> Second, the problem is not only the free. The transition must not
> switch a task while one of its frames is in a function being patched.
> The invisible task is never checked, so klp_try_complete_transition()
> can finish while the task still runs the old function, and the
> consistency model is broken whether or not anything is freed. A wait
> at free cannot repair that, since it runs after the transition has
> already completed.
> 
> So the transition itself has to see these tasks and check their
> stacks, which is what the rest of this series does. In v5, which I
> plan to post this week, the two helpers in this patch are replaced by
> a single walk of the exit lists that can drop the list lock, using the
> same cursor scheme as rcu_tasks_postscan(). If you would prefer a
> different interface on the RCU side, I am happy to rework it.

I suspect that we are talking past each other.  ;-)

I am *not* suggesting replacing your overall algorithm with a single
call to synchronize_rcu_tasks(), just the piece of it that uses the
RCU-Tasks helper functions.

I instead suggest keeping your overall algorithm, including your walk
of the tasks list, and replacing the call to your Tasks-RCU helper
function with synchronize_rcu_tasks().  This does not wait for tasks
with preemption disabled that are working towards their last call
to schedule(), but those can be handled with a subsequent call to
synchronize_rcu_tasks_rude().

Does that make sense, or am I still missing something?

							Thanx, Paul

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists
  2026-11-30 19:55       ` Paul E. McKenney
@ 2026-12-01  0:29         ` Ravindran, Binoy
  2026-12-01  1:24           ` Paul E. McKenney
  0 siblings, 1 reply; 14+ messages in thread
From: Ravindran, Binoy @ 2026-12-01  0:29 UTC (permalink / raw)
  To: paulmck
  Cc: Frederic Weisbecker, Neeraj Upadhyay, Joel Fernandes,
	Josh Triplett, Boqun Feng, Uladzislau Rezki, Steven Rostedt,
	Mathieu Desnoyers, Lai Jiangshan, Zqiang, Josh Poimboeuf,
	Miroslav Benes, Petr Mladek, Joe Lawrence, Song Liu, Ingo Molnar,
	Jiri Kosina, rcu, linux-kernel, live-patching, Yafang Shao,
	Shastri, Jaidev


On Mon, Nov 30, 2026, Paul E. McKenney wrote:
> I instead suggest keeping your overall algorithm, including your walk
> of the tasks list, and replacing the call to your Tasks-RCU helper
> function with synchronize_rcu_tasks().  This does not wait for tasks
> with preemption disabled that are working towards their last call
> to schedule(), but those can be handled with a subsequent call to
> synchronize_rcu_tasks_rude().

Thanks, and sorry for misreading your first question. I see what you
mean now, and I tried the core of it.

The test kernel is v7.4-rc2 with that change and nothing else from our
series. The transition walks the task list as before, and it does not
walk the exit lists. Once every task it finds has switched,
klp_try_complete_transition() calls synchronize_rcu_tasks() and then
synchronize_rcu_tasks_rude(), just before the cleanup.

To trigger the race, a test-only hook makes exiting tasks sleep after
exit_notify(). Two livepatches that both replace do_exit() replace
each other in a loop, and the old module is removed each time.

With a 2 s sleep, all 12 runs crashed. In every run, an exiting task
woke up and went back into memory that the removed module had used.
That memory was unmapped, filled with int3 after the free, or already
holding the next module's code.

With a 20 ms sleep, all 12 runs finished their cycles, 120 in all,
without a fault. Without the two waits, the same 20 ms test crashed in
11 of 12 runs.

So the waits only delay the cleanup. A short sleep can end in time,
but a long one does not. The reason is that a task asleep in do_exit()
after exit_notify() is in an RCU Tasks quiescent state, so the grace
period does not wait for it. The rude flavor does not help either,
because it does not cover a sleeping task.

That is why the series has the transition find these tasks on the
exit lists and check their stacks, as it does for every other task.

Thanks,
Binoy



^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists
  2026-12-01  0:29         ` Ravindran, Binoy
@ 2026-12-01  1:24           ` Paul E. McKenney
  2026-12-02  6:16             ` Ravindran, Binoy
  0 siblings, 1 reply; 14+ messages in thread
From: Paul E. McKenney @ 2026-12-01  1:24 UTC (permalink / raw)
  To: Ravindran, Binoy
  Cc: Frederic Weisbecker, Neeraj Upadhyay, Joel Fernandes,
	Josh Triplett, Boqun Feng, Uladzislau Rezki, Steven Rostedt,
	Mathieu Desnoyers, Lai Jiangshan, Zqiang, Josh Poimboeuf,
	Miroslav Benes, Petr Mladek, Joe Lawrence, Song Liu, Ingo Molnar,
	Jiri Kosina, rcu, linux-kernel, live-patching, Yafang Shao,
	Shastri, Jaidev

On Tue, Dec 01, 2026 at 12:29:12AM +0000, Ravindran, Binoy wrote:
> 
> On Mon, Nov 30, 2026, Paul E. McKenney wrote:
> > I instead suggest keeping your overall algorithm, including your walk
> > of the tasks list, and replacing the call to your Tasks-RCU helper
> > function with synchronize_rcu_tasks().  This does not wait for tasks
> > with preemption disabled that are working towards their last call
> > to schedule(), but those can be handled with a subsequent call to
> > synchronize_rcu_tasks_rude().
> 
> Thanks, and sorry for misreading your first question. I see what you
> mean now, and I tried the core of it.
> 
> The test kernel is v7.4-rc2 with that change and nothing else from our
> series. The transition walks the task list as before, and it does not
> walk the exit lists. Once every task it finds has switched,
> klp_try_complete_transition() calls synchronize_rcu_tasks() and then
> synchronize_rcu_tasks_rude(), just before the cleanup.
> 
> To trigger the race, a test-only hook makes exiting tasks sleep after
> exit_notify(). Two livepatches that both replace do_exit() replace
> each other in a loop, and the old module is removed each time.
> 
> With a 2 s sleep, all 12 runs crashed. In every run, an exiting task
> woke up and went back into memory that the removed module had used.
> That memory was unmapped, filled with int3 after the free, or already
> holding the next module's code.
> 
> With a 20 ms sleep, all 12 runs finished their cycles, 120 in all,
> without a fault. Without the two waits, the same 20 ms test crashed in
> 11 of 12 runs.
> 
> So the waits only delay the cleanup. A short sleep can end in time,
> but a long one does not. The reason is that a task asleep in do_exit()
> after exit_notify() is in an RCU Tasks quiescent state, so the grace
> period does not wait for it. The rude flavor does not help either,
> because it does not cover a sleeping task.
> 
> That is why the series has the transition find these tasks on the
> exit lists and check their stacks, as it does for every other task.

Thank you for trying this out.

And part of my problem was that I was remembering the old versions
of exit_tasks_rcu_start() and exit_tasks_rcu_finish(), for example,
from Linux kernel v6.0.  In these old versions, exit_tasks_rcu_start()
entered an SRCU read-side critical section, exit_tasks_rcu_finish()
exited it, and rcu_tasks_postscan() did synchronize_srcu().

Apologies for my confusion, but so many RCU versions!  ;-)

Would it work to add those __srcu_read_lock() and __srcu_read_unlock()
calls to exit_tasks_rcu_start() and exit_tasks_rcu_finish(),
respectively, then have your code do synchronize_srcu() instead of
synchronize_rcu_tasks(), presumably by invoking a helper function in
kernel/rcu/tasks.h?

Some thought and/or experiment maybe required to come up with the optimal
variant of __srcu_read_lock() and __srcu_read_unlock(), but those are
good places to start.

This assumes that your code would not be holding mutexes across my
proposed synchronize_srcu() that are also acquired by do_exit() between
its calls to exit_tasks_rcu_start() and exit_tasks_rcu_finish().  See
here for more details:

1612160b9127 ("rcu-tasks: Eliminate deadlocks involving do_exit() and RCU tasks")

If your code does need to hold such mutexes, back to the drawing board.

							Thanx, Paul

^ permalink raw reply	[flat|nested] 14+ messages in thread

* Re: [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists
  2026-12-01  1:24           ` Paul E. McKenney
@ 2026-12-02  6:16             ` Ravindran, Binoy
  0 siblings, 0 replies; 14+ messages in thread
From: Ravindran, Binoy @ 2026-12-02  6:16 UTC (permalink / raw)
  To: paulmck
  Cc: Frederic Weisbecker, Neeraj Upadhyay, Joel Fernandes,
	Josh Triplett, Boqun Feng, Uladzislau Rezki, Steven Rostedt,
	Mathieu Desnoyers, Lai Jiangshan, Zqiang, Josh Poimboeuf,
	Miroslav Benes, Petr Mladek, Joe Lawrence, Song Liu, Ingo Molnar,
	Jiri Kosina, rcu, linux-kernel, live-patching, Yafang Shao,
	Shastri, Jaidev


On Mon, Nov 30, 2026, Paul E. McKenney wrote:
> Apologies for my confusion, but so many RCU versions!  ;-)

No apology needed, and thank you.

> Would it work to add those __srcu_read_lock() and __srcu_read_unlock()
> calls to exit_tasks_rcu_start() and exit_tasks_rcu_finish(),
> respectively, then have your code do synchronize_srcu() instead of
> synchronize_rcu_tasks(), presumably by invoking a helper function in
> kernel/rcu/tasks.h?

Yes, it works in our tests.

I built it on v7.4-rc2 with our series. exit_tasks_rcu_start() enters an
SRCU read-side critical section on a static SRCU domain, and keeps the
index in a new task_struct field. exit_tasks_rcu_finish() leaves it. A
helper in kernel/rcu/tasks.h calls synchronize_srcu().
klp_try_complete_transition() calls it after every task on the task
list has switched, before the cleanup.

> Some thought and/or experiment maybe required to come up with the optimal
> variant of __srcu_read_lock() and __srcu_read_unlock(), but those are
> good places to start.

I used plain __srcu_read_lock() and __srcu_read_unlock(). I have not
tried other variants yet.

> This assumes that your code would not be holding mutexes across my
> proposed synchronize_srcu() that are also acquired by do_exit() between
> its calls to exit_tasks_rcu_start() and exit_tasks_rcu_finish().  See
> here for more details:
>
> 1612160b9127 ("rcu-tasks: Eliminate deadlocks involving do_exit() and RCU tasks")
>
> If your code does need to hold such mutexes, back to the drawing board.

Our code does hold klp_mutex across synchronize_srcu(). I checked
against 1612160b9127, and as far as I can see, nothing between
exit_tasks_rcu_start() and exit_tasks_rcu_finish() takes klp_mutex. No
test deadlocked.

The test is the same as before. A test-only hook makes exiting tasks
sleep after exit_notify(), and two livepatches that both replace
do_exit() replace each other in a loop.

Safety: 120 runs and 1,440 cycles, with no sleep and with sleeps from
20 ms to 2 s, had no crash. 42 of those runs used your SRCU change
without our exit-list walks, and they also had no warnings. I did not
test forced transitions with SRCU.

Lockdep: I ran three kernels under PROVE_LOCKING, PROVE_RCU and
DEBUG_ATOMIC_SLEEP: your SRCU change without our walks, your SRCU
change with the rest of our series, and our current series. Each
kernel ran 16 runs, with a 2 s sleep, a 200 ms sleep and no sleep.
There were no lockdep or sleep-in-atomic reports, no hung tasks and no
crashes. The only warning was the reschedule IPI warning at
arch/x86/kernel/apic/ipi.c:71, which we also see without either change.

Latency: here the two designs differ. The SRCU wait covers every task
in the exit window, even one that never runs patched code. Our walk
waits only for exiting tasks that still run patched code. To show this,
I used two livepatches that change getpid(), so no exiting task runs
patched code. Transition times, from "starting patching transition" to
"patching complete", as p90 / p99, from 36 runs per exit sleep (18 for
no sleep):

  no sleep:  our walk 1.68 / 1.79 s,  SRCU 1.68 / 1.78 s
  500 ms:    our walk 1.73 / 1.84 s,  SRCU 1.89 / 2.26 s
  1 s:       our walk 1.75 / 1.91 s,  SRCU 2.48 / 2.80 s
  2 s:       our walk 1.84 / 2.03 s,  SRCU 3.60 / 3.86 s

Both designs retry the transition once a second, which accounts for
most of the time with no sleep.

With no injected sleep, I also ran 24 runs per design while the guests
tore down PID namespaces, about 430,000 for each design. The p99 was
1.78 s with our walk and 1.76 s with SRCU. The longest transition was
1.94 s with our walk and 3.97 s with SRCU.

Slow exits do happen without an injected sleep. We traced exits while
PID namespaces were torn down in a loop. The longest voluntary sleep in
the exit window was 146 ms on an arm64 host and 2 ms on an x86-64 host.
Every voluntary sleep of 1 ms or more was a namespace's init waiting
for its children.

So in these runs, SRCU cost little when no exit was slow, and it added
the length of a slow exit when there was one. It is also simpler and
needs no new walker interface on the RCU side. Which would you and the
livepatch maintainers prefer? I am happy to rework the series around
SRCU if that is the better fit.

Thanks,
Binoy



^ permalink raw reply	[flat|nested] 14+ messages in thread

end of thread, other threads:[~2026-12-02  6:16 UTC | newest]

Thread overview: 14+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-26 16:41 [PATCH v4 0/3] livepatch: Do not lose exiting tasks during a transition Binoy Ravindran via B4 Relay
2026-11-26 16:41 ` [PATCH v4 1/3] rcu-tasks: Add helpers to visit tasks on the exit lists Binoy Ravindran via B4 Relay
2026-11-26 18:52   ` Petr Mladek
2026-11-27 18:56     ` Ravindran, Binoy
2026-11-30 17:42   ` Paul E. McKenney
2026-11-30 18:17     ` Ravindran, Binoy
2026-11-30 19:55       ` Paul E. McKenney
2026-12-01  0:29         ` Ravindran, Binoy
2026-12-01  1:24           ` Paul E. McKenney
2026-12-02  6:16             ` Ravindran, Binoy
2026-11-26 16:41 ` [PATCH v4 2/3] livepatch: Include exiting tasks in the transition Binoy Ravindran via B4 Relay
2026-11-27 16:10   ` Petr Mladek
2026-11-27 19:30     ` Ravindran, Binoy
2026-11-26 16:41 ` [PATCH v4 3/3] livepatch: Select TASKS_RCU Binoy Ravindran via B4 Relay

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®