[PATCH] perf: Only one Kmem cache for the per-task PMU-specific data

From: kan . liang
Date: Wed Mar 26 2025 - 09:53:51 EST


From: Kan Liang <kan.liang@xxxxxxxxxxxxxxx>

Some PMU-specific data has to be saved/restored during context switch,
e.g. LBR call stack data. The data is saved in the kmem_cache *ctx_cache
of task_struct. However, the current implementation only supports one
user.

There is no problem for now, because the Intel LBR call stack is the
only user. But if other PMUs also want to add a new kmem_cache to save
their specific data later, there must be a bug.

Add a global pointer perf_ctx_cache to save the kmem_cache address of a
PMU for the PMU-specific data. If a later PMU claims a different
address, fail the registration.
(There could be two or more PMUs which share the same kmem_cache
address, e.g., Intel hybrid. So, here can only use the address rather
than the number of PMUs for the check.)

Suggested-by: "Peter Zijlstra (Intel)" <peterz@xxxxxxxxxxxxx>
Signed-off-by: Kan Liang <kan.liang@xxxxxxxxxxxxxxx>
Closes: https://lore.kernel.org/lkml/20250317111045.GA36386@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/
---
kernel/events/core.c | 16 ++++++++++++++++
1 file changed, 16 insertions(+)

diff --git a/kernel/events/core.c b/kernel/events/core.c
index 4ce9795e5519..106fd554fc42 100644
--- a/kernel/events/core.c
+++ b/kernel/events/core.c
@@ -443,6 +443,7 @@ static cpumask_var_t perf_online_cluster_mask;
static cpumask_var_t perf_online_pkg_mask;
static cpumask_var_t perf_online_sys_mask;
static struct kmem_cache *perf_event_cache;
+static struct kmem_cache *perf_ctx_cache;

/*
* perf event paranoia level:
@@ -12189,6 +12190,21 @@ int perf_pmu_register(struct pmu *_pmu, const char *name, int type)
"Can not register a pmu with an invalid scope.\n"))
return -EINVAL;

+ if (pmu->task_ctx_cache) {
+ /*
+ * The PMU-specific data is saved in the Kmem cache
+ * ctx_cache of task_struct. It only supports one
+ * user. Check and fail the registration if there
+ * are more potential users.
+ */
+ if (!perf_ctx_cache)
+ perf_ctx_cache = pmu->task_ctx_cache;
+ if (WARN_ONCE(perf_ctx_cache != pmu->task_ctx_cache,
+ "The PMU-specific buffer of task has been reserved by other PMUs.\n"))
+ return -EINVAL;
+
+ }
+
pmu->name = name;

if (type >= 0)
--
2.38.1