[patch 19/38] kcsan: Replace get_cycles() usage

Thomas Gleixner
2026-04-10T12:20:53Z

KCSAN uses get_cycles() for two purposes:

1) Seeding the random state with get_cycles() is a historical leftover.

2) The microbenchmark uses get_cycles(), which provides an unit less
counter value and is not guaranteed to be functional on all
systems/platforms.

Use random_get_entropy() for seeding the random state and ktime_get() which
is universaly functional and provides at least a comprehensible unit.

This is part of a larger effort to remove get_cycles() usage from
non-architecture code.

Signed-off-by: Thomas Gleixner <tglx@kernel.org>
Cc: Marco Elver <elver@google.com>
Cc: Dmitry Vyukov <dvyukov@google.com>
Cc: kasan-dev@googlegroups.com
---
kernel/kcsan/core.c | 2 +-
kernel/kcsan/debugfs.c | 8 ++++----
2 files changed, 5 insertions(+), 5 deletions(-)

--- a/kernel/kcsan/core.c
+++ b/kernel/kcsan/core.c
@@ -798,7 +798,7 @@ void __init kcsan_init(void)
BUG_ON(!in_task());

for_each_possible_cpu(cpu)
- per_cpu(kcsan_rand_state, cpu) = (u32)get_cycles();
+ per_cpu(kcsan_rand_state, cpu) = (u32)random_get_entropy();

/*
* We are in the init task, and no other tasks should be running;
--- a/kernel/kcsan/debugfs.c
+++ b/kernel/kcsan/debugfs.c
@@ -58,7 +58,7 @@ static noinline void microbenchmark(unsi
{
const struct kcsan_ctx ctx_save = current->kcsan_ctx;
const bool was_enabled = READ_ONCE(kcsan_enabled);
- u64 cycles;
+ ktime_t nsecs;

/* We may have been called from an atomic region; reset context. */
memset(&current->kcsan_ctx, 0, sizeof(current->kcsan_ctx));
@@ -70,16 +70,16 @@ static noinline void microbenchmark(unsi

pr_info("%s begin | iters: %lu\n", __func__, iters);

- cycles = get_cycles();
+ nsecs = ktime_get();
while (iters--) {
unsigned long addr = iters & ((PAGE_SIZE << 8) - 1);
int type = !(iters & 0x7f) ? KCSAN_ACCESS_ATOMIC :
(!(iters & 0xf) ? KCSAN_ACCESS_WRITE : 0);
__kcsan_check_access((void *)addr, sizeof(long), type);
}
- cycles = get_cycles() - cycles;
+ nsecs = ktime_get() - nsecs;

- pr_info("%s end | cycles: %llu\n", __func__, cycles);
+ pr_info("%s end | nsecs: %llu\n", __func__, nsecs);

WRITE_ONCE(kcsan_enabled, was_enabled);
/* restore context */