[RFC PATCH 01/26] perf/core: Fix lockless time read for exclude_guest events

From: Yosry Ahmed

Date: Mon Nov 23 2026 - 19:23:17 EST


When a host perf event has exclude_guest=1, its elapsed time should
exclude guest time. However, lockless time reads through
__perf_event_time_ctx_now() only subtracts guest time while a guest
context is loaded, unlike __perf_event_time_ctx(). As a result,
time_enabled and time_running read locklessly include past guest time
after the guest context is put.

Subtract guest time regardless of whether a guest context is loaded. Guest
time does not advance while no guest context is loaded, so use the
accumulated guest time in that case.

Undo a minor optimization that avoids adding and subtracting 'now' while a
guest context is loaded, to make it clearer that guest time is always
subtracted, and only how it's calculated depends on whether a guest
context is loaded.

Fixes: 4593b4b6e218 ("perf: Add a EVENT_GUEST flag")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Yosry Ahmed <yosry@xxxxxxxxxx>
---
kernel/events/core.c | 20 ++++++++++++--------
1 file changed, 12 insertions(+), 8 deletions(-)

diff --git a/kernel/events/core.c b/kernel/events/core.c
index f5f2261f1fe6f..6f076e5483cb7 100644
--- a/kernel/events/core.c
+++ b/kernel/events/core.c
@@ -850,7 +850,7 @@ static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum e
static inline void update_perf_time_ctx(struct perf_time_ctx *time, u64 now, bool adv)
{
if (adv)
- time->time += now - time->stamp;
+ WRITE_ONCE(time->time, time->time + now - time->stamp);
time->stamp = now;

/*
@@ -887,15 +887,19 @@ static inline u64 __perf_event_time_ctx_now(struct perf_event *event,
struct perf_time_ctx *times,
u64 now)
{
- if (is_guest_mediated_pmu_loaded() && event->attr.exclude_guest) {
- /*
- * (now + times[total].offset) - (now + times[guest].offset) :=
- * times[total].offset - times[guest].offset
- */
- return READ_ONCE(times[T_TOTAL].offset) - READ_ONCE(times[T_GUEST].offset);
+ u64 time = now + READ_ONCE(times[T_TOTAL].offset);
+ u64 guest_time;
+
+ if (event->attr.exclude_guest) {
+ if (is_guest_mediated_pmu_loaded())
+ guest_time = now + READ_ONCE(times[T_GUEST].offset);
+ else
+ guest_time = READ_ONCE(times[T_GUEST].time);
+
+ time -= guest_time;
}

- return now + READ_ONCE(times[T_TOTAL].offset);
+ return time;
}

#ifdef CONFIG_CGROUP_PERF
--
2.56.1.809.ga0b61035b5-goog