* [RFC PATCH 1/7] sched/cache: Move the cache group lifecycle to cache_sched.c
2026-11-26 13:48 [RFC PATCH 0/7] sched/cache: Introduce per-task affinity group via BPF detector Luo Gengkun
@ 2026-11-26 13:48 ` Luo Gengkun
2026-11-26 13:48 ` [RFC PATCH 2/7] sched/cache: Add thread count to cache group Luo Gengkun
` (5 subsequent siblings)
6 siblings, 0 replies; 8+ messages in thread
From: Luo Gengkun @ 2026-11-26 13:48 UTC (permalink / raw)
To: Peter Zijlstra, Ingo Molnar, Juri Lelli, Vincent Guittot,
Tim Chen, Chen Yu, K Prateek Nayak
Cc: Dietmar Eggemann, Steven Rostedt, Ben Segall, Mel Gorman,
Valentin Schneider, linux-kernel
The cache group's allocation, initialization, and reference lifecycle
currently lives in fair.c inside its CONFIG_SCHED_CACHE block, mixed
in with the wakeup and load balancing code that consumes it.
Move it into its own compilation unit, kernel/sched/cache_sched.c
(built into build_utility.o), to lay the groundwork for the rest of
this series.
The moved code is unchanged except for the allocator, which is split
out of mm_init_sched() as sched_cache_alloc_group() along with its
failure path. Export this constructor via the new
kernel/sched/cache_sched.h, while keeping the responsibility of
publishing the group to the mm inside mm_init_sched(). Also make
sched_cache_group_put() global, as task_cache_work() and
mm_destroy_sched() remain in fair.c and still call it.
No functional change intended.
Signed-off-by: Luo Gengkun <luogengkun@huaweicloud.com>
---
kernel/sched/build_utility.c | 5 ++
kernel/sched/cache_sched.c | 155 +++++++++++++++++++++++++++++++++++
kernel/sched/cache_sched.h | 19 +++++
kernel/sched/fair.c | 133 +-----------------------------
4 files changed, 181 insertions(+), 131 deletions(-)
create mode 100644 kernel/sched/cache_sched.c
create mode 100644 kernel/sched/cache_sched.h
diff --git a/kernel/sched/build_utility.c b/kernel/sched/build_utility.c
index e2cf3b08d4e9..f7ea083de6a3 100644
--- a/kernel/sched/build_utility.c
+++ b/kernel/sched/build_utility.c
@@ -85,6 +85,11 @@
#include "topology.c"
+#ifdef CONFIG_SCHED_CACHE
+# include "cache_sched.h"
+# include "cache_sched.c"
+#endif
+
#ifdef CONFIG_SCHED_CORE
# include "core_sched.c"
#endif
diff --git a/kernel/sched/cache_sched.c b/kernel/sched/cache_sched.c
new file mode 100644
index 000000000000..c20ed59ba45b
--- /dev/null
+++ b/kernel/sched/cache_sched.c
@@ -0,0 +1,155 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include "sched.h"
+
+#define rcu_deref_sched_cache_grp(tsk) \
+ rcu_dereference_check((tsk)->sched_cache_grp, (tsk) == current)
+
+static struct sched_cache_group *sched_cache_replace_grp(struct task_struct *p,
+ struct sched_cache_group *new)
+{
+ struct sched_cache_group *old;
+
+ old = rcu_deref_sched_cache_grp(p);
+ rcu_assign_pointer(p->sched_cache_grp, new);
+
+ return old;
+}
+
+static void sched_cache_group_free_rcu(struct rcu_head *rcu)
+{
+ struct sched_cache_group *grp =
+ container_of(rcu, struct sched_cache_group, rcu);
+
+ free_percpu(grp->pcpu_sched);
+ kfree(grp);
+}
+
+void sched_cache_group_put(struct sched_cache_group *grp)
+{
+ if (!grp || !refcount_dec_and_test(&grp->refcnt))
+ return;
+
+ call_rcu(&grp->rcu, sched_cache_group_free_rcu);
+}
+
+DEFINE_FREE(sched_cache_group_put, struct sched_cache_group *,
+ sched_cache_group_put(_T));
+
+struct sched_cache_group *sched_cache_group_get(struct sched_cache_group *grp)
+{
+ /*
+ * refcount_inc_not_zero() is the acquire primitive for lockless
+ * (RCU) lookups; plain refcount_inc() would scribble the count if
+ * it already reached zero. Return NULL in that case.
+ */
+ if (grp && !refcount_inc_not_zero(&grp->refcnt))
+ grp = NULL;
+
+ return grp;
+}
+
+struct sched_cache_group *task_cache_group_get(struct task_struct *p)
+{
+ guard(rcu)();
+ return sched_cache_group_get(rcu_dereference(p->sched_cache_grp));
+}
+
+void sched_cache_fork(struct task_struct *p)
+{
+ /*
+ * The child takes its own reference on the mm's cache group, separate
+ * from the reference held by the mm. @p is not yet visible to readers,
+ * so a plain initializing store is enough.
+ */
+ RCU_INIT_POINTER(p->sched_cache_grp,
+ sched_cache_group_get(p->mm->sched_cache_grp));
+}
+
+void sched_cache_fork_cleanup(struct task_struct *p)
+{
+ /*
+ * A fork that fails after sched_cache_fork() never reaches exit_mm(),
+ * so drop the reference here. @p never became visible, so there are no
+ * concurrent readers and the reference we hold keeps the group alive.
+ */
+ sched_cache_group_put(rcu_access_pointer(p->sched_cache_grp));
+ RCU_INIT_POINTER(p->sched_cache_grp, NULL);
+}
+
+void sched_cache_exec_mmap(struct task_struct *p, struct mm_struct *mm)
+{
+ struct sched_cache_group *old;
+
+ /*
+ * Acquire the new reference before publishing the pointer, then drop
+ * the old one. @p is current and the only writer of its own pointer.
+ */
+ old = sched_cache_replace_grp(p, sched_cache_group_get(mm->sched_cache_grp));
+ sched_cache_group_put(old);
+}
+
+void sched_cache_exit_mm(struct task_struct *p)
+{
+ struct sched_cache_group *grp = sched_cache_replace_grp(p, NULL);
+
+#ifdef CONFIG_NUMA_BALANCING
+ /*
+ * Subtract this task's footprint from the group before dropping the
+ * reference, so the group footprint converges as its threads exit.
+ * Unlocked for performance; clamp to avoid underflow.
+ */
+ if (grp && p->total_numa_faults) {
+ unsigned long fp = READ_ONCE(grp->footprint);
+ unsigned long sub = min(fp, p->total_numa_faults);
+
+ WRITE_ONCE(grp->footprint, fp - sub);
+ }
+#endif
+ sched_cache_group_put(grp);
+}
+
+static void sched_cache_group_init(struct sched_cache_group *grp,
+ struct sched_cache_time __percpu *_pcpu_sched)
+{
+ unsigned long epoch = 0;
+ int i;
+
+ for_each_possible_cpu(i) {
+ struct sched_cache_time *pcpu_sched = per_cpu_ptr(_pcpu_sched, i);
+ struct rq *rq = cpu_rq(i);
+
+ pcpu_sched->runtime = 0;
+ /* a slightly stale cpu epoch is acceptible */
+ pcpu_sched->epoch = rq->cpu_epoch;
+ epoch = rq->cpu_epoch;
+ }
+
+ raw_spin_lock_init(&grp->lock);
+ grp->epoch = epoch;
+ grp->cpu = -1;
+ grp->next_scan = jiffies;
+ grp->nr_running_avg = 0;
+ grp->footprint = 0;
+ refcount_set(&grp->refcnt, 1);
+ /*
+ * The update to grp->pcpu_sched should not be reordered
+ * before initialization to grp's other fields, in case
+ * the readers may get invalid mm_sched_epoch, etc.
+ */
+ smp_store_release(&grp->pcpu_sched, _pcpu_sched);
+}
+
+struct sched_cache_group *
+sched_cache_alloc_group(struct sched_cache_time __percpu *_pcpu_sched)
+{
+ struct sched_cache_group *grp;
+
+ grp = kzalloc_obj(*grp);
+ if (!grp) {
+ free_percpu(_pcpu_sched);
+ return NULL;
+ }
+
+ sched_cache_group_init(grp, _pcpu_sched);
+ return grp;
+}
diff --git a/kernel/sched/cache_sched.h b/kernel/sched/cache_sched.h
new file mode 100644
index 000000000000..4d0febe5fee1
--- /dev/null
+++ b/kernel/sched/cache_sched.h
@@ -0,0 +1,19 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Cache-aware scheduling: the interface between fair.c and the cache
+ * group's own compilation unit, kernel/sched/cache_sched.c.
+ */
+#ifndef _KERNEL_SCHED_CACHE_SCHED_H
+#define _KERNEL_SCHED_CACHE_SCHED_H
+
+#include <linux/sched.h>
+
+#ifdef CONFIG_SCHED_CACHE
+
+struct sched_cache_group *
+sched_cache_alloc_group(struct sched_cache_time __percpu *_pcpu_sched);
+void sched_cache_group_put(struct sched_cache_group *grp);
+
+#endif /* CONFIG_SCHED_CACHE */
+
+#endif /* _KERNEL_SCHED_CACHE_SCHED_H */
diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c
index 57360f5cdde4..29c6be227ef8 100644
--- a/kernel/sched/fair.c
+++ b/kernel/sched/fair.c
@@ -60,6 +60,7 @@
#include "sched.h"
#include "stats.h"
#include "autogroup.h"
+#include "cache_sched.h"
/*
* The initial- and re-scaling of tunables is configurable
@@ -1652,39 +1653,13 @@ int mm_init_sched(struct mm_struct *mm,
struct sched_cache_time __percpu *_pcpu_sched)
{
struct sched_cache_group *grp;
- unsigned long epoch = 0;
- int i;
- grp = kzalloc_obj(*grp);
+ grp = sched_cache_alloc_group(_pcpu_sched);
if (!grp) {
- free_percpu(_pcpu_sched);
mm->sched_cache_grp = NULL;
return -ENOMEM;
}
- for_each_possible_cpu(i) {
- struct sched_cache_time *pcpu_sched = per_cpu_ptr(_pcpu_sched, i);
- struct rq *rq = cpu_rq(i);
-
- pcpu_sched->runtime = 0;
- /* a slightly stale cpu epoch is acceptible */
- pcpu_sched->epoch = rq->cpu_epoch;
- epoch = rq->cpu_epoch;
- }
-
- raw_spin_lock_init(&grp->lock);
- grp->epoch = epoch;
- grp->cpu = -1;
- grp->next_scan = jiffies;
- grp->nr_running_avg = 0;
- grp->footprint = 0;
- refcount_set(&grp->refcnt, 1);
- /*
- * The update to grp->pcpu_sched should not be reordered
- * before initialization to grp's other fields, in case
- * the readers may get invalid mm_sched_epoch, etc.
- */
- smp_store_release(&grp->pcpu_sched, _pcpu_sched);
/*
* Publish the group last. Not every reader qualifies it by
* grp->pcpu_sched - can_migrate_llc_task() only checks that the
@@ -1696,113 +1671,9 @@ int mm_init_sched(struct mm_struct *mm,
return 0;
}
-static void sched_cache_group_free_rcu(struct rcu_head *rcu)
-{
- struct sched_cache_group *grp =
- container_of(rcu, struct sched_cache_group, rcu);
-
- free_percpu(grp->pcpu_sched);
- kfree(grp);
-}
-
-static void sched_cache_group_put(struct sched_cache_group *grp)
-{
- if (!grp || !refcount_dec_and_test(&grp->refcnt))
- return;
-
- call_rcu(&grp->rcu, sched_cache_group_free_rcu);
-}
-
DEFINE_FREE(sched_cache_group_put, struct sched_cache_group *,
sched_cache_group_put(_T));
-#define rcu_deref_sched_cache_grp(tsk) \
- rcu_dereference_check((tsk)->sched_cache_grp, (tsk) == current)
-
-static struct sched_cache_group *sched_cache_replace_grp(struct task_struct *p,
- struct sched_cache_group *new)
-{
- struct sched_cache_group *old;
-
- old = rcu_deref_sched_cache_grp(p);
- rcu_assign_pointer(p->sched_cache_grp, new);
-
- return old;
-}
-
-struct sched_cache_group *sched_cache_group_get(struct sched_cache_group *grp)
-{
- /*
- * refcount_inc_not_zero() is the acquire primitive for lockless
- * (RCU) lookups; plain refcount_inc() would scribble the count if
- * it already reached zero. Return NULL in that case.
- */
- if (grp && !refcount_inc_not_zero(&grp->refcnt))
- grp = NULL;
-
- return grp;
-}
-
-struct sched_cache_group *task_cache_group_get(struct task_struct *p)
-{
- guard(rcu)();
- return sched_cache_group_get(rcu_dereference(p->sched_cache_grp));
-}
-
-void sched_cache_fork(struct task_struct *p)
-{
- /*
- * The child takes its own reference on the mm's cache group, separate
- * from the reference held by the mm. @p is not yet visible to readers,
- * so a plain initializing store is enough.
- */
- RCU_INIT_POINTER(p->sched_cache_grp,
- sched_cache_group_get(p->mm->sched_cache_grp));
-}
-
-void sched_cache_fork_cleanup(struct task_struct *p)
-{
- /*
- * A fork that fails after sched_cache_fork() never reaches exit_mm(),
- * so drop the reference here. @p never became visible, so there are no
- * concurrent readers and the reference we hold keeps the group alive.
- */
- sched_cache_group_put(rcu_access_pointer(p->sched_cache_grp));
- RCU_INIT_POINTER(p->sched_cache_grp, NULL);
-}
-
-void sched_cache_exec_mmap(struct task_struct *p, struct mm_struct *mm)
-{
- struct sched_cache_group *old;
-
- /*
- * Acquire the new reference before publishing the pointer, then drop
- * the old one. @p is current and the only writer of its own pointer.
- */
- old = sched_cache_replace_grp(p, sched_cache_group_get(mm->sched_cache_grp));
- sched_cache_group_put(old);
-}
-
-void sched_cache_exit_mm(struct task_struct *p)
-{
- struct sched_cache_group *grp = sched_cache_replace_grp(p, NULL);
-
-#ifdef CONFIG_NUMA_BALANCING
- /*
- * Subtract this task's footprint from the group before dropping the
- * reference, so the group footprint converges as its threads exit.
- * Unlocked for performance; clamp to avoid underflow.
- */
- if (grp && p->total_numa_faults) {
- unsigned long fp = READ_ONCE(grp->footprint);
- unsigned long sub = min(fp, p->total_numa_faults);
-
- WRITE_ONCE(grp->footprint, fp - sub);
- }
-#endif
- sched_cache_group_put(grp);
-}
-
void mm_destroy_sched(struct mm_struct *mm)
{
sched_cache_group_put(mm->sched_cache_grp);
--
2.34.1
^ permalink raw reply [flat|nested] 8+ messages in thread* [RFC PATCH 2/7] sched/cache: Add thread count to cache group
2026-11-26 13:48 [RFC PATCH 0/7] sched/cache: Introduce per-task affinity group via BPF detector Luo Gengkun
2026-11-26 13:48 ` [RFC PATCH 1/7] sched/cache: Move the cache group lifecycle to cache_sched.c Luo Gengkun
@ 2026-11-26 13:48 ` Luo Gengkun
2026-11-26 13:48 ` [RFC PATCH 3/7] sched/cache: Introduce the task affinity group Luo Gengkun
` (4 subsequent siblings)
6 siblings, 0 replies; 8+ messages in thread
From: Luo Gengkun @ 2026-11-26 13:48 UTC (permalink / raw)
To: Peter Zijlstra, Ingo Molnar, Juri Lelli, Vincent Guittot,
Tim Chen, Chen Yu, K Prateek Nayak
Cc: Dietmar Eggemann, Steven Rostedt, Ben Segall, Mel Gorman,
Valentin Schneider, linux-kernel
Every cache group belongs to an mm today, so get_nr_threads() is a
reasonable stand-in for the group's member count. Later patches in
this series will introduce cache groups that no mm owns, and
get_nr_threads() cannot tell whether such a group is valid.
So add an atomic nr_threads counter to struct sched_cache_group and
maintain it through fork, exec, exit and failed-fork cleanup.
invalid_llc_nr() switches to grp->nr_threads, an exact count of the
tasks that reference the group.
Also add a WARN_ON_ONCE in sched_cache_group_free_rcu() so any leak is
caught when the group is finally released: a group being freed has no
members left, so a non-zero count means an attach/detach pairing bug.
Signed-off-by: Luo Gengkun <luogengkun@huaweicloud.com>
---
include/linux/sched.h | 1 +
kernel/sched/cache_sched.c | 59 ++++++++++++++++++++++++++++++++------
kernel/sched/cache_sched.h | 1 +
kernel/sched/fair.c | 14 ++++-----
4 files changed, 59 insertions(+), 16 deletions(-)
diff --git a/include/linux/sched.h b/include/linux/sched.h
index d35ae49a991f..3073ed421b58 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -2415,6 +2415,7 @@ struct sched_cache_group {
unsigned long footprint;
int cpu;
refcount_t refcnt;
+ atomic_t nr_threads;
struct rcu_head rcu;
} ____cacheline_aligned_in_smp;
diff --git a/kernel/sched/cache_sched.c b/kernel/sched/cache_sched.c
index c20ed59ba45b..e1562b6af0bc 100644
--- a/kernel/sched/cache_sched.c
+++ b/kernel/sched/cache_sched.c
@@ -20,6 +20,7 @@ static void sched_cache_group_free_rcu(struct rcu_head *rcu)
struct sched_cache_group *grp =
container_of(rcu, struct sched_cache_group, rcu);
+ WARN_ON_ONCE(atomic_read(&grp->nr_threads));
free_percpu(grp->pcpu_sched);
kfree(grp);
}
@@ -54,26 +55,60 @@ struct sched_cache_group *task_cache_group_get(struct task_struct *p)
return sched_cache_group_get(rcu_dereference(p->sched_cache_grp));
}
+/*
+ * Become a member of @grp and take one reference on it. The reference
+ * returned is the caller's: publishing @grp into a task's sched_cache_grp
+ * hands it to the field, and every other outcome gives it back through
+ * sched_cache_group_detach().
+ *
+ * Returns NULL, having taken nothing, when @grp is NULL or already being
+ * released.
+ */
+static struct sched_cache_group *
+sched_cache_group_attach(struct sched_cache_group *grp) __must_check;
+
+static struct sched_cache_group *
+sched_cache_group_attach(struct sched_cache_group *grp)
+{
+ if (!grp || !refcount_inc_not_zero(&grp->refcnt))
+ return NULL;
+
+ atomic_inc(&grp->nr_threads);
+ return grp;
+}
+
+void sched_cache_group_detach(struct sched_cache_group *grp)
+{
+ if (grp) {
+ atomic_dec(&grp->nr_threads);
+ sched_cache_group_put(grp);
+ }
+}
+
void sched_cache_fork(struct task_struct *p)
{
/*
* The child takes its own reference on the mm's cache group, separate
- * from the reference held by the mm. @p is not yet visible to readers,
- * so a plain initializing store is enough.
+ * from the reference held by the mm. Attaching takes that reference
+ * and the membership in one step, and the store publishes both: @p is
+ * not yet visible to readers, so a plain initializing store is enough.
*/
RCU_INIT_POINTER(p->sched_cache_grp,
- sched_cache_group_get(p->mm->sched_cache_grp));
+ sched_cache_group_attach(p->mm->sched_cache_grp));
}
void sched_cache_fork_cleanup(struct task_struct *p)
{
+ struct sched_cache_group *grp;
+
/*
* A fork that fails after sched_cache_fork() never reaches exit_mm(),
* so drop the reference here. @p never became visible, so there are no
* concurrent readers and the reference we hold keeps the group alive.
*/
- sched_cache_group_put(rcu_access_pointer(p->sched_cache_grp));
+ grp = rcu_access_pointer(p->sched_cache_grp);
RCU_INIT_POINTER(p->sched_cache_grp, NULL);
+ sched_cache_group_detach(grp);
}
void sched_cache_exec_mmap(struct task_struct *p, struct mm_struct *mm)
@@ -81,11 +116,16 @@ void sched_cache_exec_mmap(struct task_struct *p, struct mm_struct *mm)
struct sched_cache_group *old;
/*
- * Acquire the new reference before publishing the pointer, then drop
- * the old one. @p is current and the only writer of its own pointer.
+ * Attaching takes the new group's reference and its membership before
+ * the store publishes it, so a reader that finds it in the field sees
+ * a group @p is already counted in. The store then hands over that
+ * reference and the old group is detached, which drops both its
+ * membership and the reference it was published with. @p is current
+ * and the only writer of its own pointer.
*/
- old = sched_cache_replace_grp(p, sched_cache_group_get(mm->sched_cache_grp));
- sched_cache_group_put(old);
+ old = sched_cache_replace_grp(p,
+ sched_cache_group_attach(mm->sched_cache_grp));
+ sched_cache_group_detach(old);
}
void sched_cache_exit_mm(struct task_struct *p)
@@ -105,7 +145,7 @@ void sched_cache_exit_mm(struct task_struct *p)
WRITE_ONCE(grp->footprint, fp - sub);
}
#endif
- sched_cache_group_put(grp);
+ sched_cache_group_detach(grp);
}
static void sched_cache_group_init(struct sched_cache_group *grp,
@@ -131,6 +171,7 @@ static void sched_cache_group_init(struct sched_cache_group *grp,
grp->nr_running_avg = 0;
grp->footprint = 0;
refcount_set(&grp->refcnt, 1);
+ atomic_set(&grp->nr_threads, 0);
/*
* The update to grp->pcpu_sched should not be reordered
* before initialization to grp's other fields, in case
diff --git a/kernel/sched/cache_sched.h b/kernel/sched/cache_sched.h
index 4d0febe5fee1..c73595ad6a9a 100644
--- a/kernel/sched/cache_sched.h
+++ b/kernel/sched/cache_sched.h
@@ -13,6 +13,7 @@
struct sched_cache_group *
sched_cache_alloc_group(struct sched_cache_time __percpu *_pcpu_sched);
void sched_cache_group_put(struct sched_cache_group *grp);
+void sched_cache_group_detach(struct sched_cache_group *grp);
#endif /* CONFIG_SCHED_CACHE */
diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c
index 29c6be227ef8..f5610cbc76ec 100644
--- a/kernel/sched/fair.c
+++ b/kernel/sched/fair.c
@@ -1527,17 +1527,17 @@ static bool exceed_llc_capacity(struct sched_cache_group *grp, int cpu)
return false;
}
-static bool invalid_llc_nr(struct sched_cache_group *grp, struct task_struct *p,
- int cpu)
+static bool invalid_llc_nr(struct sched_cache_group *grp, int cpu)
{
int scale;
- if (get_nr_threads(p) <= 1)
+ /* Skip if the cache group has at most one member. */
+ if (atomic_read(&grp->nr_threads) <= 1)
return true;
/*
* Scale the number of 'cores' in a LLC by llc_aggr_tolerance
- * and compare it to the task's active threads.
+ * and compare it to the group's active threads.
*/
scale = get_sched_cache_scale(1);
if (scale == INT_MAX)
@@ -1802,7 +1802,7 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec)
* its preferred state.
*/
if ((long)(epoch - READ_ONCE(grp->epoch)) > llc_epoch_affinity_timeout ||
- invalid_llc_nr(grp, p, cpu_of(rq)) ||
+ invalid_llc_nr(grp, cpu_of(rq)) ||
exceed_llc_capacity(grp, cpu_of(rq))) {
if (READ_ONCE(grp->cpu) != -1)
WRITE_ONCE(grp->cpu, -1);
@@ -1946,7 +1946,7 @@ static void task_cache_work(struct callback_head *work)
return;
curr_cpu = task_cpu(p);
- if (invalid_llc_nr(grp, p, curr_cpu) ||
+ if (invalid_llc_nr(grp, curr_cpu) ||
exceed_llc_capacity(grp, curr_cpu)) {
if (READ_ONCE(grp->cpu) != -1)
WRITE_ONCE(grp->cpu, -1);
@@ -10830,7 +10830,7 @@ static enum llc_mig can_migrate_llc_task(struct lb_env *env,
return mig_unrestricted;
/* skip cache aware load balance for too many threads */
- if (invalid_llc_nr(grp, p, dst_cpu) ||
+ if (invalid_llc_nr(grp, dst_cpu) ||
exceed_llc_capacity(grp, dst_cpu)) {
if (READ_ONCE(grp->cpu) != -1)
WRITE_ONCE(grp->cpu, -1);
--
2.34.1
^ permalink raw reply [flat|nested] 8+ messages in thread* [RFC PATCH 3/7] sched/cache: Introduce the task affinity group
2026-11-26 13:48 [RFC PATCH 0/7] sched/cache: Introduce per-task affinity group via BPF detector Luo Gengkun
2026-11-26 13:48 ` [RFC PATCH 1/7] sched/cache: Move the cache group lifecycle to cache_sched.c Luo Gengkun
2026-11-26 13:48 ` [RFC PATCH 2/7] sched/cache: Add thread count to cache group Luo Gengkun
@ 2026-11-26 13:48 ` Luo Gengkun
2026-11-26 13:48 ` [RFC PATCH 4/7] sched/cache: Converge task accounting to the affinity root Luo Gengkun
` (3 subsequent siblings)
6 siblings, 0 replies; 8+ messages in thread
From: Luo Gengkun @ 2026-11-26 13:48 UTC (permalink / raw)
To: Peter Zijlstra, Ingo Molnar, Juri Lelli, Vincent Guittot,
Tim Chen, Chen Yu, K Prateek Nayak
Cc: Dietmar Eggemann, Steven Rostedt, Ben Segall, Mel Gorman,
Valentin Schneider, linux-kernel
A cache group belongs to an mm today, and it is what gathers all the
tasks of a thread group together. But it cannot gather tasks from
different mms: two processes talking through a pipe, for example, have
data affinity, yet still cannot be gathered together. To address this
problem, add the affinity group: it belongs to no mm, so it can gather
tasks from different mms.
An mm's group and an affinity group are the two kinds of cache group,
told apart by the new type field. An affinity group adds two members:
- parent, used only by affinity groups: when two affinity groups
merge, the loser points to the winner
- rank, used only by affinity groups: when two affinity groups merge,
rank decides the winner
Submitting sched_cache_hint(x, y) is all it takes to gather x and y
into one affinity group. An example:
before after
[ A ] [ B ] [ A ]----->[ B ]
/ \ / \ / \ / \
t1 t2 t3 t4 t1 t2 t3 t4
This commit only sets A->parent to B; updating the sched_cache_grp of
the tasks in A to follow the link is implemented in the next commit.
Signed-off-by: Luo Gengkun <luogengkun@huaweicloud.com>
---
include/linux/sched.h | 19 +++
kernel/sched/cache_sched.c | 280 ++++++++++++++++++++++++++++++++++++-
2 files changed, 296 insertions(+), 3 deletions(-)
diff --git a/include/linux/sched.h b/include/linux/sched.h
index 3073ed421b58..de270443cffa 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -2406,6 +2406,16 @@ struct sched_cache_time {
unsigned long epoch;
};
+/*
+ * The kind of a cache group. An mm's group and an affinity group are the
+ * only kinds there are, and only an affinity group ever carries a merge
+ * link: the type tells them apart.
+ */
+enum cache_group_type {
+ CACHE_GROUP_MM = 0,
+ CACHE_GROUP_AFFINITY,
+};
+
struct sched_cache_group {
struct sched_cache_time __percpu *pcpu_sched;
raw_spinlock_t lock;
@@ -2416,6 +2426,9 @@ struct sched_cache_group {
int cpu;
refcount_t refcnt;
atomic_t nr_threads;
+ enum cache_group_type type;
+ struct sched_cache_group __rcu *parent;
+ unsigned int rank;
struct rcu_head rcu;
} ____cacheline_aligned_in_smp;
@@ -2427,6 +2440,8 @@ void sched_cache_fork_cleanup(struct task_struct *p);
void sched_cache_exec_mmap(struct task_struct *p, struct mm_struct *mm);
void sched_cache_exit_mm(struct task_struct *p);
+int sched_cache_hint(struct task_struct *t1, struct task_struct *t2);
+
#else
struct sched_cache_group { };
@@ -2436,6 +2451,10 @@ static inline void sched_cache_fork_cleanup(struct task_struct *p) { }
static inline void sched_cache_exec_mmap(struct task_struct *p, struct mm_struct *mm) { }
static inline void sched_cache_exit_mm(struct task_struct *p) { }
+static inline int sched_cache_hint(struct task_struct *t1, struct task_struct *t2)
+{
+ return -EOPNOTSUPP;
+}
#endif
#ifndef MODULE
diff --git a/kernel/sched/cache_sched.c b/kernel/sched/cache_sched.c
index e1562b6af0bc..52106c3ac049 100644
--- a/kernel/sched/cache_sched.c
+++ b/kernel/sched/cache_sched.c
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-2.0-only
#include "sched.h"
+#include "cache_sched.h"
#define rcu_deref_sched_cache_grp(tsk) \
rcu_dereference_check((tsk)->sched_cache_grp, (tsk) == current)
@@ -9,8 +10,14 @@ static struct sched_cache_group *sched_cache_replace_grp(struct task_struct *p,
{
struct sched_cache_group *old;
+ /*
+ * A hint on another CPU may change the field concurrently. cmpxchg
+ * makes sure @old is the group this call actually replaced: that is
+ * the one to detach, and a concurrent swap is left intact.
+ */
old = rcu_deref_sched_cache_grp(p);
- rcu_assign_pointer(p->sched_cache_grp, new);
+ do {
+ } while (!try_cmpxchg(&p->sched_cache_grp, &old, new));
return old;
}
@@ -19,10 +26,15 @@ static void sched_cache_group_free_rcu(struct rcu_head *rcu)
{
struct sched_cache_group *grp =
container_of(rcu, struct sched_cache_group, rcu);
+ struct sched_cache_group *parent;
WARN_ON_ONCE(atomic_read(&grp->nr_threads));
+ /* Only affinity groups hold it; for an mm's group this is NULL. */
+ parent = rcu_access_pointer(grp->parent);
free_percpu(grp->pcpu_sched);
kfree(grp);
+
+ sched_cache_group_put(parent);
}
void sched_cache_group_put(struct sched_cache_group *grp)
@@ -120,8 +132,7 @@ void sched_cache_exec_mmap(struct task_struct *p, struct mm_struct *mm)
* the store publishes it, so a reader that finds it in the field sees
* a group @p is already counted in. The store then hands over that
* reference and the old group is detached, which drops both its
- * membership and the reference it was published with. @p is current
- * and the only writer of its own pointer.
+ * membership and the reference it was published with.
*/
old = sched_cache_replace_grp(p,
sched_cache_group_attach(mm->sched_cache_grp));
@@ -194,3 +205,266 @@ sched_cache_alloc_group(struct sched_cache_time __percpu *_pcpu_sched)
sched_cache_group_init(grp, _pcpu_sched);
return grp;
}
+
+/*
+ * Follow the merge links up to the root of @grp, which is where the
+ * accounting lives. Walking needs no lock of its own: the caller's
+ * reference on @grp keeps it alive, and every live affinity group holds a
+ * reference on its parent, so the chain cannot be freed under the walk.
+ */
+static struct sched_cache_group *scg_find_root(struct sched_cache_group *grp)
+{
+ struct sched_cache_group *parent;
+
+ while ((parent = rcu_dereference(grp->parent)))
+ grp = parent;
+
+ return grp;
+}
+
+/*
+ * Allocate an affinity group: a fresh group typed CACHE_GROUP_AFFINITY,
+ * never an mm's. Returns with one reference, the caller's. Sleeps, so
+ * call it with no lock held.
+ */
+static struct sched_cache_group *scg_affinity_alloc(void)
+{
+ struct sched_cache_time __percpu *pcpu_sched;
+ struct sched_cache_group *grp;
+
+ pcpu_sched = alloc_percpu(struct sched_cache_time);
+ if (!pcpu_sched)
+ return NULL;
+
+ /* Frees @pcpu_sched itself when it fails. */
+ grp = sched_cache_alloc_group(pcpu_sched);
+ if (!grp)
+ return NULL;
+
+ grp->type = CACHE_GROUP_AFFINITY;
+
+ return grp;
+}
+
+/*
+ * Whether @p can be put into an affinity group. A kernel thread has no mm
+ * to pin, and a task on its way out of one - the last exec or exit - is past
+ * the point where an affinity move means anything.
+ *
+ * Both are racy reads from another CPU: a stale read only lets a hint
+ * through, and the cmpxchg on the field settles that race like any other.
+ * What the checks buy is skipping an affinity allocation and swap for a task
+ * that is already gone.
+ */
+static bool scg_can_attach(struct task_struct *p)
+{
+ return !(p->flags & (PF_KTHREAD | PF_EXITING)) &&
+ !p->in_execve && p->mm;
+}
+
+/*
+ * The task's entry into its affinity group: the group it accounts in. A
+ * task outside any affinity group accounts in its mm's group; first contact
+ * switches it to a fresh affinity group here, so membership and accounting
+ * are one fact in one field.
+ *
+ * The switch mirrors sched_cache_replace_grp(): exec and exit race it from
+ * @t's own context, and two hints may race each other, so whoever wins the
+ * cmpxchg owns the attach and the detach of what it installed and replaced.
+ */
+static struct sched_cache_group *
+scg_get_or_alloc_affinity(struct task_struct *t)
+{
+ struct sched_cache_group *c, *new;
+
+ scoped_guard(rcu) {
+ c = rcu_dereference(t->sched_cache_grp);
+ /* The type is stamped before publication and never changes. */
+ if (c && (READ_ONCE(c->type) == CACHE_GROUP_AFFINITY)) {
+ if (!sched_cache_group_get(c))
+ return ERR_PTR(-EAGAIN);
+ return c; /* already an affinity group */
+ }
+ }
+
+ if (!scg_can_attach(t))
+ return ERR_PTR(-ESRCH);
+
+ new = scg_affinity_alloc(); /* sleepable, outside any lock */
+ if (!new)
+ return ERR_PTR(-ENOMEM);
+
+ scoped_guard(rcu) {
+ c = rcu_dereference(t->sched_cache_grp);
+ if (!c) {
+ /* Exit took the group away while we were allocating. */
+ sched_cache_group_put(new);
+ return ERR_PTR(-ESRCH);
+ }
+ if (READ_ONCE(c->type) == CACHE_GROUP_AFFINITY) {
+ /* Another hint won the first contact while we allocated. */
+ if (!sched_cache_group_get(c)) {
+ sched_cache_group_put(new);
+ return ERR_PTR(-EAGAIN);
+ }
+ sched_cache_group_put(new);
+ return c;
+ }
+
+ /*
+ * First contact: switch the accounting to the fresh affinity
+ * group. A lost cmpxchg means @t moved on after the read
+ * above (exec installed a new mm's group, exit cleared it):
+ * drop the hint, not the task.
+ *
+ * Two references are in play: the allocator's, which the
+ * caller owns, and the field's. Attaching takes the second
+ * and counts the membership in the same step.
+ */
+ if (!sched_cache_group_attach(new)) {
+ /* Fresh from the allocator, so this cannot happen. */
+ sched_cache_group_put(new);
+ return ERR_PTR(-EAGAIN);
+ }
+ if (!try_cmpxchg(&t->sched_cache_grp, &c, new)) {
+ sched_cache_group_detach(new); /* the field's */
+ sched_cache_group_put(new); /* the allocator's */
+ return ERR_PTR(-EAGAIN);
+ }
+
+ sched_cache_group_detach(c);
+ }
+
+ return new; /* the allocator's reference */
+}
+
+/*
+ * Put one root under the other; every member keeps converging to whatever
+ * its root is now.
+ *
+ * The child's reference on the root keeps the chain up while the members
+ * that cached the child are still converging through it; it is dropped only
+ * in the child's free callback.
+ *
+ * The lock is the groups' own, shared with the tick's queueing, which runs
+ * from interrupt context - hence the IRQ-disabled take. The two groups are
+ * locked in address order, the only nesting this lock ever sees.
+ */
+static int scg_merge(struct sched_cache_group *a, struct sched_cache_group *b)
+{
+ int ret = 0;
+ struct sched_cache_group *root, *child;
+ unsigned long flags;
+
+ if (a == b)
+ return 0; /* same affinity group already */
+
+ /* Merge links exist only between affinity groups, never an mm's. */
+ if (WARN_ON_ONCE(a->type != CACHE_GROUP_AFFINITY ||
+ b->type != CACHE_GROUP_AFFINITY))
+ return -EINVAL;
+
+ if (a > b)
+ swap(a, b);
+
+ raw_spin_lock_irqsave(&a->lock, flags);
+ raw_spin_lock_nested(&b->lock, SINGLE_DEPTH_NESTING);
+
+ if (rcu_dereference_protected(a->parent, 1) != NULL ||
+ rcu_dereference_protected(b->parent, 1) != NULL) {
+ ret = -EAGAIN;
+ goto out;
+ }
+ root = a->rank < b->rank ? b : a;
+ child = root == a ? b : a;
+ if (root->rank == child->rank)
+ root->rank++;
+
+ /*
+ * The child's per-CPU runtime history dies with the group - the
+ * merged affinity group's occupancy starts over from what accrues on
+ * the root. These are advisory statistics, not accounting of record;
+ * keeping the sums continuous would mean walking the child's
+ * per-CPU array under both locks, for numbers that converge again
+ * within an epoch anyway.
+ */
+ refcount_inc(&root->refcnt); /* child owns one ref on root */
+ rcu_assign_pointer(child->parent, root);
+
+out:
+ raw_spin_unlock(&b->lock);
+ raw_spin_unlock_irqrestore(&a->lock, flags);
+
+ return ret;
+}
+
+/*
+ * Connect @t1 and @t2: they are accounted in one group from here on. The
+ * caller's references are enough, no tasks are pinned.
+ *
+ * Two threads of one mm need nothing of this only while neither is in an
+ * affinity group: their accounting already meets in the mm's group. Once
+ * one of them joins an affinity group the pair is split, and the hint has
+ * real work to do.
+ */
+int sched_cache_hint(struct task_struct *t1, struct task_struct *t2)
+{
+ struct sched_cache_group *c1, *c2;
+ struct mm_struct *mm1;
+ int ret = 0;
+
+ if (!sched_cache_enabled())
+ return -EOPNOTSUPP;
+
+ if (t1 == t2)
+ return 0;
+
+ /*
+ * The common same-mm case is two threads outside any affinity group:
+ * they share the mm's group already, so skip the lock. These reads
+ * are racy and may skip a pair that just joined an affinity group;
+ * hints are advisory, and whatever still observes the relation
+ * submits again.
+ */
+ mm1 = READ_ONCE(t1->mm);
+ if (mm1 && mm1 == READ_ONCE(t2->mm)) {
+ struct sched_cache_group *g1;
+
+ rcu_read_lock();
+ g1 = rcu_dereference(t1->sched_cache_grp);
+ if (g1 && g1 == rcu_dereference(t2->sched_cache_grp) &&
+ READ_ONCE(g1->type) != CACHE_GROUP_AFFINITY) {
+ rcu_read_unlock();
+ return 0;
+ }
+ rcu_read_unlock();
+ }
+
+ if (!scg_can_attach(t1) || !scg_can_attach(t2))
+ return -ESRCH;
+
+ for (;;) {
+ c1 = scg_get_or_alloc_affinity(t1);
+ if (IS_ERR(c1)) {
+ ret = PTR_ERR(c1);
+ break;
+ }
+ c2 = scg_get_or_alloc_affinity(t2);
+ if (IS_ERR(c2)) {
+ sched_cache_group_put(c1);
+ ret = PTR_ERR(c2);
+ break;
+ }
+ rcu_read_lock();
+ ret = scg_merge(scg_find_root(c1), scg_find_root(c2));
+ rcu_read_unlock();
+
+ sched_cache_group_put(c1);
+ sched_cache_group_put(c2);
+
+ if (ret != -EAGAIN)
+ return ret;
+ cond_resched();
+ }
+ return ret;
+}
--
2.34.1
^ permalink raw reply [flat|nested] 8+ messages in thread* [RFC PATCH 4/7] sched/cache: Converge task accounting to the affinity root
2026-11-26 13:48 [RFC PATCH 0/7] sched/cache: Introduce per-task affinity group via BPF detector Luo Gengkun
` (2 preceding siblings ...)
2026-11-26 13:48 ` [RFC PATCH 3/7] sched/cache: Introduce the task affinity group Luo Gengkun
@ 2026-11-26 13:48 ` Luo Gengkun
2026-11-26 13:48 ` [RFC PATCH 5/7] sched/cache: Add the per-CPU hint queue Luo Gengkun
` (2 subsequent siblings)
6 siblings, 0 replies; 8+ messages in thread
From: Luo Gengkun @ 2026-11-26 13:48 UTC (permalink / raw)
To: Peter Zijlstra, Ingo Molnar, Juri Lelli, Vincent Guittot,
Tim Chen, Chen Yu, K Prateek Nayak
Cc: Dietmar Eggemann, Steven Rostedt, Ben Segall, Mel Gorman,
Valentin Schneider, linux-kernel
Merging two affinity groups only sets the loser's parent: the tasks of
the loser keep accounting in their old group. Add
sched_grp_refresh(), which walks a task's merge links up to the
root and switches the task to it, so the entire affinity group ends up
accounted in a single group.
The convergence is lazy, triggered at the task's next accounting: a
task outside any affinity group is untouched, while a task whose
affinity group has not moved pays only a type read and a parent read.
account_mm_sched() converges before accounting, and task_cache_work()
does the same; the walk and switch happen at most once per member per
merge.
Signed-off-by: Luo Gengkun <luogengkun@huaweicloud.com>
---
include/linux/sched.h | 3 +++
kernel/sched/cache_sched.c | 54 ++++++++++++++++++++++++++++++++++++++
kernel/sched/fair.c | 16 +++++++++++
3 files changed, 73 insertions(+)
diff --git a/include/linux/sched.h b/include/linux/sched.h
index de270443cffa..769e2304f617 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -2442,6 +2442,9 @@ void sched_cache_exit_mm(struct task_struct *p);
int sched_cache_hint(struct task_struct *t1, struct task_struct *t2);
+struct sched_cache_group *sched_grp_refresh(struct task_struct *p,
+ struct sched_cache_group *grp);
+
#else
struct sched_cache_group { };
diff --git a/kernel/sched/cache_sched.c b/kernel/sched/cache_sched.c
index 52106c3ac049..c5fce997c114 100644
--- a/kernel/sched/cache_sched.c
+++ b/kernel/sched/cache_sched.c
@@ -468,3 +468,57 @@ int sched_cache_hint(struct task_struct *t1, struct task_struct *t2)
}
return ret;
}
+
+/*
+ * Converge @p to the group its affinity group accounts in, and return the
+ * group the caller should account in. A task outside any affinity group
+ * keeps its group, i.e. the default thread-group behaviour.
+ *
+ * @p is always the task running on the rq being accounted, but the caller
+ * need not run on that CPU: a remote wakeup's enqueue or a bandwidth
+ * unthrottle calls account_mm_sched() on rq->curr under that rq's lock, so
+ * this can converge @p while @p itself is in exec_mmap() or exit_mm() on
+ * its own CPU. The move is therefore a cmpxchg, mirrored by
+ * sched_cache_replace_grp() and scg_get_or_alloc_affinity(): whoever
+ * loses drops the reference it just took and converges again at the next
+ * accounting.
+ */
+struct sched_cache_group *sched_grp_refresh(struct task_struct *p,
+ struct sched_cache_group *grp)
+{
+ struct sched_cache_group *new_root;
+
+ /* Outside any affinity group: keeps the mm's group, nothing to do. */
+ if (!grp || READ_ONCE(grp->type) != CACHE_GROUP_AFFINITY)
+ return grp;
+
+ scoped_guard(rcu) {
+ /* Still the root: the common case. */
+ if (!rcu_dereference(grp->parent))
+ return grp;
+
+ /* The group we account in was merged away: follow the links. */
+ new_root = scg_find_root(grp);
+ /*
+ * Pinned by the reference @p holds on @grp: it keeps the whole
+ * chain above alive, and an RCU-pending @grp holds its edge on
+ * the parent until its free callback, so attaching cannot fail
+ * here.
+ */
+ if (!sched_cache_group_attach(new_root))
+ return grp;
+ /*
+ * Move @p's reference to the new root. Losing means @p moved
+ * on (exec installed a new mm's group, exit cleared it) after
+ * the caller read @grp: give back the membership and the
+ * reference just taken, the winner's is its own.
+ */
+ if (!try_cmpxchg(&p->sched_cache_grp, &grp, new_root)) {
+ sched_cache_group_detach(new_root);
+ return grp;
+ }
+ sched_cache_group_detach(grp); /* nr_threads + the field's reference */
+ }
+
+ return new_root;
+}
diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c
index f5610cbc76ec..5be8a7c7076e 100644
--- a/kernel/sched/fair.c
+++ b/kernel/sched/fair.c
@@ -1788,6 +1788,14 @@ void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec)
if (p->flags & PF_KTHREAD || !grp || !grp->pcpu_sched)
return;
+ /*
+ * Converge to the group the task's affinity group accounts in
+ * before accounting into it; a no-op outside any affinity group.
+ */
+ grp = sched_grp_refresh(p, grp);
+ if (!grp || !grp->pcpu_sched)
+ return;
+
pcpu_sched = per_cpu_ptr(grp->pcpu_sched, cpu_of(rq));
scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) {
@@ -1912,6 +1920,7 @@ static inline void update_avg_scale(u64 *avg, u64 sample)
static void task_cache_work(struct callback_head *work)
{
struct sched_cache_group *grp __free(sched_cache_group_put) = NULL;
+ struct sched_cache_group *new_grp;
cpumask_var_t cpus __free(free_cpumask_var) = CPUMASK_VAR_NULL;
int cpu, m_a_cpu = -1, nr_running = 0, curr_cpu;
unsigned long next_scan, now = jiffies;
@@ -1934,6 +1943,13 @@ static void task_cache_work(struct callback_head *work)
grp = task_cache_group_get(p);
if (!grp)
return;
+ new_grp = sched_grp_refresh(p, grp);
+ if (new_grp != grp) {
+ sched_cache_group_put(grp);
+ grp = sched_cache_group_get(new_grp);
+ if (!grp)
+ return;
+ }
next_scan = READ_ONCE(grp->next_scan);
if (time_before(now, next_scan))
--
2.34.1
^ permalink raw reply [flat|nested] 8+ messages in thread* [RFC PATCH 5/7] sched/cache: Add the per-CPU hint queue
2026-11-26 13:48 [RFC PATCH 0/7] sched/cache: Introduce per-task affinity group via BPF detector Luo Gengkun
` (3 preceding siblings ...)
2026-11-26 13:48 ` [RFC PATCH 4/7] sched/cache: Converge task accounting to the affinity root Luo Gengkun
@ 2026-11-26 13:48 ` Luo Gengkun
2026-11-26 13:48 ` [RFC PATCH 6/7] sched/cache: Add BPF-facing hint submitters Luo Gengkun
2026-11-26 13:48 ` [RFC PATCH 7/7] samples/bpf: Add pipe-based cache hint example Luo Gengkun
6 siblings, 0 replies; 8+ messages in thread
From: Luo Gengkun @ 2026-11-26 13:48 UTC (permalink / raw)
To: Peter Zijlstra, Ingo Molnar, Juri Lelli, Vincent Guittot,
Tim Chen, Chen Yu, K Prateek Nayak
Cc: Dietmar Eggemann, Steven Rostedt, Ben Segall, Mel Gorman,
Valentin Schneider, linux-kernel
sched_cache_hint() is not callable from every context: it sleeps when it
has to allocate a group, and it takes the hinted tasks' rq locks, which
a caller on the wakeup path may already hold. This adds a lockless
per-CPU queue in front of it: submitting a hint only queues it, and
everything that sleeps or locks happens in the worker's own context.
The queue is one lock-free llist per CPU. A producer takes a slot from
the per-CPU pool and queues it with llist_add(); the per-CPU smpboot
worker detaches the whole batch with llist_del_all() and calls
sched_cache_hint() on each hint. A queued hint owns the caller's
references on its two tasks, and the worker drops them as it consumes
each hint. The producer raises the worker with irq_work only when it is
not already running; the worker sleeps when the queue is empty, so there
is no polling.
SCG_HINT_LIMIT bounds both the pool and the queue, so the queue can
never overflow. A hint is dropped when the feature is off or the
backlog is full - hints are advisory, and whoever still observes the
relation submits it again. The BPF-facing submitters are added in the
next commit.
Signed-off-by: Luo Gengkun <luogengkun@huaweicloud.com>
---
kernel/sched/build_utility.c | 1 +
kernel/sched/cache_sched.c | 359 +++++++++++++++++++++++++++++++++++
2 files changed, 360 insertions(+)
diff --git a/kernel/sched/build_utility.c b/kernel/sched/build_utility.c
index f7ea083de6a3..5f63dbd43714 100644
--- a/kernel/sched/build_utility.c
+++ b/kernel/sched/build_utility.c
@@ -28,6 +28,7 @@
#include <linux/hashtable_api.h>
#include <linux/irq.h>
#include <linux/kobject_api.h>
+#include <linux/llist.h>
#include <linux/membarrier.h>
#include <linux/mempolicy.h>
#include <linux/nmi.h>
diff --git a/kernel/sched/cache_sched.c b/kernel/sched/cache_sched.c
index c5fce997c114..fafb04bcdfa9 100644
--- a/kernel/sched/cache_sched.c
+++ b/kernel/sched/cache_sched.c
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: GPL-2.0-only
#include "sched.h"
#include "cache_sched.h"
+#include <linux/smpboot.h>
+#include <linux/irq_work.h>
#define rcu_deref_sched_cache_grp(tsk) \
rcu_dereference_check((tsk)->sched_cache_grp, (tsk) == current)
@@ -522,3 +524,360 @@ struct sched_cache_group *sched_grp_refresh(struct task_struct *p,
return new_root;
}
+
+/*
+ * The hint queue: producers submit hints locklessly, per-CPU workers consume
+ * them. sched_cache_hint() sleeps and takes the hinted tasks' rq locks,
+ * which a producer may already hold, so submitting only queues the hint;
+ * everything that sleeps or locks runs in the worker's own context.
+ *
+ * The queue is one lock-free llist per CPU, the shape irq_work uses:
+ * submitting is one atomic on a local cache line, and the worker takes its
+ * CPU's worth with another atomic, so producers append to the now-empty
+ * list without contending with the consumer. The worker runs on the CPU
+ * the hints were submitted on, so the queue, the hints and the tasks the
+ * batch connects stay cache- and node-local.
+ *
+ * A per-CPU smpboot thread drains the queue and sleeps when it is empty; a
+ * submitter raises it with irq_work only when it is not already running.
+ * SCG_HINT_LIMIT bounds the backlog: past it a hint is dropped - hints are
+ * advisory, and whatever still observes the relation submits it again.
+ */
+struct scg_hint {
+ struct task_struct *t1;
+ struct task_struct *t2;
+ struct llist_node node;
+};
+
+struct scg_hint_queue {
+ struct llist_head hints;
+ struct llist_head free;
+ atomic_t cnt;
+ struct irq_work waker;
+ /*
+ * The worker task that drains this queue. The waker and the
+ * submitters reach the worker through the queue - never through the
+ * CPU they happen to run on - so a preemptible producer that
+ * migrates still wakes the worker that owns the queue it filled.
+ * Filled in by the smpboot .create callback.
+ */
+ struct task_struct *thread;
+};
+
+#define SCG_HINT_LIMIT 128 /* per-CPU backlog before dropping */
+
+static struct scg_hint_queue __percpu *scg_hint_queues;
+
+/* The per-CPU worker itself; owned by the smpboot machinery. */
+static DEFINE_PER_CPU(struct task_struct *, scg_hint_thread);
+
+static inline struct scg_hint *scg_hint_alloc(struct scg_hint_queue *q)
+{
+ struct llist_node *node = llist_del_first(&q->free);
+
+ if (node)
+ return container_of(node, struct scg_hint, node);
+ return NULL;
+}
+
+static inline void scg_hint_free(struct scg_hint_queue *q, struct scg_hint *h)
+{
+ llist_add(&h->node, &q->free);
+}
+
+static inline s32 __scg_submit_hint(struct scg_hint_queue *q, struct scg_hint *h)
+{
+ s32 err = 0;
+
+ /* A full queue sheds load; the hint is dropped, and it will come. */
+ if (atomic_read(&q->cnt) >= SCG_HINT_LIMIT) {
+ err = -EBUSY;
+ goto err_free;
+ }
+ /*
+ * Count before publishing: the worker decrements the count per hint
+ * as it consumes each slot, so publishing first could let the count
+ * dip below what is queued; the xchg in llist_add() orders the count
+ * before the hint becomes visible, so the count only ever
+ * overcounts, briefly, never undercounts - the worker can gate on it.
+ */
+ atomic_inc(&q->cnt);
+ llist_add(&h->node, &q->hints);
+
+ return 0;
+
+err_free:
+ scg_hint_free(q, h);
+ return err;
+}
+
+/*
+ * Best-effort, lockless check whether @t1 and @t2 already account in
+ * one group: in one affinity group, or in one mm's group. A stale read
+ * can cause a false negative, and the queued hint then runs as a no-op;
+ * it never causes a false positive.
+ */
+static inline bool scg_same_group(struct task_struct *t1,
+ struct task_struct *t2)
+{
+ struct sched_cache_group *g1, *g2;
+ struct mm_struct *mm;
+ bool same = false;
+
+ rcu_read_lock();
+ g1 = rcu_dereference(t1->sched_cache_grp);
+ g2 = rcu_dereference(t2->sched_cache_grp);
+
+ if (g1 && g1 == g2) {
+ if (READ_ONCE(g1->type) == CACHE_GROUP_AFFINITY) {
+ /* One affinity group: the two account in one group. */
+ same = true;
+ } else {
+ /*
+ * A shared mm group means one accounting only while
+ * the two really share the mm: exec installs the new
+ * mm before the new group, so a task mid-exec still
+ * points at the old mm's group from a new mm, and
+ * such a pair is already two processes.
+ */
+ mm = READ_ONCE(t1->mm);
+ same = mm && mm == READ_ONCE(t2->mm);
+ }
+ }
+ rcu_read_unlock();
+
+ return same;
+}
+
+/*
+ * The producer holds preemption off from the this_cpu_ptr() to the
+ * queueing, so the queue it filled is the queue whose worker drains it;
+ * the callback itself may fire on a different CPU. Find the owning worker
+ * through the queue, not through the CPU it runs on.
+ */
+static void scg_waker_fn(struct irq_work *work)
+{
+ struct scg_hint_queue *q =
+ container_of(work, struct scg_hint_queue, waker);
+ struct task_struct *tsk = READ_ONCE(q->thread);
+
+ /*
+ * Wake only a worker that is not running; waking a running one just
+ * burns a runqueue operation. The smpboot loop publishes
+ * TASK_INTERRUPTIBLE - a full barrier - before it re-checks the
+ * queue, and the submitter's list update precedes its state read,
+ * so if the worker still reads as running here it is bound to
+ * observe the new hint and keep draining.
+ */
+ if (tsk && !task_is_running(tsk))
+ wake_up_process(tsk);
+}
+
+/*
+ * Queue a hint connecting @t1 and @t2. The caller must already hold a
+ * reference on each task: once the hint is queued it owns both, and the
+ * worker drops them; every path that does not queue drops both here.
+ */
+static inline s32 scg_submit_hint_pinned(struct task_struct *t1,
+ struct task_struct *t2)
+{
+ struct scg_hint_queue *q;
+ struct task_struct *tsk;
+ struct scg_hint *h;
+ s32 ret;
+
+ /*
+ * The cheapest gate first, before any pinning: the sched_feat gate
+ * on the wake path does not imply this one, and with the feature
+ * statically off every affine wakeup would otherwise pay the task
+ * pinning and the queue dance only to be discarded in here.
+ */
+ if (!sched_cache_enabled()) {
+ ret = -EOPNOTSUPP;
+ goto out_drop;
+ }
+
+ if (unlikely(!READ_ONCE(scg_hint_queues))) {
+ ret = -ENOMEM;
+ goto out_drop;
+ }
+
+ /*
+ * preempt_disable() keeps a second submitter on this CPU off, but
+ * interrupt contexts bypass it - a hardirq, softirq or NMI program
+ * runs regardless - so refuse those instead of racing them; the
+ * hint is advisory and will come again.
+ */
+ if (!in_task()) {
+ ret = -EOPNOTSUPP;
+ goto out_drop;
+ }
+ preempt_disable();
+
+ q = this_cpu_ptr(scg_hint_queues);
+
+ if (scg_same_group(t1, t2)) {
+ ret = 0;
+ goto out_enable;
+ }
+
+ h = scg_hint_alloc(q);
+ if (!h) {
+ ret = -ENOMEM;
+ goto out_enable;
+ }
+ h->t1 = t1;
+ h->t2 = t2;
+
+ ret = __scg_submit_hint(q, h);
+ if (ret)
+ goto out_enable;
+
+ /*
+ * The smpboot loop publishes TASK_INTERRUPTIBLE before its last look
+ * at the queue, so a worker that still reads as running here will
+ * pick this hint up itself; only wake one that is not.
+ */
+ tsk = READ_ONCE(q->thread);
+ if (tsk && !task_is_running(tsk))
+ irq_work_queue(&q->waker);
+
+ preempt_enable();
+ return 0; /* queued: the hint owns both references */
+
+out_enable:
+ preempt_enable();
+out_drop:
+ put_task_struct(t1);
+ put_task_struct(t2);
+ return ret;
+}
+
+static int scg_hint_should_run(unsigned int cpu)
+{
+ return !llist_empty(&per_cpu_ptr(scg_hint_queues, cpu)->hints);
+}
+
+static void scg_hint_thread_fn(unsigned int cpu)
+{
+ struct scg_hint_queue *q = per_cpu_ptr(scg_hint_queues, cpu);
+ struct llist_node *llnode = llist_del_all(&q->hints);
+ struct scg_hint *h, *n;
+
+ /*
+ * Consume one hint at a time: each slot returns to the pool and drops
+ * the count as it is processed, so a submitter sees the freed capacity
+ * immediately instead of only after the whole batch.
+ */
+ llist_for_each_entry_safe(h, n, llnode, node) {
+ sched_cache_hint(h->t1, h->t2);
+ put_task_struct(h->t1);
+ put_task_struct(h->t2);
+ scg_hint_free(q, h);
+ atomic_dec(&q->cnt);
+ }
+
+ /* A full batch may have taken a while; yield before the next one. */
+ cond_resched();
+}
+
+/*
+ * The smpboot layer stores the freshly created thread and only then calls
+ * back, so the just-stored task is already visible here. The queues are
+ * published before the threads are registered, and a later hotplug bringup
+ * goes through the same store-then-create path.
+ */
+static void scg_hint_create(unsigned int cpu)
+{
+ WRITE_ONCE(per_cpu_ptr(scg_hint_queues, cpu)->thread,
+ per_cpu(scg_hint_thread, cpu));
+}
+
+/*
+ * A CPU going offline parks its worker with the queue undrained: drop what
+ * is left so the pinned task references do not sit on an offline CPU
+ * forever. The hints are dropped rather than processed - they are
+ * advisory, and park context is not the place for sched_cache_hint()'s
+ * sleepable work. Hints queued after the offline sit until the CPU comes
+ * back, bounded by the queue limit.
+ */
+static void scg_hint_park(unsigned int cpu)
+{
+ struct scg_hint_queue *q = per_cpu_ptr(scg_hint_queues, cpu);
+ struct llist_node *llnode = llist_del_all(&q->hints);
+ struct scg_hint *h, *n;
+
+ llist_for_each_entry_safe(h, n, llnode, node) {
+ put_task_struct(h->t1);
+ put_task_struct(h->t2);
+ scg_hint_free(q, h);
+ atomic_dec(&q->cnt);
+ }
+}
+
+static struct smp_hotplug_thread scg_hint_threads = {
+ .store = &scg_hint_thread,
+ .thread_should_run = scg_hint_should_run,
+ .thread_fn = scg_hint_thread_fn,
+ .create = scg_hint_create,
+ .park = scg_hint_park,
+ .thread_comm = "scg_hints/%u",
+};
+
+/*
+ * Late, on purpose: smpboot threads need the scheduler up, and the queues
+ * must be published before any hint can be submitted.
+ */
+static int __init scg_hint_init(void)
+{
+ struct scg_hint_queue __percpu *queues;
+ struct scg_hint __percpu *pool;
+ int cpu, ret;
+
+ queues = alloc_percpu(struct scg_hint_queue);
+ if (!queues)
+ return -ENOMEM;
+
+ pool = (struct scg_hint __percpu *)
+ __alloc_percpu(sizeof(struct scg_hint) * SCG_HINT_LIMIT,
+ __alignof__(struct scg_hint));
+ if (!pool) {
+ free_percpu(queues);
+ return -ENOMEM;
+ }
+
+ for_each_possible_cpu(cpu) {
+ struct scg_hint_queue *q = per_cpu_ptr(queues, cpu);
+ struct scg_hint *hpool = per_cpu_ptr(pool, cpu);
+ int i;
+
+ init_llist_head(&q->hints);
+ init_llist_head(&q->free);
+ for (i = 0; i < SCG_HINT_LIMIT; i++)
+ llist_add(&hpool[i].node, &q->free);
+ atomic_set(&q->cnt, 0);
+ init_irq_work(&q->waker, scg_waker_fn);
+ }
+
+ /*
+ * Publish first: the workers - and the .create callbacks the smpboot
+ * registration below runs - consult the queues as soon as they run.
+ */
+ scg_hint_queues = queues;
+
+ ret = smpboot_register_percpu_thread(&scg_hint_threads);
+ if (ret) {
+ /*
+ * Leak the queues rather than tear them down: they are already
+ * published, and no producer can exist this early - the kfuncs
+ * are not registered and CACHE_WAKE_HINT is off until debugfs
+ * is up - so the only cost is that this feature fails to boot.
+ */
+ pr_err("sched_cache: Failed to register the hint workers (%d)\n",
+ ret);
+ return ret;
+ }
+
+ return 0;
+}
+late_initcall(scg_hint_init);
--
2.34.1
^ permalink raw reply [flat|nested] 8+ messages in thread* [RFC PATCH 6/7] sched/cache: Add BPF-facing hint submitters
2026-11-26 13:48 [RFC PATCH 0/7] sched/cache: Introduce per-task affinity group via BPF detector Luo Gengkun
` (4 preceding siblings ...)
2026-11-26 13:48 ` [RFC PATCH 5/7] sched/cache: Add the per-CPU hint queue Luo Gengkun
@ 2026-11-26 13:48 ` Luo Gengkun
2026-11-26 13:48 ` [RFC PATCH 7/7] samples/bpf: Add pipe-based cache hint example Luo Gengkun
6 siblings, 0 replies; 8+ messages in thread
From: Luo Gengkun @ 2026-11-26 13:48 UTC (permalink / raw)
To: Peter Zijlstra, Ingo Molnar, Juri Lelli, Vincent Guittot,
Tim Chen, Chen Yu, K Prateek Nayak
Cc: Dietmar Eggemann, Steven Rostedt, Ben Segall, Mel Gorman,
Valentin Schneider, linux-kernel
Expose the hint queue to BPF programs as kfuncs:
- scg_bpf_submit_hint(tid1, tid2) submits by vpid.
- scg_bpf_submit_hint_tsk(t1, t2) submits by task pointer.
Both pin the two tasks before submitting: the queue owns the references
from there, and the worker drops what it consumes. Register them for
the tracing, kprobe, tracepoint and syscall BPF program types. The
queue machinery itself is in the previous commit.
Signed-off-by: Luo Gengkun <luogengkun@huaweicloud.com>
---
kernel/sched/build_utility.c | 3 ++
kernel/sched/cache_sched.c | 95 ++++++++++++++++++++++++++++++++++++
2 files changed, 98 insertions(+)
diff --git a/kernel/sched/build_utility.c b/kernel/sched/build_utility.c
index 5f63dbd43714..b4a72fd2311a 100644
--- a/kernel/sched/build_utility.c
+++ b/kernel/sched/build_utility.c
@@ -19,6 +19,9 @@
#include <linux/sched/rseq_api.h>
#include <linux/sched/task_stack.h>
+#include <linux/bpf.h>
+#include <linux/btf.h>
+#include <linux/btf_ids.h>
#include <linux/cpufreq.h>
#include <linux/cpumask_api.h>
#include <linux/cpuset.h>
diff --git a/kernel/sched/cache_sched.c b/kernel/sched/cache_sched.c
index fafb04bcdfa9..045c21e90505 100644
--- a/kernel/sched/cache_sched.c
+++ b/kernel/sched/cache_sched.c
@@ -753,6 +753,77 @@ static inline s32 scg_submit_hint_pinned(struct task_struct *t1,
return ret;
}
+__bpf_kfunc_start_defs();
+
+/*
+ * Submit a hint: two tasks, by vpid, are worth keeping in one cache group.
+ * The vpid is resolved in the caller's pid namespace here, because the
+ * worker consumes task pointers and the namespace context cannot shift
+ * between submit and flush.
+ */
+__bpf_kfunc s32 scg_bpf_submit_hint(u32 tid1, u32 tid2)
+{
+ struct task_struct *t1, *t2;
+
+ if (!sched_cache_enabled())
+ return -EOPNOTSUPP;
+
+ if (!tid1 || !tid2 || tid1 == tid2)
+ return 0;
+
+ t1 = find_get_task_by_vpid(tid1);
+ if (!t1)
+ return -ESRCH;
+
+ t2 = find_get_task_by_vpid(tid2);
+ if (!t2) {
+ put_task_struct(t1);
+ return -ESRCH;
+ }
+
+ return scg_submit_hint_pinned(t1, t2);
+}
+
+/*
+ * Submit a hint using two task pointers. The caller passes pointers that
+ * are valid in its context (an fentry/fexit probe argument, or
+ * bpf_get_current_task_btf()); they are pinned with tryget_task_struct()
+ * here, so the asynchronous worker can use them safely.
+ */
+__bpf_kfunc s32 scg_bpf_submit_hint_tsk(struct task_struct *t1,
+ struct task_struct *t2)
+{
+ if (!sched_cache_enabled())
+ return -EOPNOTSUPP;
+
+ if (!t1 || !t2 || t1 == t2)
+ return 0;
+
+ t1 = tryget_task_struct(t1);
+ if (!t1)
+ return -ESRCH;
+
+ t2 = tryget_task_struct(t2);
+ if (!t2) {
+ put_task_struct(t1);
+ return -ESRCH;
+ }
+
+ return scg_submit_hint_pinned(t1, t2);
+}
+
+__bpf_kfunc_end_defs();
+
+BTF_KFUNCS_START(scg_kfunc_ids_hint)
+BTF_ID_FLAGS(func, scg_bpf_submit_hint)
+BTF_ID_FLAGS(func, scg_bpf_submit_hint_tsk)
+BTF_KFUNCS_END(scg_kfunc_ids_hint)
+
+static const struct btf_kfunc_id_set scg_kfunc_set_hint = {
+ .owner = THIS_MODULE,
+ .set = &scg_kfunc_ids_hint,
+};
+
static int scg_hint_should_run(unsigned int cpu)
{
return !llist_empty(&per_cpu_ptr(scg_hint_queues, cpu)->hints);
@@ -878,6 +949,30 @@ static int __init scg_hint_init(void)
return ret;
}
+ ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
+ &scg_kfunc_set_hint);
+ if (ret) {
+ /*
+ * A registered kfunc set cannot be unregistered, so there is
+ * nothing to unwind here either.
+ */
+ pr_err("sched_cache: Failed to register the hint kfuncs (%d)\n",
+ ret);
+ return ret;
+ }
+
+ /*
+ * The remaining types are best-effort: keep the working queues and
+ * carry on without the types that fail to register.
+ */
+ if (register_btf_kfunc_id_set(BPF_PROG_TYPE_KPROBE,
+ &scg_kfunc_set_hint) ||
+ register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACEPOINT,
+ &scg_kfunc_set_hint) ||
+ register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
+ &scg_kfunc_set_hint))
+ pr_err("sched_cache: some hint kfunc registrations failed\n");
+
return 0;
}
late_initcall(scg_hint_init);
--
2.34.1
^ permalink raw reply [flat|nested] 8+ messages in thread* [RFC PATCH 7/7] samples/bpf: Add pipe-based cache hint example
2026-11-26 13:48 [RFC PATCH 0/7] sched/cache: Introduce per-task affinity group via BPF detector Luo Gengkun
` (5 preceding siblings ...)
2026-11-26 13:48 ` [RFC PATCH 6/7] sched/cache: Add BPF-facing hint submitters Luo Gengkun
@ 2026-11-26 13:48 ` Luo Gengkun
6 siblings, 0 replies; 8+ messages in thread
From: Luo Gengkun @ 2026-11-26 13:48 UTC (permalink / raw)
To: Peter Zijlstra, Ingo Molnar, Juri Lelli, Vincent Guittot,
Tim Chen, Chen Yu, K Prateek Nayak
Cc: Dietmar Eggemann, Steven Rostedt, Ben Segall, Mel Gorman,
Valentin Schneider, linux-kernel
Two BPF objects attach to the same pair of pipe hooks: a detector that
learns who talks to whom and asks the kernel to account those tasks
together, and an empty one that prices the hook itself. Run them under
the same workload and the difference is the cost of the policy.
scg_pipe_hint.bpf.c
-------------------
The detector. fentry on anon_pipe_read and anon_pipe_write, keyed by the
pipe_inode_info the two ends share. Every task that touches a pipe takes
a slot on its own side and is counted there; it is admitted once its own
traffic on that pipe passes 100 writes or reads, so a shell pipeline or a
one-shot hand-off never counts, and a task that arrives when its side is
full (16 slots) is dropped.
scg_pipe_noop.bpf.c
-------------------
The same two hooks with an empty body. It prices the fentry trampoline
with the policy removed, so the two objects can be compared under one
workload without guessing how much of a regression is the hook and how
much is the hints.
Signed-off-by: Luo Gengkun <luogengkun@huaweicloud.com>
---
samples/bpf/Makefile | 4 +
samples/bpf/scg_pipe_hint.bpf.c | 361 +++++++++++++++++++++++++++++++
samples/bpf/scg_pipe_hint_user.c | 210 ++++++++++++++++++
samples/bpf/scg_pipe_noop.bpf.c | 24 ++
4 files changed, 599 insertions(+)
create mode 100644 samples/bpf/scg_pipe_hint.bpf.c
create mode 100644 samples/bpf/scg_pipe_hint_user.c
create mode 100644 samples/bpf/scg_pipe_noop.bpf.c
diff --git a/samples/bpf/Makefile b/samples/bpf/Makefile
index 95a4fa1f1e44..90e166f5b129 100644
--- a/samples/bpf/Makefile
+++ b/samples/bpf/Makefile
@@ -32,6 +32,7 @@ tprogs-y += test_map_in_map
tprogs-y += per_socket_stats_example
tprogs-y += syscall_tp
tprogs-y += cpustat
+tprogs-y += scg_pipe_hint
tprogs-y += xdp_adjust_tail
tprogs-y += xdp_fwd
tprogs-y += task_fd_query
@@ -73,6 +74,7 @@ test_map_in_map-objs := test_map_in_map_user.o
per_socket_stats_example-objs := cookie_uid_helper_example.o
syscall_tp-objs := syscall_tp_user.o
cpustat-objs := cpustat_user.o
+scg_pipe_hint-objs := scg_pipe_hint_user.o
xdp_adjust_tail-objs := xdp_adjust_tail_user.o
xdp_fwd-objs := xdp_fwd_user.o
task_fd_query-objs := task_fd_query_user.o $(TRACE_HELPERS)
@@ -116,6 +118,8 @@ always-y += tcp_dumpstats_kern.o
always-y += xdp2skb_meta_kern.o
always-y += syscall_tp_kern.o
always-y += cpustat_kern.o
+always-y += scg_pipe_hint.bpf.o
+always-y += scg_pipe_noop.bpf.o
always-y += xdp_adjust_tail_kern.o
always-y += xdp_fwd_kern.o
always-y += task_fd_query_kern.o
diff --git a/samples/bpf/scg_pipe_hint.bpf.c b/samples/bpf/scg_pipe_hint.bpf.c
new file mode 100644
index 000000000000..81f386572d06
--- /dev/null
+++ b/samples/bpf/scg_pipe_hint.bpf.c
@@ -0,0 +1,361 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * scg_pipe_hint.bpf.c -- hint a cache group for tasks exchanging pipe data.
+ *
+ * One LRU hash entry per anonymous pipe, keyed by the pipe_inode_info
+ * address, holds the tasks seen on each side of it:
+ *
+ * nwriters, writers[], wcnt[] the writers and their write counts
+ * nreaders, readers[], rcnt[] the readers and their read counts
+ * anchor the first member to pass its
+ * threshold
+ * pending bit i: writers[i] not linked
+ * yet, bit MAX_WRITERS + j:
+ * readers[j] not linked yet
+ *
+ * Every task that touches the pipe takes a slot on its own side and is
+ * counted there. It is admitted once its own traffic on this pipe passes
+ * HINT_THRESHOLD, and dropped if it arrives when its side is full.
+ *
+ * Either hook may submit, so neither side waits for the other. A pending
+ * member is hinted once, against the anchor, never as a pair: hints merge
+ * transitively, so N members need at most N-1 hints, and a reader switch
+ * cannot resubmit the set the way a per-reader bitmap would. A member that
+ * has already exited is skipped; a hint is advisory, so a lost one is not
+ * worth retrying.
+ *
+ * Cost. A call below the threshold costs one slot scan and one saturated
+ * counter bump; a member already linked costs the same scan plus two
+ * compares. No task is resolved in either case. The metrics map is looked
+ * up on every call and exists only to price this program.
+ */
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/* kernel kfuncs: connect two tasks in one accounting group */
+extern s32 scg_bpf_submit_hint(u32 tid1, u32 tid2) __ksym;
+extern s32 scg_bpf_submit_hint_tsk(struct task_struct *t1,
+ struct task_struct *t2) __ksym;
+
+#define MAX_PIPES 4096
+/* Writes or reads one task needs on a pipe before it is admitted. */
+#define HINT_THRESHOLD 100
+/* Slots per pipe, each side. A task that arrives when its side is full is
+ * dropped, never displacing a member already there.
+ */
+#define MAX_WRITERS 16
+#define MAX_READERS 16
+#define MAX_MEMBERS (MAX_WRITERS + MAX_READERS)
+/* Per-slot counters saturate; past the threshold only "hot" matters. */
+#define COUNT_MAX 255
+
+struct pipe_state {
+ u32 nwriters; /* used slots in writers[] */
+ u32 nreaders; /* used slots in readers[] */
+ u32 anchor; /* first member; the star's centre */
+ u32 pending; /* bit i: writers[i] not linked yet,
+ * bit MAX_WRITERS + j: readers[j]
+ */
+ u32 writers[MAX_WRITERS]; /* admitted writers, in arrival order */
+ u32 readers[MAX_READERS]; /* admitted readers, in arrival order */
+ u8 wcnt[MAX_WRITERS]; /* writes seen from writers[i] */
+ u8 rcnt[MAX_READERS]; /* reads seen from readers[j] */
+};
+
+struct hint_stats {
+ u64 accepted;
+ u64 skipped;
+ u64 slots_full; /* task dropped, its side was full */
+ u64 new_pipes; /* write hook created the entry */
+};
+
+/* Per CPU: a shared element would be written from every CPU and cost more
+ * than the work it measures.
+ */
+struct hint_metrics {
+ u64 write_calls;
+ u64 read_calls;
+ u64 read_noop; /* read returned without submitting */
+ u64 submits; /* hint attempts actually made */
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_LRU_HASH);
+ __uint(max_entries, MAX_PIPES);
+ __type(key, u64);
+ __type(value, struct pipe_state);
+} pipes SEC(".maps");
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, u32);
+ __type(value, struct hint_stats);
+} stats SEC(".maps");
+
+struct {
+ __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, u32);
+ __type(value, struct hint_metrics);
+} metrics SEC(".maps");
+
+/* The pipe_inode_info shared by both ends; identity only, never dereferenced. */
+static __always_inline u64 pipe_id(struct kiocb *iocb)
+{
+ const struct file *filp = iocb->ki_filp;
+
+ if (!filp)
+ return 0;
+ return (u64)(unsigned long)filp->private_data;
+}
+
+/* Index of @tid in p->writers[], or -1. */
+static __always_inline int writer_slot(struct pipe_state *p, u32 tid)
+{
+ int i;
+
+ for (i = 0; i < MAX_WRITERS; i++) {
+ if (i >= p->nwriters)
+ break;
+ if (p->writers[i] == tid)
+ return i;
+ }
+ return -1;
+}
+
+/* Index of @tid in p->readers[], or -1. */
+static __always_inline int reader_slot(struct pipe_state *p, u32 tid)
+{
+ int i;
+
+ for (i = 0; i < MAX_READERS; i++) {
+ if (i >= p->nreaders)
+ break;
+ if (p->readers[i] == tid)
+ return i;
+ }
+ return -1;
+}
+
+/* Bump @cnt and report whether this call admitted the task. A task is
+ * admitted exactly once, so the caller sets the pending bit on the true
+ * return only.
+ */
+static __always_inline bool just_admitted(u8 *cnt)
+{
+ if (*cnt > HINT_THRESHOLD)
+ return false;
+ if (*cnt < COUNT_MAX)
+ *cnt = *cnt + 1;
+ return *cnt > HINT_THRESHOLD;
+}
+
+/* Hint @tid against @anchor_task; clear its pending bit either way. */
+static __always_inline void link_member(struct pipe_state *p, u32 bit, u32 tid,
+ struct task_struct *anchor_task,
+ struct hint_stats *s,
+ struct hint_metrics *m)
+{
+ struct task_struct *t;
+
+ p->pending = p->pending & ~bit;
+
+ t = bpf_task_from_pid(tid);
+ if (!t) {
+ if (s)
+ s->skipped++;
+ return;
+ }
+
+ if (m)
+ m->submits++;
+ if (scg_bpf_submit_hint_tsk(anchor_task, t) == 0) {
+ if (s)
+ s->accepted++;
+ }
+ bpf_task_release(t);
+}
+
+/* Link every admitted member that is not linked yet. The first pending one
+ * becomes the anchor if there is none; it is a member by definition, so its
+ * own bit is cleared rather than linked to itself.
+ */
+static __always_inline void link_pending(struct pipe_state *p,
+ struct hint_stats *s,
+ struct hint_metrics *m)
+{
+ struct task_struct *anchor_task;
+ int i;
+
+ if (!p->pending)
+ return;
+
+ if (!p->anchor) {
+ for (i = 0; i < MAX_MEMBERS; i++) {
+ if (p->pending & (1u << i))
+ break;
+ }
+ if (i >= MAX_MEMBERS) {
+ p->pending = 0;
+ return;
+ }
+ p->anchor = (i < MAX_WRITERS) ? p->writers[i] :
+ p->readers[i - MAX_WRITERS];
+ p->pending = p->pending & ~(1u << i);
+ if (!p->pending)
+ return;
+ }
+
+ anchor_task = bpf_task_from_pid(p->anchor);
+ if (!anchor_task) {
+ /* The anchor is gone; forget it and pick a new one next time. */
+ p->anchor = 0;
+ return;
+ }
+
+ for (i = 0; i < MAX_MEMBERS; i++) {
+ u32 bit = 1u << i;
+ u32 tid;
+
+ if (!p->pending)
+ break;
+ if (!(p->pending & bit))
+ continue;
+ if (i < MAX_WRITERS) {
+ if (i >= p->nwriters)
+ continue;
+ tid = p->writers[i];
+ } else {
+ if (i - MAX_WRITERS >= p->nreaders)
+ continue;
+ tid = p->readers[i - MAX_WRITERS];
+ }
+ if (tid == p->anchor) {
+ p->pending = p->pending & ~bit;
+ continue;
+ }
+ link_member(p, bit, tid, anchor_task, s, m);
+ }
+
+ bpf_task_release(anchor_task);
+}
+
+SEC("fentry/anon_pipe_write")
+int BPF_PROG(pipe_write, struct kiocb *iocb, struct iov_iter *from)
+{
+ struct hint_metrics *m;
+ struct pipe_state *p;
+ u64 id = pipe_id(iocb);
+ u32 zero = 0;
+ u32 me;
+ int i;
+
+ m = bpf_map_lookup_elem(&metrics, &zero);
+ if (m)
+ m->write_calls++;
+
+ if (!id)
+ return 0;
+
+ me = (u32)bpf_get_current_pid_tgid(); /* low half: the tid */
+ p = bpf_map_lookup_elem(&pipes, &id);
+ if (!p) {
+ struct hint_stats *s;
+ struct pipe_state fresh = {};
+
+ fresh.writers[0] = me;
+ fresh.nwriters = 1;
+ fresh.wcnt[0] = 1;
+ bpf_map_update_elem(&pipes, &id, &fresh, BPF_NOEXIST);
+ s = bpf_map_lookup_elem(&stats, &zero);
+ if (s)
+ s->new_pipes++;
+ return 0;
+ }
+
+ i = writer_slot(p, me);
+ if (i < 0) {
+ /* writers[] full: drop this task rather than track it. */
+ if (p->nwriters >= MAX_WRITERS) {
+ struct hint_stats *s = bpf_map_lookup_elem(&stats, &zero);
+
+ if (s)
+ s->slots_full++;
+ return 0;
+ }
+ i = p->nwriters;
+ p->writers[i] = me;
+ p->wcnt[i] = 1;
+ p->nwriters = p->nwriters + 1;
+ return 0;
+ }
+
+ if (just_admitted(&p->wcnt[i]))
+ p->pending = p->pending | (1u << i);
+
+ if (p->pending) {
+ struct hint_stats *s = bpf_map_lookup_elem(&stats, &zero);
+
+ link_pending(p, s, m);
+ }
+ return 0;
+}
+
+SEC("fentry/anon_pipe_read")
+int BPF_PROG(pipe_read, struct kiocb *iocb, struct iov_iter *to)
+{
+ struct hint_metrics *m;
+ struct pipe_state *p;
+ u64 id = pipe_id(iocb);
+ u32 zero = 0;
+ u32 me_pid;
+ int j;
+
+ m = bpf_map_lookup_elem(&metrics, &zero);
+ if (m)
+ m->read_calls++;
+
+ if (!id)
+ return 0;
+
+ p = bpf_map_lookup_elem(&pipes, &id);
+ me_pid = (u32)bpf_get_current_pid_tgid();
+ if (!p) {
+ if (m)
+ m->read_noop++;
+ return 0;
+ }
+
+ j = reader_slot(p, me_pid);
+ if (j < 0) {
+ /* readers[] full: drop this task rather than track it. */
+ if (p->nreaders >= MAX_READERS) {
+ if (m)
+ m->read_noop++;
+ return 0;
+ }
+ j = p->nreaders;
+ p->readers[j] = me_pid;
+ p->rcnt[j] = 1;
+ p->nreaders = p->nreaders + 1;
+ if (m)
+ m->read_noop++;
+ return 0;
+ }
+
+ if (just_admitted(&p->rcnt[j]))
+ p->pending = p->pending | (1u << (MAX_WRITERS + j));
+
+ if (p->pending) {
+ struct hint_stats *s = bpf_map_lookup_elem(&stats, &zero);
+
+ link_pending(p, s, m);
+ } else if (m) {
+ m->read_noop++;
+ }
+ return 0;
+}
+
+char LICENSE[] SEC("license") = "GPL";
diff --git a/samples/bpf/scg_pipe_hint_user.c b/samples/bpf/scg_pipe_hint_user.c
new file mode 100644
index 000000000000..35c6eb2c3719
--- /dev/null
+++ b/samples/bpf/scg_pipe_hint_user.c
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * scg_pipe_hint_user.c -- load, attach and report the pipe-hint policy
+ *
+ * usage: scg_pipe_hint [seconds] [object]
+ *
+ * Attaches every program in the object, keeps it loaded for the given number
+ * of seconds or until SIGINT/SIGTERM, and prints the counters once a second.
+ * A final line is printed on the way out so a harness can read the totals
+ * from the log without parsing the per-second samples.
+ */
+#include <errno.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <bpf/bpf.h>
+#include <bpf/libbpf.h>
+
+/* Must match struct hint_stats in scg_pipe_hint.bpf.c. */
+struct hint_stats {
+ __u64 accepted;
+ __u64 skipped;
+ __u64 slots_full;
+ __u64 new_pipes;
+};
+
+/* Must match struct hint_metrics in scg_pipe_hint.bpf.c. */
+struct hint_metrics {
+ __u64 write_calls;
+ __u64 read_calls;
+ __u64 read_noop;
+ __u64 submits;
+};
+
+static volatile sig_atomic_t stop;
+
+static void on_signal(int sig)
+{
+ (void)sig;
+ stop = 1;
+}
+
+static int ncpus;
+
+/* Per-CPU array values are padded to 8 bytes each. */
+#define PERCPU_STRIDE ((sizeof(struct hint_metrics) + 7) & ~7UL)
+
+/* Sum a per-CPU array's single element across all CPUs. */
+static int sum_percpu(int fd, struct hint_metrics *out)
+{
+ size_t sz = PERCPU_STRIDE * (size_t)ncpus;
+ void *buf = calloc(1, sz);
+ __u32 zero = 0;
+ int cpu;
+
+ if (!buf)
+ return -1;
+ if (bpf_map_lookup_elem(fd, &zero, buf)) {
+ free(buf);
+ return -1;
+ }
+ memset(out, 0, sizeof(*out));
+ for (cpu = 0; cpu < ncpus; cpu++) {
+ struct hint_metrics *m =
+ (void *)((char *)buf + (size_t)cpu * PERCPU_STRIDE);
+
+ out->write_calls += m->write_calls;
+ out->read_calls += m->read_calls;
+ out->read_noop += m->read_noop;
+ out->submits += m->submits;
+ }
+ free(buf);
+ return 0;
+}
+
+static void report(int stats_fd, int metrics_fd, __u32 stats_val_sz)
+{
+ struct hint_metrics mt;
+ struct hint_stats st;
+ __u32 zero = 0;
+
+ memset(&st, 0, sizeof(st));
+ if (stats_fd >= 0 && stats_val_sz &&
+ !bpf_map_lookup_elem(stats_fd, &zero, &st))
+ printf("hints accepted=%llu skipped=%llu "
+ "slots_full=%llu new_pipes=%llu\n",
+ (unsigned long long)st.accepted,
+ (unsigned long long)st.skipped,
+ (unsigned long long)(stats_val_sz > 2 * sizeof(__u64) ?
+ st.slots_full : 0),
+ (unsigned long long)(stats_val_sz > 3 * sizeof(__u64) ?
+ st.new_pipes : 0));
+ fflush(stdout);
+
+ if (metrics_fd >= 0 && !sum_percpu(metrics_fd, &mt))
+ printf("calls write=%llu read=%llu noop=%llu submits=%llu\n",
+ (unsigned long long)mt.write_calls,
+ (unsigned long long)mt.read_calls,
+ (unsigned long long)mt.read_noop,
+ (unsigned long long)mt.submits);
+ fflush(stdout);
+}
+
+int main(int argc, char **argv)
+{
+ const char *file = argc > 2 ? argv[2] : "scg_pipe_hint.bpf.o";
+ int seconds = argc > 1 ? atoi(argv[1]) : 30;
+ struct bpf_object *obj;
+ struct bpf_program *prog;
+ struct bpf_link **links;
+ int nlinks, i, attached = 0;
+ struct bpf_map *stats, *metrics;
+ int stats_fd = -1, metrics_fd = -1;
+ __u32 stats_val_sz = 0;
+ long err;
+
+ ncpus = libbpf_num_possible_cpus();
+ if (ncpus < 1) {
+ fprintf(stderr, "scg_pipe_hint: cannot count CPUs: %d\n", ncpus);
+ return 1;
+ }
+
+ obj = bpf_object__open_file(file, NULL);
+ err = libbpf_get_error(obj);
+ if (err) {
+ fprintf(stderr, "scg_pipe_hint: cannot open %s: %ld\n", file, err);
+ return 1;
+ }
+ err = bpf_object__load(obj);
+ if (err) {
+ fprintf(stderr, "scg_pipe_hint: verifier rejected the object: %ld\n",
+ err);
+ bpf_object__close(obj);
+ return 1;
+ }
+
+ /* Links are owned by the loader, not by the object. */
+ nlinks = 0;
+ bpf_object__for_each_program(prog, obj)
+ nlinks++;
+ if (!nlinks) {
+ fprintf(stderr, "scg_pipe_hint: %s has no programs\n", file);
+ bpf_object__close(obj);
+ return 1;
+ }
+
+ links = calloc(nlinks, sizeof(*links));
+ if (!links) {
+ fprintf(stderr, "scg_pipe_hint: out of memory\n");
+ bpf_object__close(obj);
+ return 1;
+ }
+
+ bpf_object__for_each_program(prog, obj) {
+ struct bpf_link *link = bpf_program__attach(prog);
+
+ err = libbpf_get_error(link);
+ if (err) {
+ fprintf(stderr, "scg_pipe_hint: cannot attach %s: %ld\n",
+ bpf_program__name(prog), err);
+ goto out_destroy;
+ }
+ links[attached++] = link;
+ fprintf(stderr, "scg_pipe_hint: attached %s\n",
+ bpf_program__name(prog));
+ }
+
+ stats = bpf_object__find_map_by_name(obj, "stats");
+ metrics = bpf_object__find_map_by_name(obj, "metrics");
+ if (stats) {
+ stats_fd = bpf_map__fd(stats);
+ stats_val_sz = bpf_map__value_size(stats);
+ }
+ if (metrics)
+ metrics_fd = bpf_map__fd(metrics);
+ if (stats_fd < 0)
+ fprintf(stderr, "scg_pipe_hint: no stats map, running blind\n");
+
+ signal(SIGINT, on_signal);
+ signal(SIGTERM, on_signal);
+ signal(SIGHUP, on_signal);
+
+ if (seconds > 0)
+ fprintf(stderr, "scg_pipe_hint: running for %ds\n", seconds);
+ else if (seconds == 0)
+ fprintf(stderr, "scg_pipe_hint: running\n");
+
+ for (i = 0; (i < seconds || seconds <= 0) && !stop; i++) {
+ report(stats_fd, metrics_fd, stats_val_sz);
+ sleep(1);
+ }
+
+ printf("FINAL ");
+ report(stats_fd, metrics_fd, stats_val_sz);
+
+ for (i = 0; i < attached; i++)
+ bpf_link__destroy(links[i]);
+ free(links);
+ bpf_object__close(obj);
+ return 0;
+
+out_destroy:
+ for (i = 0; i < attached; i++)
+ bpf_link__destroy(links[i]);
+ free(links);
+ bpf_object__close(obj);
+ return 1;
+}
diff --git a/samples/bpf/scg_pipe_noop.bpf.c b/samples/bpf/scg_pipe_noop.bpf.c
new file mode 100644
index 000000000000..c14a5ab4778c
--- /dev/null
+++ b/samples/bpf/scg_pipe_noop.bpf.c
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * scg_pipe_noop.bpf.c -- the same two hooks as scg_pipe_hint.bpf.c, empty.
+ *
+ * Prices the fentry trampoline alone, so running both objects under the same
+ * workload separates the cost of the hook from the cost of the policy.
+ */
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+SEC("fentry/anon_pipe_write")
+int BPF_PROG(noop_pipe_write, struct kiocb *iocb, struct iov_iter *from)
+{
+ return 0;
+}
+
+SEC("fentry/anon_pipe_read")
+int BPF_PROG(noop_pipe_read, struct kiocb *iocb, struct iov_iter *to)
+{
+ return 0;
+}
+
+char LICENSE[] SEC("license") = "GPL";
--
2.34.1
^ permalink raw reply [flat|nested] 8+ messages in thread