Skip to contentSkip to conversation

kcsan: Avoid scheduler recursion by using non-instrumented preempt_disable()

PATCH Superseded Marco Elver 1 participant 1 message Nov 17, 2020 KCSAN

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Marco Elver

author maintainer
#0 lore raw

PATCH 1/1 kcsan: Avoid scheduler recursion by using non-instrumented preempt_disable()

When enabling KCSAN for kernel/sched (remove KCSAN_SANITIZE := n from kernel/sched/Makefile), with CONFIG_DEBUG_PREEMPT=y, we can observe recursion due to:

check_access() [via instrumentation]
kcsan_setup_watchpoint()
reset_kcsan_skip()
kcsan_prandom_u32_max()
get_cpu_var()
preempt_disable()
preempt_count_add() [in kernel/sched/core.c]
check_access() [via instrumentation]

Avoid this by rewriting kcsan_prandom_u32_max() to only use safe versions of preempt_disable() that do not call into scheduler code.

Note, while this currently does not affect an unmodified kernel, it'd be good to keep a KCSAN kernel working when KCSAN_SANITIZE := n is removed from kernel/sched/Makefile to permit testing scheduler code with KCSAN if desired.

Fixes cd290ec24633 ("kcsan: Use tracing-safe version of prandom")
---
 kernel/kcsan/core.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)
kernel/kcsan/core.c +11 -3
index 3994a217bde7..967b0b2f9d59 100644
@@ -284,10 +284,18 @@ should_watch(const volatile void *ptr, size_t size, int type, struct kcsan_ctx *
  */
 static u32 kcsan_prandom_u32_max(u32 ep_ro)
 {
-	struct rnd_state *state = &get_cpu_var(kcsan_rand_state);
-	const u32 res = prandom_u32_state(state);
+	struct rnd_state *state;
+	u32 res;
+
+	/*
+	 * Avoid recursion with scheduler by using non-tracing version of
+	 * preempt_disable() that do not call into scheduler code.
+	 */
+	preempt_disable_notrace();
+	state = raw_cpu_ptr(&kcsan_rand_state);
+	res = prandom_u32_state(state);
+	preempt_enable_no_resched_notrace();
 
-	put_cpu_var(kcsan_rand_state);
 	return (u32)(((u64) res * ep_ro) >> 32);
 }
 
Signature · 1 line
2.29.2.299.gdc1121823c-goog