All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH v3 0/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup
@ 2026-12-06  5:37 Changwoo Min
  2026-12-06  5:37 ` [PATCH v3 1/6] sched_ext: Add scx_bpf_sched_id() and scx_task_sched_id() Changwoo Min
                   ` (5 more replies)
  0 siblings, 6 replies; 12+ messages in thread
From: Changwoo Min @ 2026-12-06  5:37 UTC (permalink / raw)
  To: tj, void, arighi, changwoo
  Cc: david.dai, Gavin Guo, kernel-dev, sched-ext, linux-kernel

BPF schedulers keep their per-task context in task local storage, or in
an arena allocation reached through it, and look it up in nearly every
callback. Each lookup is a bpf_task_storage_get() call.

This series adds p->scx.bpf_priv, an opaque u64 that the task's scheduler
sets with scx_bpf_task_set_priv(), typically to an arena pointer to its
task context. Any BPF program, tracing programs included, reads it with a
plain load. The value belongs to the scheduler that owns the task, from
after ops.init_task() until ops.exit_task(), and the kernel clears it
after ops.exit_task(). The kfunc checks the ownership under the task's
locks. Like scx_bpf_cpuperf_set(), it can be called from an op called
for the task or with no lock held.

With sub-schedulers, a task that a scheduler reaches may belong to
another scheduler. scx_bpf_sched_id() returns the calling scheduler's
id, which is never reused, and scx_task_sched_id() in compat.bpf.h the
id of the task's owner. A reader holding the task's locks compares the
two, and a lockless one tags the value with its id.

- Patch 1 adds scx_bpf_sched_id() and scx_task_sched_id().
- Patch 3 adds p->scx.bpf_priv and scx_bpf_task_set_priv().
- Patch 4 converts scx_qmap as an example.
- Patches 2, 5 and 6 add selftests.

The scx side uses the field in its shared task data library and in
scx_lavd:

  https://github.com/multics69/scx/tree/changwoo/taskc-caching

scx_lavd without and with that branch was compared on a 2-socket AMD
EPYC 9R45 machine with 192 CPUs (SMT off), running 7.4-rc4. Under
sysbench OLTP against MariaDB, at a fixed request rate of 60% of the
saturation throughput, bpf_stats shows ops.select_cpu() 9% and
ops.running() 12% cheaper per call. The BPF programs of scx_lavd use
6% less of the total CPU time.

The other workloads were MariaDB at a fixed rate of 80% and with one
closed-loop connection per CPU, memcached under memtier, schbench,
stress-ng futex, fork and exec, kernel builds and rt-app. None got
worse. stress-ng futex throughput improved by 10% and the memtier p99
latency by 12%.

The series is based on sched_ext/for-next (31f4eeaf9b7b).

ChangeLog v2 -> v3:
 - Address all the review comments from Tejun, Andrea and Sashiko.
 - Drop "sched_ext: Reset task fields after ops.exit_task()", applied
   as 82cd5232be43.
 - Drop "sched_ext: Mark a task enabled before ops.enable()" (Tejun).
 - The value belongs to the task's owner, from after ops.init_task()
   until ops.exit_task(), and is cleared after ops.exit_task() (Tejun).
 - scx_bpf_task_set_priv() checks the ownership under the task's locks,
   like scx_bpf_cpuperf_set(), and tracing programs can't call it
   (Tejun). Publish the value with smp_wmb() and WRITE_ONCE().
 - Replace the scx_bpf_task_sched_id() kfunc with the CO-RE helper
   scx_task_sched_id() (Andrea), which reports 0 for an unowned task
   (Tejun). Set the task state in one store, as the helper reads it.
 - Document how a reader checks the owner: compare the ids under the
   task's locks, or tag the value.
 - scx_qmap: Clear the value in qmap_exit_task(), use it in
   qmap_dump_task() (Tejun), and read it with scx_bpf_task_priv().
 - Selftests: Test the new lifetime, the locking rules and
   ops.init_task() in sub-scheduler handoffs. Count only the test's own
   tasks and work in a PID namespace (Tejun). Associate the syscall
   programs with the scheduler, use SCHED_OTHER instead of SCHED_FIFO,
   fix the skeleton leaks and SCX_EQ() double evaluations, check that
   the ops and writes the tests depend on actually ran, and skip where
   sub-schedulers aren't supported (Sashiko).

ChangeLog v1 -> v2:
 - Rename p->scx.bpf_data to p->scx.bpf_priv, scx_bpf_task_set_data() to
   scx_bpf_task_set_priv() and the compat reader scx_bpf_task_data() to
   scx_bpf_task_priv() (Andrea).
 - Reset the task fields after ops.exit_task() instead of before it
   (new patch 1). ops.exit_task() could set a value that reached the
   next scheduler in a sub-scheduler handoff (reported by Andrea).
 - Mark a task enabled before ops.enable() (new patch 2, suggested by
   Andrea). scx_bpf_task_set_priv() now accepts only enabled tasks,
   which drops v1's exception for ops.enable().
 - Add a selftest for the sub-scheduler handoffs (new patch 8).

v1: https://lore.kernel.org/r/20261201054850.780664-1-changwoo@igalia.com
v2: https://lore.kernel.org/r/20261203045618.982539-1-changwoo@igalia.com

Changwoo Min (6):
  sched_ext: Add scx_bpf_sched_id() and scx_task_sched_id()
  selftests/sched_ext: Test scx_bpf_sched_id() and scx_task_sched_id()
  sched_ext: Add p->scx.bpf_priv for O(1) task context lookup
  sched_ext: scx_qmap: Cache task_ctx in p->scx.bpf_priv
  selftests/sched_ext: Test p->scx.bpf_priv across class changes
  selftests/sched_ext: Test task field reset across sub-scheduler
    handoffs

 include/linux/sched/ext.h                     |  11 +
 kernel/sched/ext/ext.c                        | 111 +++++-
 tools/sched_ext/include/scx/compat.bpf.h      |  85 +++++
 tools/sched_ext/scx_qmap.bpf.c                |  69 +++-
 tools/testing/selftests/sched_ext/Makefile    |   3 +
 .../selftests/sched_ext/sched_id.bpf.c        |  43 +++
 tools/testing/selftests/sched_ext/sched_id.c  | 129 +++++++
 .../selftests/sched_ext/sub_handoff.bpf.c     | 166 +++++++++
 .../testing/selftests/sched_ext/sub_handoff.c | 341 ++++++++++++++++++
 .../selftests/sched_ext/task_bpf_priv.bpf.c   | 129 +++++++
 .../selftests/sched_ext/task_bpf_priv.c       | 195 ++++++++++
 11 files changed, 1276 insertions(+), 6 deletions(-)
 create mode 100644 tools/testing/selftests/sched_ext/sched_id.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/sched_id.c
 create mode 100644 tools/testing/selftests/sched_ext/sub_handoff.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/sub_handoff.c
 create mode 100644 tools/testing/selftests/sched_ext/task_bpf_priv.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/task_bpf_priv.c


base-commit: 31f4eeaf9b7bc78f210475a551e7d61840514c03
-- 
2.56.1


^ permalink raw reply	[flat|nested] 12+ messages in thread

* [PATCH v3 1/6] sched_ext: Add scx_bpf_sched_id() and scx_task_sched_id()
  2026-12-06  5:37 [PATCH v3 0/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
@ 2026-12-06  5:37 ` Changwoo Min
  2026-12-06  6:03   ` sashiko-bot
  2026-12-06  5:37 ` [PATCH v3 2/6] selftests/sched_ext: Test " Changwoo Min
                   ` (4 subsequent siblings)
  5 siblings, 1 reply; 12+ messages in thread
From: Changwoo Min @ 2026-12-06  5:37 UTC (permalink / raw)
  To: tj, void, arighi, changwoo
  Cc: david.dai, Gavin Guo, kernel-dev, sched-ext, linux-kernel

A BPF scheduler can't tell which scheduler instance it is or which one
owns a task. With sub-schedulers, a task it reaches as a waker, from a
tracing program or by iteration may belong to another scheduler, and a
value that scheduler stored in the task means nothing to it.

Every scx_sched already has an id that starts at 1, increases
monotonically and is never reused. Add the scx_bpf_sched_id() kfunc,
the calling scheduler's id, 0 for none. Only the kernel knows which
scheduler a program belongs to, so it has to be a kfunc.

Add scx_task_sched_id() to compat.bpf.h, the id of the scheduler that
owns a task, 0 for none. It reads p->scx.sched with CO-RE, but only in
INIT, READY or ENABLED, as a scheduler owns a task only after
ops.init_task(). Without CONFIG_EXT_SUB_SCHED, the kernel doesn't set
p->scx.sched, so the helper returns scx_bpf_sched_id(), the root's id.

scx_set_task_state() now publishes the state bits in one store, as the
helper reads them without a lock.

Suggested-by: Andrea Righi <arighi@nvidia.com>
Signed-off-by: Changwoo Min <changwoo@igalia.com>
---
 kernel/sched/ext/ext.c                   | 22 ++++++++-
 tools/sched_ext/include/scx/compat.bpf.h | 61 ++++++++++++++++++++++++
 2 files changed, 81 insertions(+), 2 deletions(-)

diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c
index 6e1ce8681352..343d82f328ef 100644
--- a/kernel/sched/ext/ext.c
+++ b/kernel/sched/ext/ext.c
@@ -784,8 +784,9 @@ void scx_set_task_state(struct task_struct *p, u32 state)
 	WARN_ONCE(warn, "sched_ext: Invalid task state transition 0x%x -> 0x%x for %s[%d]",
 		  prev_state, state, p->comm, p->pid);
 
-	p->scx.flags &= ~SCX_TASK_STATE_MASK;
-	p->scx.flags |= state;
+	/* One store, as BPF's scx_task_sched_id() reads it locklessly */
+	WRITE_ONCE(p->scx.flags,
+		   (p->scx.flags & ~SCX_TASK_STATE_MASK) | state);
 }
 
 /**
@@ -11958,6 +11959,22 @@ __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
 	return task_cpu(p);
 }
 
+/**
+ * scx_bpf_sched_id - Id of the calling scheduler
+ * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
+ *
+ * Return the calling scheduler's instance id, 0 if there is none. Ids start at
+ * 1, increase monotonically and are never reused.
+ */
+__bpf_kfunc u64 scx_bpf_sched_id(const struct bpf_prog_aux *aux)
+{
+	struct scx_sched *sch;
+
+	guard(rcu)();
+	sch = scx_prog_sched(aux);
+	return sch ? sch->id : 0;
+}
+
 /**
  * scx_bpf_task_cid - cid a task is currently associated with
  * @p: task of interest
@@ -12280,6 +12297,7 @@ BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
+BTF_ID_FLAGS(func, scx_bpf_sched_id, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, scx_bpf_task_cid, KF_RCU)
 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL)
 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
diff --git a/tools/sched_ext/include/scx/compat.bpf.h b/tools/sched_ext/include/scx/compat.bpf.h
index 3520a749f8ce..4d2298bd7ac5 100644
--- a/tools/sched_ext/include/scx/compat.bpf.h
+++ b/tools/sched_ext/include/scx/compat.bpf.h
@@ -487,6 +487,67 @@ static inline void scx_bpf_task_set_lazy_resched(struct task_struct *p, bool laz
 		scx_bpf_task_set_lazy_resched___new(p, lazy);
 }
 
+/*
+ * v7.5: Add scx_bpf_sched_id(). Ids start at 1, increase monotonically and are
+ * never reused. 0 means no scheduler, including on kernels without the kfunc.
+ */
+u64 scx_bpf_sched_id___new(void) __ksym __weak;
+
+static inline u64 scx_bpf_sched_id(void)
+{
+	if (bpf_ksym_exists(scx_bpf_sched_id___new))
+		return scx_bpf_sched_id___new();
+	return 0;
+}
+
+struct scx_sched___task_id {
+	u64 id;
+	struct cgroup *cgrp;
+} __attribute__((preserve_access_index));
+
+struct sched_ext_entity___task_id {
+	struct scx_sched___task_id *sched;
+	u32 flags;
+} __attribute__((preserve_access_index));
+
+/*
+ * Id of the scheduler @p is on, see scx_bpf_sched_id(), 0 if @p is not on any.
+ * Unless @p's rq lock or pi_lock is held, @p may move to another scheduler
+ * right after.
+ */
+static __always_inline u64 scx_task_sched_id(const struct task_struct *p)
+{
+	struct sched_ext_entity___task_id *scx = (void *)&p->scx;
+	struct scx_sched___task_id *sch;
+	u32 state;
+	u64 id;
+
+	if (!bpf_ksym_exists(scx_bpf_sched_id___new))
+		return 0;
+
+	/* A sched owns @p only after ops.init_task() */
+	state = READ_ONCE(scx->flags) &
+		bpf_core_enum_value(enum scx_ent_flags, SCX_TASK_STATE_MASK);
+	if (state == bpf_core_enum_value(enum scx_ent_flags, SCX_TASK_NONE) ||
+	    state == bpf_core_enum_value(enum scx_ent_flags, SCX_TASK_INIT_BEGIN) ||
+	    state == bpf_core_enum_value(enum scx_ent_flags, SCX_TASK_DEAD))
+		return 0;
+
+	/*
+	 * Without CONFIG_EXT_SUB_SCHED, which @cgrp comes with, the kernel
+	 * doesn't set p->scx.sched, and the root is the only scheduler.
+	 */
+	if (!bpf_core_field_exists(struct scx_sched___task_id, cgrp))
+		return scx_bpf_sched_id();
+
+	/* Sleepable programs aren't in an RCU read section */
+	bpf_rcu_read_lock();
+	sch = scx->sched;
+	id = sch ? sch->id : 0;
+	bpf_rcu_read_unlock();
+	return id;
+}
+
 /*
  * v7.1: New scx_bpf_dsq_reenq() that allows re-enqueues on more DSQs. This
  * will eventually deprecate scx_bpf_reenqueue_local().
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v3 2/6] selftests/sched_ext: Test scx_bpf_sched_id() and scx_task_sched_id()
  2026-12-06  5:37 [PATCH v3 0/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
  2026-12-06  5:37 ` [PATCH v3 1/6] sched_ext: Add scx_bpf_sched_id() and scx_task_sched_id() Changwoo Min
@ 2026-12-06  5:37 ` Changwoo Min
  2026-12-06  5:37 ` [PATCH v3 3/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
                   ` (3 subsequent siblings)
  5 siblings, 0 replies; 12+ messages in thread
From: Changwoo Min @ 2026-12-06  5:37 UTC (permalink / raw)
  To: tj, void, arighi, changwoo
  Cc: david.dai, Gavin Guo, kernel-dev, sched-ext, linux-kernel

Load a partial-switch scheduler. The test task's owner id must equal the
scheduler's id and be nonzero, before and after the task switches to
SCHED_EXT, since a task that isn't SCHED_EXT is on the scheduler too.
Both must read 0 once the scheduler is unloaded. A second instance must
get a larger id.

Signed-off-by: Changwoo Min <changwoo@igalia.com>
---
 tools/testing/selftests/sched_ext/Makefile    |   1 +
 .../selftests/sched_ext/sched_id.bpf.c        |  43 ++++++
 tools/testing/selftests/sched_ext/sched_id.c  | 129 ++++++++++++++++++
 3 files changed, 173 insertions(+)
 create mode 100644 tools/testing/selftests/sched_ext/sched_id.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/sched_id.c

diff --git a/tools/testing/selftests/sched_ext/Makefile b/tools/testing/selftests/sched_ext/Makefile
index fe63dbd53f56..ef59c463cd33 100644
--- a/tools/testing/selftests/sched_ext/Makefile
+++ b/tools/testing/selftests/sched_ext/Makefile
@@ -198,6 +198,7 @@ auto-test-targets :=			\
 	select_cpu_dispatch_dbl_dsp	\
 	select_cpu_vtime		\
 	rt_stall			\
+	sched_id			\
 	sub_caps_kfunc			\
 	sub_core_caps			\
 	test_example			\
diff --git a/tools/testing/selftests/sched_ext/sched_id.bpf.c b/tools/testing/selftests/sched_ext/sched_id.bpf.c
new file mode 100644
index 000000000000..661a61f28343
--- /dev/null
+++ b/tools/testing/selftests/sched_ext/sched_id.bpf.c
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A BPF program for testing scx_bpf_sched_id() and scx_task_sched_id().
+ *
+ * Copyright (c) 2026 Meta Platforms, Inc. and affiliates.
+ * Author: Changwoo Min <changwoo@igalia.com>
+ */
+#include <scx/common.bpf.h>
+
+char _license[] SEC("license") = "GPL";
+
+UEI_DEFINE(uei); /* Error handling */
+
+/* Results of the last probe() run, overwritten by every run */
+u64 probe_sched_id;
+u64 probe_task_sched_id;
+
+void BPF_STRUCT_OPS(sched_id_exit, struct scx_exit_info *ei)
+{
+	UEI_RECORD(uei, ei);
+}
+
+/*
+ * Read this scheduler's id and the id of the calling task's scheduler. Only
+ * BPF_PROG_TEST_RUN from the test runs this program, synchronously in the
+ * test task, so the current task is the task under test.
+ */
+SEC("syscall")
+int probe(void *ctx)
+{
+	struct task_struct *p = bpf_get_current_task_btf();
+
+	probe_sched_id = scx_bpf_sched_id();
+	probe_task_sched_id = scx_task_sched_id(p);
+	return 0;
+}
+
+SEC(".struct_ops.link")
+struct sched_ext_ops sched_id_ops = {
+	.exit			= (void *)sched_id_exit,
+	.flags			= SCX_OPS_SWITCH_PARTIAL,
+	.name			= "sched_id",
+};
diff --git a/tools/testing/selftests/sched_ext/sched_id.c b/tools/testing/selftests/sched_ext/sched_id.c
new file mode 100644
index 000000000000..f0568b2c5f0d
--- /dev/null
+++ b/tools/testing/selftests/sched_ext/sched_id.c
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Test for scx_bpf_sched_id() and scx_task_sched_id().
+ *
+ * Copyright (c) 2026 Meta Platforms, Inc. and affiliates.
+ * Author: Changwoo Min <changwoo@igalia.com>
+ */
+#include <bpf/bpf.h>
+#include <sched.h>
+#include <scx/common.h>
+#include <unistd.h>
+#include "sched_id.bpf.skel.h"
+#include "scx_test.h"
+
+#define SCHED_EXT	7
+
+static int set_policy(int policy)
+{
+	struct sched_param param = {};
+
+	return sched_setscheduler(0, policy, &param);
+}
+
+/* Run probe() on this task and return its result */
+static int probe(struct sched_id *skel)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, topts);
+
+	return bpf_prog_test_run_opts(bpf_program__fd(skel->progs.probe),
+				      &topts) ?: topts.retval;
+}
+
+/*
+ * Load a scheduler, move this task onto it and return the scheduler's id, after
+ * checking that the task reports the same owner and that both read 0 once the
+ * scheduler is unloaded.
+ */
+static enum scx_test_status load_and_check(u64 *id)
+{
+	enum scx_test_status status = SCX_TEST_FAIL;
+	struct sched_id *skel;
+	struct bpf_link *link = NULL;
+
+	skel = sched_id__open();
+	SCX_FAIL_IF(!skel, "Failed to open skel");
+	SCX_ENUM_INIT(skel);
+	if (sched_id__load(skel)) {
+		SCX_ERR("Failed to load skel");
+		goto out;
+	}
+	if (bpf_program__assoc_struct_ops(skel->progs.probe,
+					  skel->maps.sched_id_ops, NULL)) {
+		SCX_ERR("Failed to associate probe with sched_id_ops");
+		goto out;
+	}
+
+	link = bpf_map__attach_struct_ops(skel->maps.sched_id_ops);
+	if (!link) {
+		SCX_ERR("Failed to attach struct_ops");
+		goto out;
+	}
+
+	/*
+	 * Step 1: Under %SCX_OPS_SWITCH_PARTIAL, a task that isn't SCHED_EXT
+	 * is on the scheduler too. The task must report the scheduler's id
+	 * before and after switching to SCHED_EXT.
+	 */
+	if (probe(skel)) {
+		SCX_ERR("Failed to probe");
+		goto out;
+	}
+	*id = skel->bss->probe_sched_id;
+	if (!*id || skel->bss->probe_task_sched_id != *id) {
+		SCX_ERR("sched_id=%llu task_sched_id=%llu",
+			(unsigned long long)*id,
+			(unsigned long long)skel->bss->probe_task_sched_id);
+		goto out;
+	}
+	if (set_policy(SCHED_EXT) || probe(skel)) {
+		SCX_ERR("Failed to switch to SCHED_EXT and probe");
+		goto out;
+	}
+	if (skel->bss->probe_task_sched_id != *id) {
+		SCX_ERR("On SCHED_EXT: task_sched_id=%llu",
+			(unsigned long long)skel->bss->probe_task_sched_id);
+		goto out;
+	}
+
+	/* Step 2: Both read 0 after the scheduler is unloaded */
+	bpf_link__destroy(link);
+	link = NULL;
+	if (probe(skel) || skel->bss->probe_sched_id ||
+	    skel->bss->probe_task_sched_id) {
+		SCX_ERR("After unload: sched_id=%llu task_sched_id=%llu",
+			(unsigned long long)skel->bss->probe_sched_id,
+			(unsigned long long)skel->bss->probe_task_sched_id);
+		goto out;
+	}
+
+	status = SCX_TEST_PASS;
+out:
+	set_policy(SCHED_OTHER);
+	bpf_link__destroy(link);
+	sched_id__destroy(skel);
+	return status;
+}
+
+static enum scx_test_status run(void *ctx)
+{
+	enum scx_test_status status;
+	u64 id1 = 0, id2 = 0;
+
+	status = load_and_check(&id1);
+	SCX_EQ(status, SCX_TEST_PASS);
+
+	/* Step 3: A new instance gets a larger id */
+	status = load_and_check(&id2);
+	SCX_EQ(status, SCX_TEST_PASS);
+	SCX_GT(id2, id1);
+
+	return SCX_TEST_PASS;
+}
+
+struct scx_test sched_id = {
+	.name = "sched_id",
+	.description = "Verify scx_bpf_sched_id() and scx_task_sched_id()",
+	.run = run,
+};
+REGISTER_SCX_TEST(&sched_id)
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v3 3/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup
  2026-12-06  5:37 [PATCH v3 0/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
  2026-12-06  5:37 ` [PATCH v3 1/6] sched_ext: Add scx_bpf_sched_id() and scx_task_sched_id() Changwoo Min
  2026-12-06  5:37 ` [PATCH v3 2/6] selftests/sched_ext: Test " Changwoo Min
@ 2026-12-06  5:37 ` Changwoo Min
  2026-12-06  6:00   ` sashiko-bot
  2026-12-06  5:37 ` [PATCH v3 4/6] sched_ext: scx_qmap: Cache task_ctx in p->scx.bpf_priv Changwoo Min
                   ` (2 subsequent siblings)
  5 siblings, 1 reply; 12+ messages in thread
From: Changwoo Min @ 2026-12-06  5:37 UTC (permalink / raw)
  To: tj, void, arighi, changwoo
  Cc: david.dai, Gavin Guo, kernel-dev, sched-ext, linux-kernel

BPF schedulers keep their per-task context in task local storage, or in
an arena allocation reached through it, and pay a bpf_task_storage_get()
call per lookup.

Add p->scx.bpf_priv, an opaque u64 that the task's scheduler sets with
scx_bpf_task_set_priv(), typically to an arena pointer to its context.
Any BPF program reads it with a plain load.

The value belongs to the scheduler that owns @p, from after
ops.init_task() until ops.exit_task(). The kernel clears it after
ops.exit_task(), so it never reaches the next scheduler. It isn't reset
with the other task fields when @p leaves the ext class, as the
scheduler still owns @p then.

scx_bpf_task_set_priv() checks the ownership under @p's locks, so a
write can't race @p's move to another scheduler. Like
scx_bpf_cpuperf_set(), it works from an op called for @p, which holds
one of those locks, or with no lock held, where it takes them. It fails
from any other op, and tracing programs, which may run under any lock,
can't call it. For lockless readers, the store is ordered after the
stores that set up what the value points to.

With sub-schedulers, a task that a scheduler reaches as a waker, from a
tracing program or in ops.init_task() may belong to another one. A
reader holding the task's locks compares scx_task_sched_id() with its
scx_bpf_sched_id(). A lockless reader tags the value with its id
instead, since only the owner stores and the kernel clears the value
before the task moves.

Signed-off-by: Changwoo Min <changwoo@igalia.com>
---
 include/linux/sched/ext.h                | 11 +++
 kernel/sched/ext/ext.c                   | 89 ++++++++++++++++++++++++
 tools/sched_ext/include/scx/compat.bpf.h | 24 +++++++
 3 files changed, 124 insertions(+)

diff --git a/include/linux/sched/ext.h b/include/linux/sched/ext.h
index f3564581c317..a1793ab5f0c3 100644
--- a/include/linux/sched/ext.h
+++ b/include/linux/sched/ext.h
@@ -277,6 +277,17 @@ struct sched_ext_entity {
 	 */
 	atomic64_t		slice_oob;
 
+	/*
+	 * Opaque value owned by the task's scheduler, typically an arena
+	 * pointer to its per-task context. The kernel never dereferences it.
+	 * Set with scx_bpf_task_set_priv() while @p is on the scheduler,
+	 * from after ops.init_task() until ops.exit_task(), and cleared
+	 * after ops.exit_task(). Any BPF program can read it, so a tracing
+	 * program can reach the context of the current task with a single
+	 * load.
+	 */
+	u64			bpf_priv;
+
 	/*
 	 * Sub-sched cap rejected reenq context, valid only while
 	 * %SCX_TASK_REENQ_CAP is set. @reenq_reason_caps is the SCX_CAP_* bits
diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c
index 343d82f328ef..4f575a19df76 100644
--- a/kernel/sched/ext/ext.c
+++ b/kernel/sched/ext/ext.c
@@ -4833,6 +4833,12 @@ void __scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p)
 	 * ops.exit_task() can still write them while @p is on @sch.
 	 */
 	scx_reset_task_fields(task_rq(p), p);
+
+	/*
+	 * Not in scx_reset_task_fields(), which also runs when @p leaves the
+	 * ext class. The value stays until @p leaves @sch.
+	 */
+	WRITE_ONCE(p->scx.bpf_priv, 0);
 }
 
 /*
@@ -10912,6 +10918,84 @@ __bpf_kfunc bool scx_bpf_task_set_lazy_resched(struct task_struct *p, bool lazy,
 	return true;
 }
 
+/**
+ * scx_bpf_task_set_priv - Set the BPF scheduler's private value of a task
+ * @p: task of interest
+ * @priv: opaque value to store in @p->scx.bpf_priv
+ * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
+ *
+ * Store @priv in @p->scx.bpf_priv, where any BPF program can read it with a
+ * plain load. The calling scheduler can set it while @p is on it, from after
+ * ops.init_task() until ops.exit_task(), whatever @p's class. The kernel
+ * clears it after ops.exit_task().
+ *
+ * @p may be on another scheduler, e.g. as a waker, in a tracing program or
+ * in ops.init_task(), and the value is then that scheduler's. So check the
+ * owner before using it. With @p's rq lock or pi_lock held, compare
+ * scx_task_sched_id() of @p, in compat.bpf.h, with scx_bpf_sched_id().
+ * Without them, @p may move in between, so tag the value with
+ * scx_bpf_sched_id() and check the tag.
+ *
+ * Can be called from an op called for @p, or with no rq lock held, e.g. from
+ * an unlocked op, a BPF timer or a syscall program, in which case @p's locks
+ * are taken. Fails from any other op, such as one called for another task.
+ * Tracing programs can't call it.
+ *
+ * Return %true if @priv was stored, %false if @p is not on the calling
+ * scheduler or the caller is an op not called for @p.
+ */
+__bpf_kfunc bool scx_bpf_task_set_priv(struct task_struct *p, u64 priv,
+				       const struct bpf_prog_aux *aux)
+{
+	struct scx_sched *sch;
+	struct rq_flags rf;
+	struct rq *rq = NULL;
+	bool locked, ret = false;
+	u32 state;
+
+	guard(rcu)();
+	sch = scx_prog_sched(aux);
+	if (unlikely(!sch || !scx_kf_allowed_ctx(sch)))
+		return false;
+
+	/* Fast path, rechecked under @p's locks below */
+	if (!scx_task_on_sched(sch, p))
+		return false;
+
+	/*
+	 * @p's owner and state change only under both @p's pi_lock and rq lock.
+	 * An op called for @p holds one of them, the rq lock or, for
+	 * ops.select_cpu(), the pi_lock. Any other lock doesn't pin @p, and
+	 * taking @p's locks under it can deadlock, so restrict the call to @p's
+	 * own op when a lock is held.
+	 */
+	locked = p == current->scx.kf_tasks[0] || p == current->scx.kf_tasks[1];
+	if (!locked && (scx_locked_rq() || current->scx.kf_tasks[0]))
+		return false;
+
+	/* If no lock is held, pin @p by taking its locks */
+	if (!locked)
+		rq = task_rq_lock(p, &rf);
+
+	/* The sched owns @p from after ops.init_task() until ops.exit_task() */
+	state = scx_get_task_state(p);
+	if (scx_task_on_sched(sch, p) &&
+	    (state == SCX_TASK_INIT || state == SCX_TASK_READY ||
+	     state == SCX_TASK_ENABLED)) {
+		/*
+		 * Lockless readers may dereference @priv. Order the stores that
+		 * set up what @priv points to before the store that publishes it.
+		 */
+		smp_wmb();
+		WRITE_ONCE(p->scx.bpf_priv, priv);
+		ret = true;
+	}
+
+	if (!locked)
+		task_rq_unlock(rq, p, &rf);
+	return ret;
+}
+
 void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags)
 {
 	struct scx_sched_pcpu *pcpu;
@@ -12267,6 +12351,7 @@ BTF_KFUNCS_START(scx_kfunc_ids_any)
 BTF_ID_FLAGS(func, scx_bpf_task_set_slice, KF_IMPLICIT_ARGS | KF_RCU);
 BTF_ID_FLAGS(func, scx_bpf_task_set_dsq_vtime, KF_IMPLICIT_ARGS | KF_RCU);
 BTF_ID_FLAGS(func, scx_bpf_task_set_lazy_resched, KF_IMPLICIT_ARGS | KF_RCU);
+BTF_ID_FLAGS(func, scx_bpf_task_set_priv, KF_IMPLICIT_ARGS | KF_RCU);
 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, scx_bpf_kick_cid, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued, KF_IMPLICIT_ARGS)
@@ -12330,6 +12415,9 @@ static const struct btf_kfunc_id_set scx_kfunc_set_any = {
  * when scx_locked_rq() returns NULL. Taking it while the context already holds
  * an rq lock, the same one or another cpu's, can deadlock.
  *
+ * scx_bpf_task_set_priv() takes the task's pi_lock and rq lock outside an op
+ * called for the task, with the same deadlock.
+ *
  * scx_bpf_destroy_dsq() takes a user DSQ lock. So do
  * bpf_iter_scx_dsq_next() and bpf_iter_scx_dsq_destroy(), the latter only
  * after a successful next() has linked the cursor. A tracing program can
@@ -12347,6 +12435,7 @@ static const struct btf_kfunc_id_set scx_kfunc_set_any = {
 BTF_KFUNCS_START(scx_kfunc_ids_no_tracing)
 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS)
+BTF_ID_FLAGS(func, scx_bpf_task_set_priv, KF_IMPLICIT_ARGS | KF_RCU)
 BTF_ID_FLAGS(func, scx_bpf_sub_grant, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS)
diff --git a/tools/sched_ext/include/scx/compat.bpf.h b/tools/sched_ext/include/scx/compat.bpf.h
index 4d2298bd7ac5..e8cb5f35eed0 100644
--- a/tools/sched_ext/include/scx/compat.bpf.h
+++ b/tools/sched_ext/include/scx/compat.bpf.h
@@ -487,6 +487,30 @@ static inline void scx_bpf_task_set_lazy_resched(struct task_struct *p, bool laz
 		scx_bpf_task_set_lazy_resched___new(p, lazy);
 }
 
+/* v7.5: Add p->scx.bpf_priv and scx_bpf_task_set_priv(). */
+bool scx_bpf_task_set_priv___new(struct task_struct *p, u64 priv) __ksym __weak;
+
+static inline bool scx_bpf_task_set_priv(struct task_struct *p, u64 priv)
+{
+	if (bpf_ksym_exists(scx_bpf_task_set_priv___new))
+		return scx_bpf_task_set_priv___new(p, priv);
+	return false;
+}
+
+struct sched_ext_entity___bpf_priv {
+	u64 bpf_priv;
+} __attribute__((preserve_access_index));
+
+/* p->scx.bpf_priv, or 0 on kernels without it */
+static __always_inline u64 scx_bpf_task_priv(struct task_struct *p)
+{
+	struct sched_ext_entity___bpf_priv *scx = (void *)&p->scx;
+
+	if (bpf_core_field_exists(scx->bpf_priv))
+		return READ_ONCE(scx->bpf_priv);
+	return 0;
+}
+
 /*
  * v7.5: Add scx_bpf_sched_id(). Ids start at 1, increase monotonically and are
  * never reused. 0 means no scheduler, including on kernels without the kfunc.
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v3 4/6] sched_ext: scx_qmap: Cache task_ctx in p->scx.bpf_priv
  2026-12-06  5:37 [PATCH v3 0/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
                   ` (2 preceding siblings ...)
  2026-12-06  5:37 ` [PATCH v3 3/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
@ 2026-12-06  5:37 ` Changwoo Min
  2026-12-06  5:56   ` sashiko-bot
  2026-12-06  5:37 ` [PATCH v3 5/6] selftests/sched_ext: Test p->scx.bpf_priv across class changes Changwoo Min
  2026-12-06  5:37 ` [PATCH v3 6/6] selftests/sched_ext: Test task field reset across sub-scheduler handoffs Changwoo Min
  5 siblings, 1 reply; 12+ messages in thread
From: Changwoo Min @ 2026-12-06  5:37 UTC (permalink / raw)
  To: tj, void, arighi, changwoo
  Cc: david.dai, Gavin Guo, kernel-dev, sched-ext, linux-kernel

Show how a scheduler uses p->scx.bpf_priv. lookup_task_ctx() runs in most
qmap callbacks and costs a task storage lookup each time. qmap_enable()
now caches the task_ctx arena pointer in the field, and lookup_task_ctx()
takes it with a single load, falling back to task storage otherwise.
qmap_exit_task() clears the field before freeing the task_ctx.

The field holds whatever the sched owning the task stored, and a qmap
sched also sees the tasks of its sub-scheds, e.g. when dumping. So the
cached value is tagged with scx_bpf_sched_id(): the upper 32 bits hold
the id with bit 31 set, the lower 32 bits the pointer's. Ids are never
reused, so values of other scheds, including unloaded ones, never match.
The pointer is rebuilt from the upper 32 bits all of the arena's pointers
share.

An arena pointer is a user space address, whose most significant bit is
always zero. Bit 31 of the tag is the most significant bit of the cached
value, and setting it to 1 makes the value an invalid user space address,
for foolproofing.

Signed-off-by: Changwoo Min <changwoo@igalia.com>
---
 tools/sched_ext/scx_qmap.bpf.c | 69 ++++++++++++++++++++++++++++++++--
 1 file changed, 65 insertions(+), 4 deletions(-)

diff --git a/tools/sched_ext/scx_qmap.bpf.c b/tools/sched_ext/scx_qmap.bpf.c
index 3951f1f6e3c6..90237a1ce38a 100644
--- a/tools/sched_ext/scx_qmap.bpf.c
+++ b/tools/sched_ext/scx_qmap.bpf.c
@@ -9,6 +9,7 @@
  * - BPF arena for scheduler state.
  * - Core-sched support.
  * - Hierarchical sub-scheduling: delegating cpus to child cgroup schedulers.
+ * - Caching the per-task context in p->scx.bpf_priv.
  *
  * scx_qmap is often used to exercise sched_ext features as they land. It is
  * coupled with the kernel it ships with and uses its sched_ext interfaces
@@ -256,12 +257,49 @@ static s32 pick_direct_dispatch_cid(struct task_struct *p, s32 prev_cid,
  */
 #define QMAP_TOUCH_ARENA() do { asm volatile("" :: "r"(&arena)); } while (0)
 
+/*
+ * p->scx.bpf_priv caches @p's task_ctx so that lookup_task_ctx() takes a load
+ * instead of a task storage lookup. The field holds whatever the sched owning
+ * @p stored, and a qmap sched also sees tasks of its sub-scheds, e.g. in
+ * qmap_core_sched_before() and qmap_dump_task(). So the cached value carries
+ * this sched's id as a tag:
+ *
+ *   task_ctx_key
+ *     63-32  upper 32 bits of the arena's pointers
+ *     31     1, TASK_CTX_TAG_BIT
+ *     30-0   id from scx_bpf_sched_id(), 1 <= id < 2^31
+ *
+ *   p->scx.bpf_priv
+ *     63     1, TASK_CTX_TAG_BIT
+ *     62-32  id
+ *     31-0   lower 32 bits of @p's task_ctx pointer
+ *
+ * The arena never crosses a 4G boundary, so all its pointers share the upper
+ * 32 bits. Ids are never reused, so a value left by another sched, including
+ * one that has since unloaded, never matches. An arena pointer is a user space
+ * address, whose most significant bit is always zero. Bit 31 of the tag is the
+ * most significant bit of p->scx.bpf_priv, and setting it to 1 makes the
+ * cached value an invalid user space address, for foolproofing.
+ *
+ * qmap_enable() sets the value. The first call also sets task_ctx_key, which
+ * then never changes. qmap_exit_task() clears the value before freeing the
+ * task_ctx, as the kernel clears it only after ops.exit_task().
+ */
+#define TASK_CTX_TAG_BIT	(1U << 31)
+
+static u64 task_ctx_key;
+
 static task_ctx_t *lookup_task_ctx(struct task_struct *p)
 {
 	struct task_ctx_stor_val *v;
+	u64 key = READ_ONCE(task_ctx_key);
+	u64 priv = scx_bpf_task_priv(p);
 
 	QMAP_TOUCH_ARENA();
 
+	if (key && (u32)(priv >> 32) == (u32)key)
+		return (task_ctx_t *)((key & ~0xffffffffULL) | (u32)priv);
+
 	v = bpf_task_storage_get(&task_ctx_stor, p, 0, 0);
 	if (!v || !v->taskc)
 		return NULL;
@@ -1062,12 +1100,36 @@ s32 BPF_STRUCT_OPS_SLEEPABLE(qmap_init_task, struct task_struct *p,
 	return 0;
 }
 
+void BPF_STRUCT_OPS(qmap_enable, struct task_struct *p,
+		    struct scx_enable_args *args)
+{
+	task_ctx_t *taskc = lookup_task_ctx(p);
+	u64 key = READ_ONCE(task_ctx_key);
+	u64 id;
+
+	if (!taskc)
+		return;
+
+	if (!key) {
+		id = scx_bpf_sched_id();
+		if (!id || id >= TASK_CTX_TAG_BIT)
+			return;
+		key = ((u64)taskc & ~0xffffffffULL) | TASK_CTX_TAG_BIT | (u32)id;
+		WRITE_ONCE(task_ctx_key, key);
+	}
+
+	scx_bpf_task_set_priv(p, (u64)(u32)key << 32 | (u32)(u64)taskc);
+}
+
 void BPF_STRUCT_OPS(qmap_exit_task, struct task_struct *p,
 		    struct scx_exit_task_args *args)
 {
 	struct task_ctx_stor_val *v;
 	task_ctx_t *taskc;
 
+	/* Don't let lookup_task_ctx() return @p's task_ctx once it's freed */
+	scx_bpf_task_set_priv(p, 0);
+
 	v = bpf_task_storage_get(&task_ctx_stor, p, NULL, 0);
 	if (!v || !v->taskc)
 		return;
@@ -1124,17 +1186,15 @@ void BPF_STRUCT_OPS(qmap_dump_cid, struct scx_dump_ctx *dctx, s32 cid, bool idle
 
 void BPF_STRUCT_OPS(qmap_dump_task, struct scx_dump_ctx *dctx, struct task_struct *p)
 {
-	struct task_ctx_stor_val *v;
 	task_ctx_t *taskc;
 
 	QMAP_TOUCH_ARENA();
 
 	if (suppress_dump)
 		return;
-	v = bpf_task_storage_get(&task_ctx_stor, p, NULL, 0);
-	if (!v || !v->taskc)
+	taskc = lookup_task_ctx(p);
+	if (!taskc)
 		return;
-	taskc = v->taskc;
 
 	scx_bpf_dump("QMAP: force_local=%d core_sched_seq=%llu",
 		     taskc->force_local, taskc->core_sched_seq);
@@ -2252,6 +2312,7 @@ SCX_OPS_CID_DEFINE(qmap_ops,
 	       .set_cmask		= (void *)qmap_set_cmask,
 	       .update_idle		= (void *)qmap_update_idle,
 	       .init_task		= (void *)qmap_init_task,
+	       .enable			= (void *)qmap_enable,
 	       .exit_task		= (void *)qmap_exit_task,
 	       .dump			= (void *)qmap_dump,
 	       .dump_cid		= (void *)qmap_dump_cid,
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v3 5/6] selftests/sched_ext: Test p->scx.bpf_priv across class changes
  2026-12-06  5:37 [PATCH v3 0/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
                   ` (3 preceding siblings ...)
  2026-12-06  5:37 ` [PATCH v3 4/6] sched_ext: scx_qmap: Cache task_ctx in p->scx.bpf_priv Changwoo Min
@ 2026-12-06  5:37 ` Changwoo Min
  2026-12-06  5:59   ` sashiko-bot
  2026-12-06  5:37 ` [PATCH v3 6/6] selftests/sched_ext: Test task field reset across sub-scheduler handoffs Changwoo Min
  5 siblings, 1 reply; 12+ messages in thread
From: Changwoo Min @ 2026-12-06  5:37 UTC (permalink / raw)
  To: tj, void, arighi, changwoo
  Cc: david.dai, Gavin Guo, kernel-dev, sched-ext, linux-kernel

Under a partial-switch scheduler that sets p->scx.bpf_priv from
ops.enable(), ops.disable() and ops.exit_task(), move the test task
through SCHED_EXT, SCHED_OTHER and SCHED_EXT again, then unload the
scheduler. After each step, a syscall program reads the value and sets
its own with no lock held. The task stays on the scheduler across the
class changes, so the value must survive them and the program's write
must succeed. After the unload, the value must be cleared and the write
must fail.

The task also forks while on SCHED_EXT. The child must start with the
value cleared. The child's ops.enable() runs in the parent under the
child's rq lock, and its write to the parent must fail.

Signed-off-by: Changwoo Min <changwoo@igalia.com>
---
 tools/testing/selftests/sched_ext/Makefile    |   1 +
 .../selftests/sched_ext/task_bpf_priv.bpf.c   | 129 ++++++++++++
 .../selftests/sched_ext/task_bpf_priv.c       | 195 ++++++++++++++++++
 3 files changed, 325 insertions(+)
 create mode 100644 tools/testing/selftests/sched_ext/task_bpf_priv.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/task_bpf_priv.c

diff --git a/tools/testing/selftests/sched_ext/Makefile b/tools/testing/selftests/sched_ext/Makefile
index ef59c463cd33..1ab274250403 100644
--- a/tools/testing/selftests/sched_ext/Makefile
+++ b/tools/testing/selftests/sched_ext/Makefile
@@ -201,6 +201,7 @@ auto-test-targets :=			\
 	sched_id			\
 	sub_caps_kfunc			\
 	sub_core_caps			\
+	task_bpf_priv			\
 	test_example			\
 	total_bw			\
 	unlocked_kfunc			\
diff --git a/tools/testing/selftests/sched_ext/task_bpf_priv.bpf.c b/tools/testing/selftests/sched_ext/task_bpf_priv.bpf.c
new file mode 100644
index 000000000000..8dec22de5288
--- /dev/null
+++ b/tools/testing/selftests/sched_ext/task_bpf_priv.bpf.c
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A BPF program for testing p->scx.bpf_priv.
+ *
+ * Copyright (c) 2026 Meta Platforms, Inc. and affiliates.
+ * Author: Changwoo Min <changwoo@igalia.com>
+ */
+#include <scx/common.bpf.h>
+
+char _license[] SEC("license") = "GPL";
+
+UEI_DEFINE(uei); /* Error handling */
+
+/*
+ * The value every op stores. It doesn't carry the task's pid, which user space
+ * sees in its own PID namespace while p->pid is in the initial one.
+ */
+#define PRIV_MAGIC	0x5c7da7a05c7da7a0ULL
+
+/* Results of ops.enable() */
+u64 nr_enable, nr_enable_nonzero, nr_enable_set_fail;
+
+/* Sets on another task from ops.enable(), which must all fail */
+u64 nr_other_try, nr_other_set;
+
+/* The test task's tgid, set by set_target() */
+s32 target_tgid;
+
+/* Whether @p is the test task or its child */
+static bool is_target(struct task_struct *p)
+{
+	return p->tgid == target_tgid || p->real_parent->tgid == target_tgid;
+}
+
+/* Results of ops.disable() and ops.exit_task() */
+u64 nr_disable, nr_disable_set_fail, nr_exit, nr_exit_zero, nr_exit_set_fail;
+
+/* The value probe() stores, set by user space */
+u64 probe_val;
+
+/* Results of the last probe() run, overwritten by every run */
+u64 probe_priv;
+bool probe_set_ret;
+
+void BPF_STRUCT_OPS(task_bpf_priv_enable, struct task_struct *p)
+{
+	struct task_struct *cur = bpf_get_current_task_btf();
+
+	if (!is_target(p))
+		return;
+
+	__sync_fetch_and_add(&nr_enable, 1);
+	if (p->scx.bpf_priv)
+		__sync_fetch_and_add(&nr_enable_nonzero, 1);
+	if (!scx_bpf_task_set_priv(p, PRIV_MAGIC))
+		__sync_fetch_and_add(&nr_enable_set_fail, 1);
+
+	/*
+	 * On the target's fork, @p is the child and @cur the parent. Setting
+	 * @cur must fail, as this op holds @p's rq lock, not @cur's.
+	 */
+	if (cur != p && is_target(cur)) {
+		__sync_fetch_and_add(&nr_other_try, 1);
+		if (scx_bpf_task_set_priv(cur, PRIV_MAGIC))
+			__sync_fetch_and_add(&nr_other_set, 1);
+	}
+}
+
+void BPF_STRUCT_OPS(task_bpf_priv_disable, struct task_struct *p)
+{
+	if (!is_target(p))
+		return;
+
+	__sync_fetch_and_add(&nr_disable, 1);
+	if (!scx_bpf_task_set_priv(p, PRIV_MAGIC))
+		__sync_fetch_and_add(&nr_disable_set_fail, 1);
+}
+
+void BPF_STRUCT_OPS(task_bpf_priv_exit_task, struct task_struct *p,
+		    struct scx_exit_task_args *args)
+{
+	if (!is_target(p))
+		return;
+
+	/* @p is still on this scheduler, so the value is still there */
+	__sync_fetch_and_add(&nr_exit, 1);
+	if (!p->scx.bpf_priv)
+		__sync_fetch_and_add(&nr_exit_zero, 1);
+	if (!scx_bpf_task_set_priv(p, PRIV_MAGIC))
+		__sync_fetch_and_add(&nr_exit_set_fail, 1);
+}
+
+void BPF_STRUCT_OPS(task_bpf_priv_exit, struct scx_exit_info *ei)
+{
+	UEI_RECORD(uei, ei);
+}
+
+/* Record the calling task, the test task, as the target */
+SEC("syscall")
+int set_target(void *ctx)
+{
+	target_tgid = bpf_get_current_task_btf()->tgid;
+	return 0;
+}
+
+/*
+ * Read the calling task's value, then set it to probe_val with no lock held.
+ * Only BPF_PROG_TEST_RUN from the test runs this program, synchronously in the
+ * test task, so the current task is the task under test.
+ */
+SEC("syscall")
+int probe(void *ctx)
+{
+	struct task_struct *p = bpf_get_current_task_btf();
+
+	probe_priv = p->scx.bpf_priv;
+	probe_set_ret = scx_bpf_task_set_priv(p, probe_val);
+	return 0;
+}
+
+SEC(".struct_ops.link")
+struct sched_ext_ops task_bpf_priv_ops = {
+	.enable			= (void *)task_bpf_priv_enable,
+	.disable		= (void *)task_bpf_priv_disable,
+	.exit_task		= (void *)task_bpf_priv_exit_task,
+	.exit			= (void *)task_bpf_priv_exit,
+	.flags			= SCX_OPS_SWITCH_PARTIAL,
+	.name			= "task_bpf_priv",
+};
diff --git a/tools/testing/selftests/sched_ext/task_bpf_priv.c b/tools/testing/selftests/sched_ext/task_bpf_priv.c
new file mode 100644
index 000000000000..bfdeab327375
--- /dev/null
+++ b/tools/testing/selftests/sched_ext/task_bpf_priv.c
@@ -0,0 +1,195 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Test for p->scx.bpf_priv across class changes, fork and unload.
+ *
+ * Copyright (c) 2026 Meta Platforms, Inc. and affiliates.
+ * Author: Changwoo Min <changwoo@igalia.com>
+ */
+#include <bpf/bpf.h>
+#include <sched.h>
+#include <scx/common.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include "task_bpf_priv.bpf.skel.h"
+#include "scx_test.h"
+
+#define SCHED_EXT	7
+/* Must match task_bpf_priv.bpf.c */
+#define PRIV_MAGIC	0x5c7da7a05c7da7a0ULL
+#define PROBE_VAL	0x9a0be9a0be9a0be0ULL
+
+static int set_policy(int policy)
+{
+	struct sched_param param = { .sched_priority = 0 };
+
+	return sched_setscheduler(0, policy, &param);
+}
+
+/* Run @prog on this task and return its result */
+static int run_prog(struct bpf_program *prog)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, topts);
+
+	return bpf_prog_test_run_opts(bpf_program__fd(prog), &topts) ?:
+	       topts.retval;
+}
+
+/* Read this task's value, then set it to PROBE_VAL with no lock held */
+static int probe(struct task_bpf_priv *skel)
+{
+	skel->bss->probe_val = PROBE_VAL;
+	return run_prog(skel->progs.probe);
+}
+
+static enum scx_test_status steps(struct task_bpf_priv *skel,
+				  struct bpf_link **link)
+{
+	int status;
+	pid_t pid;
+
+	/*
+	 * ops.enable(), ops.disable() and ops.exit_task() store PRIV_MAGIC in
+	 * this task's value. Each probe() reads the value and then replaces it
+	 * with PROBE_VAL. So a read of PRIV_MAGIC shows one of those ops stored
+	 * it since the last probe(), and a read of PROBE_VAL shows none did.
+	 */
+
+	/* Step 1: Switch this task to SCHED_EXT */
+	SCX_FAIL_IF(set_policy(SCHED_EXT), "Failed to switch to SCHED_EXT");
+
+	/*
+	 * %SCX_OPS_SWITCH_PARTIAL takes only SCHED_EXT tasks. Switching makes
+	 * ops.enable() set the value. probe() must read it back and replace it.
+	 */
+	SCX_FAIL_IF(probe(skel), "Failed to run probe()");
+	SCX_EQ(skel->bss->probe_priv, PRIV_MAGIC);
+	SCX_EQ(skel->bss->probe_set_ret, true);
+
+	/* Step 2: Fork a child on SCHED_EXT */
+	pid = fork();
+	SCX_FAIL_IF(pid < 0, "Failed to fork");
+	if (pid == 0)
+		_exit(0);
+	SCX_FAIL_IF(waitpid(pid, &status, 0) != pid,
+		    "Failed to wait for the child");
+	SCX_FAIL_IF(!WIFEXITED(status) || WEXITSTATUS(status),
+		    "The child failed");
+
+	/*
+	 * The child must not inherit the value, which ops.enable() checks. The
+	 * child's ops.enable() can't set this task's value either, as it isn't
+	 * called for this task, so probe() must read its own earlier store.
+	 */
+	SCX_FAIL_IF(probe(skel), "Failed to run probe()");
+	SCX_EQ(skel->bss->probe_priv, PROBE_VAL);
+	SCX_EQ(skel->bss->probe_set_ret, true);
+
+	/* Step 3: Switch this task to SCHED_OTHER */
+	SCX_FAIL_IF(set_policy(SCHED_OTHER), "Failed to switch to SCHED_OTHER");
+
+	/*
+	 * %SCX_OPS_SWITCH_PARTIAL leaves SCHED_OTHER tasks on the fair class.
+	 * The task stays on the scheduler, so the value ops.disable() set
+	 * survives, and probe() can still set it.
+	 */
+	SCX_FAIL_IF(probe(skel), "Failed to run probe()");
+	SCX_EQ(skel->bss->probe_priv, PRIV_MAGIC);
+	SCX_EQ(skel->bss->probe_set_ret, true);
+
+	/*
+	 * Step 4: Switch this task back to SCHED_EXT. ops.enable() finds the
+	 * value probe() set and sets its own.
+	 */
+	SCX_FAIL_IF(set_policy(SCHED_EXT), "Failed to switch to SCHED_EXT");
+	SCX_FAIL_IF(probe(skel), "Failed to run probe()");
+	SCX_EQ(skel->bss->probe_priv, PRIV_MAGIC);
+	SCX_EQ(skel->bss->probe_set_ret, true);
+
+	/* Step 5: Unload the scheduler */
+	SCX_ASSERT_ALIVE(skel, uei);
+	bpf_link__destroy(*link);
+	*link = NULL;
+
+	/*
+	 * The scheduler must exit by unregistration, not by an error. The task
+	 * left the scheduler, so the kernel cleared the value after
+	 * ops.exit_task(), and probe() must read 0 and fail to set it.
+	 */
+	SCX_EQ(skel->data->uei.kind, EXIT_KIND(SCX_EXIT_UNREG));
+	SCX_FAIL_IF(probe(skel), "Failed to run probe()");
+	SCX_EQ(skel->bss->probe_priv, 0);
+	SCX_EQ(skel->bss->probe_set_ret, false);
+
+	/*
+	 * ops.enable() ran twice for this task and once for the child. Only the
+	 * one in step 4 found a value, the one probe() left.
+	 */
+	SCX_EQ(skel->bss->nr_enable, 3);
+	SCX_EQ(skel->bss->nr_enable_nonzero, 1);
+	SCX_EQ(skel->bss->nr_enable_set_fail, 0);
+	SCX_EQ(skel->bss->nr_other_try, 1);
+	SCX_EQ(skel->bss->nr_other_set, 0);
+
+	/*
+	 * ops.disable() ran for this task in steps 3 and 5 and once for the
+	 * child, and ops.exit_task() ran for this task in step 5 and for the
+	 * child. The task was on the scheduler in all of them, so each found
+	 * the value and could set it.
+	 */
+	SCX_EQ(skel->bss->nr_disable, 3);
+	SCX_EQ(skel->bss->nr_disable_set_fail, 0);
+	SCX_EQ(skel->bss->nr_exit, 2);
+	SCX_EQ(skel->bss->nr_exit_zero, 0);
+	SCX_EQ(skel->bss->nr_exit_set_fail, 0);
+
+	return SCX_TEST_PASS;
+}
+
+static enum scx_test_status run(void *ctx)
+{
+	enum scx_test_status status = SCX_TEST_FAIL;
+	struct task_bpf_priv *skel;
+	struct bpf_link *link = NULL;
+
+	skel = task_bpf_priv__open();
+	SCX_FAIL_IF(!skel, "Failed to open skel");
+	SCX_ENUM_INIT(skel);
+	if (task_bpf_priv__load(skel)) {
+		SCX_ERR("Failed to load skel");
+		goto out;
+	}
+	if (bpf_program__assoc_struct_ops(skel->progs.probe,
+					  skel->maps.task_bpf_priv_ops, NULL)) {
+		SCX_ERR("Failed to associate probe with task_bpf_priv_ops");
+		goto out;
+	}
+
+	/* Before the attach, so that no op sees target_tgid unset */
+	if (run_prog(skel->progs.set_target)) {
+		SCX_ERR("Failed to set the target");
+		goto out;
+	}
+
+	link = bpf_map__attach_struct_ops(skel->maps.task_bpf_priv_ops);
+	if (!link) {
+		SCX_ERR("Failed to attach struct_ops");
+		goto out;
+	}
+
+	status = steps(skel, &link);
+
+out:
+	/* Restore the policy even if a step failed */
+	set_policy(SCHED_OTHER);
+	bpf_link__destroy(link);
+	task_bpf_priv__destroy(skel);
+
+	return status;
+}
+
+struct scx_test task_bpf_priv = {
+	.name = "task_bpf_priv",
+	.description = "Verify p->scx.bpf_priv across class changes",
+	.run = run,
+};
+REGISTER_SCX_TEST(&task_bpf_priv)
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH v3 6/6] selftests/sched_ext: Test task field reset across sub-scheduler handoffs
  2026-12-06  5:37 [PATCH v3 0/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
                   ` (4 preceding siblings ...)
  2026-12-06  5:37 ` [PATCH v3 5/6] selftests/sched_ext: Test p->scx.bpf_priv across class changes Changwoo Min
@ 2026-12-06  5:37 ` Changwoo Min
  2026-12-06  6:06   ` sashiko-bot
  5 siblings, 1 reply; 12+ messages in thread
From: Changwoo Min @ 2026-12-06  5:37 UTC (permalink / raw)
  To: tj, void, arighi, changwoo
  Cc: david.dai, Gavin Guo, kernel-dev, sched-ext, linux-kernel

A task handed between a root scheduler and a sub-scheduler must not
carry the bpf_priv and dsq_vtime of the scheduler it left, even when that
scheduler writes them from ops.exit_task().

Load one scheduler twice, as the root and as a sub-scheduler on a cgroup.
A task in that cgroup goes to the sub-scheduler when it attaches and
back to the root when it detaches. Both schedulers set bpf_priv from
ops.enable(), and set bpf_priv and dsq_vtime from ops.exit_task(). Every
ops.enable() must find both fields cleared.

The receiving scheduler's ops.init_task() runs while the task is still
on the other scheduler. It must see the task as not its own and fail to
set bpf_priv, and scx_task_sched_id() there must report the other
scheduler, which a test with a single scheduler can't show.

The test skips where sub-schedulers aren't supported.

Signed-off-by: Changwoo Min <changwoo@igalia.com>
---
 tools/testing/selftests/sched_ext/Makefile    |   1 +
 .../selftests/sched_ext/sub_handoff.bpf.c     | 166 +++++++++
 .../testing/selftests/sched_ext/sub_handoff.c | 341 ++++++++++++++++++
 3 files changed, 508 insertions(+)
 create mode 100644 tools/testing/selftests/sched_ext/sub_handoff.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/sub_handoff.c

diff --git a/tools/testing/selftests/sched_ext/Makefile b/tools/testing/selftests/sched_ext/Makefile
index 1ab274250403..1dcaf60c5b33 100644
--- a/tools/testing/selftests/sched_ext/Makefile
+++ b/tools/testing/selftests/sched_ext/Makefile
@@ -201,6 +201,7 @@ auto-test-targets :=			\
 	sched_id			\
 	sub_caps_kfunc			\
 	sub_core_caps			\
+	sub_handoff			\
 	task_bpf_priv			\
 	test_example			\
 	total_bw			\
diff --git a/tools/testing/selftests/sched_ext/sub_handoff.bpf.c b/tools/testing/selftests/sched_ext/sub_handoff.bpf.c
new file mode 100644
index 000000000000..183ec98d9469
--- /dev/null
+++ b/tools/testing/selftests/sched_ext/sub_handoff.bpf.c
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A cid-form scheduler for the sub_handoff selftest, loaded twice: as the root
+ * and as a sub-scheduler on a cgroup.
+ *
+ * Copyright (c) 2026 Meta Platforms, Inc. and affiliates.
+ * Author: Changwoo Min <changwoo@igalia.com>
+ */
+#include <scx/common.bpf.h>
+
+char _license[] SEC("license") = "GPL";
+
+#define PRIV_MAGIC	0x5c7da7a000000000ULL
+#define VTIME_MAGIC	0x5c7d7173e0000000ULL
+
+struct {
+	__uint(type, BPF_MAP_TYPE_ARENA);
+	__uint(map_flags, BPF_F_MMAPABLE);
+	__uint(max_entries, 1 << 4);
+} arena SEC(".maps");
+
+u64 __arena_global arena_touch;
+
+/* The task handed between the schedulers, set by set_target() */
+s32 target_pid;
+
+/* The same task's pid in user space's PID namespace, set by user space */
+s32 target_vpid;
+
+/* ops.enable() calls on the target, and those that saw a value left behind */
+u64 nr_enable, nr_stale_priv, nr_stale_vtime;
+
+/* Failed writes that the checks above depend on */
+u64 nr_enable_set_fail, nr_exit_vtime_fail;
+
+/* ops.exit_task() calls on the target, and those that failed to set bpf_priv */
+u64 nr_exit, nr_exit_set_fail;
+
+/*
+ * ops.init_task() calls on the target, those that saw a bpf_priv, those that
+ * found the target on this scheduler, and those that set bpf_priv
+ */
+u64 nr_init, nr_init_priv, nr_init_own, nr_init_set;
+
+/* This scheduler's id, and the target's owner id at ops.init_task() */
+u64 sched_id, init_owner_id;
+
+/* ops.enable() calls that didn't find the target on this scheduler */
+u64 nr_enable_not_own;
+
+UEI_DEFINE(uei);
+
+s32 BPF_STRUCT_OPS(sub_handoff_select_cid, struct task_struct *p, s32 prev_cid,
+		   u64 wake_flags)
+{
+	return prev_cid;
+}
+
+void BPF_STRUCT_OPS(sub_handoff_enqueue, struct task_struct *p, u64 enq_flags)
+{
+	scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, enq_flags);
+}
+
+void BPF_STRUCT_OPS(sub_handoff_enable, struct task_struct *p,
+		    struct scx_enable_args *args)
+{
+	if (p->pid != target_pid)
+		return;
+
+	if (scx_task_sched_id(p) != scx_bpf_sched_id())
+		__sync_fetch_and_add(&nr_enable_not_own, 1);
+	if (p->scx.bpf_priv)
+		__sync_fetch_and_add(&nr_stale_priv, 1);
+	if (p->scx.dsq_vtime)
+		__sync_fetch_and_add(&nr_stale_vtime, 1);
+
+	if (!scx_bpf_task_set_priv(p, PRIV_MAGIC | (u32)p->pid))
+		__sync_fetch_and_add(&nr_enable_set_fail, 1);
+	__sync_fetch_and_add(&nr_enable, 1);
+}
+
+/*
+ * @p is not on this scheduler yet. On a handoff, it is still on the other
+ * scheduler, whose bpf_priv this sees and must not be able to set.
+ */
+s32 BPF_STRUCT_OPS(sub_handoff_init_task, struct task_struct *p,
+		   struct scx_init_task_args *args)
+{
+	u64 owner;
+
+	if (p->pid != target_pid)
+		return 0;
+
+	__sync_fetch_and_add(&nr_init, 1);
+	if (p->scx.bpf_priv)
+		__sync_fetch_and_add(&nr_init_priv, 1);
+	owner = scx_task_sched_id(p);
+	init_owner_id = owner;
+	if (owner == scx_bpf_sched_id())
+		__sync_fetch_and_add(&nr_init_own, 1);
+	if (scx_bpf_task_set_priv(p, PRIV_MAGIC | (u32)p->pid))
+		__sync_fetch_and_add(&nr_init_set, 1);
+	return 0;
+}
+
+/*
+ * @p is still on this scheduler, so both writes succeed. Neither may reach the
+ * scheduler @p moves to.
+ */
+void BPF_STRUCT_OPS(sub_handoff_exit_task, struct task_struct *p,
+		    struct scx_exit_task_args *args)
+{
+	if (p->pid != target_pid)
+		return;
+
+	__sync_fetch_and_add(&nr_exit, 1);
+	if (!scx_bpf_task_set_priv(p, PRIV_MAGIC | (u32)p->pid))
+		__sync_fetch_and_add(&nr_exit_set_fail, 1);
+	if (!scx_bpf_task_set_dsq_vtime(p, VTIME_MAGIC))
+		__sync_fetch_and_add(&nr_exit_vtime_fail, 1);
+}
+
+s32 BPF_STRUCT_OPS_SLEEPABLE(sub_handoff_sub_attach,
+			     struct scx_sub_attach_args *args)
+{
+	return 0;
+}
+
+s32 BPF_STRUCT_OPS_SLEEPABLE(sub_handoff_init)
+{
+	arena_touch++;
+	sched_id = scx_bpf_sched_id();
+	return 0;
+}
+
+void BPF_STRUCT_OPS(sub_handoff_exit, struct scx_exit_info *ei)
+{
+	UEI_RECORD(uei, ei);
+}
+
+struct task_struct *bpf_task_from_vpid(s32 vpid) __ksym;
+
+/* p->pid is in the initial PID namespace, which user space may not be in */
+SEC("syscall")
+int set_target(void *ctx)
+{
+	struct task_struct *p = bpf_task_from_vpid(target_vpid);
+
+	if (!p)
+		return -ESRCH;
+	target_pid = p->pid;
+	bpf_task_release(p);
+	return 0;
+}
+
+SCX_OPS_CID_DEFINE(sub_handoff_ops,
+		   .select_cid		= (void *)sub_handoff_select_cid,
+		   .enqueue		= (void *)sub_handoff_enqueue,
+		   .init_task		= (void *)sub_handoff_init_task,
+		   .enable		= (void *)sub_handoff_enable,
+		   .exit_task		= (void *)sub_handoff_exit_task,
+		   .sub_attach		= (void *)sub_handoff_sub_attach,
+		   .init		= (void *)sub_handoff_init,
+		   .exit		= (void *)sub_handoff_exit,
+		   .flags		= SCX_OPS_SWITCH_PARTIAL,
+		   .name		= "sub_handoff");
diff --git a/tools/testing/selftests/sched_ext/sub_handoff.c b/tools/testing/selftests/sched_ext/sub_handoff.c
new file mode 100644
index 000000000000..e79eea4c9542
--- /dev/null
+++ b/tools/testing/selftests/sched_ext/sub_handoff.c
@@ -0,0 +1,341 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Verify that a task handed between a root scheduler and a sub-scheduler
+ * arrives without the p->scx.bpf_priv and dsq_vtime of the scheduler it left,
+ * even when that scheduler writes them from ops.exit_task().
+ *
+ * Copyright (c) 2026 Meta Platforms, Inc. and affiliates.
+ * Author: Changwoo Min <changwoo@igalia.com>
+ */
+#define _GNU_SOURCE
+#include <bpf/bpf.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <sched.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+#include <scx/common.h>
+
+#include "cgroup_util.h"
+#include "scx_test.h"
+#include "sub_handoff.bpf.skel.h"
+
+#ifndef SCHED_EXT
+#define SCHED_EXT	7
+#endif
+
+/* As long as the longest sched_ext watchdog timeout */
+#define WAIT_TIMEOUT_MS	30000
+
+struct sub_handoff_ctx {
+	struct sub_handoff *root_skel;
+	struct sub_handoff *sub_skel;
+	char sub_cg[PATH_MAX];
+	u64 sub_cgid;
+	bool cg_created;
+};
+
+static u64 get_cgroup_id(const char *path)
+{
+	union {
+		u64 id;
+		unsigned char bytes[8];
+	} id = {};
+	struct file_handle *handle;
+	int mount_id, ret;
+
+	handle = calloc(1, sizeof(*handle) + sizeof(id));
+	if (!handle)
+		return 0;
+	handle->handle_bytes = sizeof(id);
+	ret = name_to_handle_at(AT_FDCWD, path, handle, &mount_id, 0);
+	if (!ret && handle->handle_bytes == sizeof(id))
+		memcpy(id.bytes, handle->f_handle, sizeof(id));
+	free(handle);
+
+	return ret ? 0 : id.id;
+}
+
+static u64 now_ns(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	return (u64)ts.tv_sec * 1000000000ULL + ts.tv_nsec;
+}
+
+/* Wait until *@ptr reaches @val, return its last value */
+static u64 wait_u64(u64 *ptr, u64 val)
+{
+	u64 deadline = now_ns() + WAIT_TIMEOUT_MS * 1000000ULL;
+	u64 v;
+
+	while ((v = __atomic_load_n(ptr, __ATOMIC_ACQUIRE)) < val &&
+	       now_ns() < deadline)
+		usleep(1000);
+	return v;
+}
+
+/*
+ * Wait until @pid sleeps. /proc/PID/stat starts with "PID (COMM) STATE", and
+ * COMM may contain spaces and ')', so STATE follows the last ')'. 'S' means
+ * interruptible sleep.
+ */
+static bool wait_pid_sleeping(pid_t pid, u64 timeout_ms)
+{
+	char path[64], buf[256];
+	u64 deadline = now_ns() + timeout_ms * 1000000ULL;
+
+	snprintf(path, sizeof(path), "/proc/%d/stat", pid);
+	while (now_ns() < deadline) {
+		int fd = open(path, O_RDONLY);
+		ssize_t n = -1;
+		char *state;
+
+		if (fd >= 0) {
+			n = read(fd, buf, sizeof(buf) - 1);
+			close(fd);
+		}
+		if (n > 0) {
+			buf[n] = '\0';
+			state = strrchr(buf, ')');
+			if (state && !strncmp(state, ") S", 3))
+				return true;
+		}
+		usleep(500);
+	}
+	return false;
+}
+
+static void cleanup(void *ctx_ptr)
+{
+	struct sub_handoff_ctx *ctx = ctx_ptr;
+
+	sub_handoff__destroy(ctx->sub_skel);
+	sub_handoff__destroy(ctx->root_skel);
+	if (ctx->cg_created)
+		cg_destroy(ctx->sub_cg);
+	free(ctx);
+}
+
+static struct sub_handoff *open_and_load(u64 sub_cgid)
+{
+	struct sub_handoff *skel;
+
+	skel = sub_handoff__open();
+	if (!skel)
+		return NULL;
+	SCX_ENUM_INIT(skel);
+	skel->struct_ops.sub_handoff_ops->sub_cgroup_id = sub_cgid;
+	if (sub_handoff__load(skel)) {
+		sub_handoff__destroy(skel);
+		return NULL;
+	}
+	return skel;
+}
+
+static enum scx_test_status setup(void **ctx_ptr)
+{
+	struct sub_handoff_ctx *ctx;
+	char root[PATH_MAX];
+
+	if (!__COMPAT_struct_has_field("sched_ext_ops", "sub_cgroup_id")) {
+		printf("SKIP: sub-schedulers not supported\n");
+		return SCX_TEST_SKIP;
+	}
+
+	if (cg_find_unified_root(root, sizeof(root), NULL)) {
+		printf("SKIP: cgroup v2 root not found\n");
+		return SCX_TEST_SKIP;
+	}
+
+	ctx = calloc(1, sizeof(*ctx));
+	SCX_FAIL_IF(!ctx, "Failed to allocate context");
+
+	if (snprintf(ctx->sub_cg, sizeof(ctx->sub_cg), "%s/scx_sub_handoff_%d",
+		     root, getpid()) >= (int)sizeof(ctx->sub_cg)) {
+		cleanup(ctx);
+		SCX_FAIL("Sub cgroup path too long");
+	}
+	if (cg_create(ctx->sub_cg)) {
+		cleanup(ctx);
+		SCX_FAIL("Failed to create sub cgroup (%d)", errno);
+	}
+	ctx->cg_created = true;
+
+	ctx->sub_cgid = get_cgroup_id(ctx->sub_cg);
+	if (!ctx->sub_cgid) {
+		cleanup(ctx);
+		SCX_FAIL("Failed to read sub cgroup ID");
+	}
+
+	ctx->root_skel = open_and_load(0);
+	if (!ctx->root_skel) {
+		cleanup(ctx);
+		SCX_FAIL("Failed to load root skel");
+	}
+
+	ctx->sub_skel = open_and_load(ctx->sub_cgid);
+	if (!ctx->sub_skel) {
+		cleanup(ctx);
+		SCX_FAIL("Failed to load sub skel");
+	}
+
+	*ctx_ptr = ctx;
+	return SCX_TEST_PASS;
+}
+
+static int set_target(struct sub_handoff *skel, pid_t pid)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, topts);
+
+	skel->bss->target_vpid = pid;
+	return bpf_prog_test_run_opts(bpf_program__fd(skel->progs.set_target),
+				      &topts) ?: topts.retval;
+}
+
+static enum scx_test_status handoffs(struct sub_handoff_ctx *ctx, pid_t pid,
+				     struct bpf_link **root_link,
+				     struct bpf_link **sub_link)
+{
+	struct sub_handoff__bss *root = ctx->root_skel->bss;
+	struct sub_handoff__bss *sub = ctx->sub_skel->bss;
+	struct sched_param param = {};
+
+	SCX_FAIL_IF(set_target(ctx->root_skel, pid),
+		    "Failed to set the root's target");
+	SCX_FAIL_IF(set_target(ctx->sub_skel, pid),
+		    "Failed to set the sub-scheduler's target");
+
+	*root_link = bpf_map__attach_struct_ops(ctx->root_skel->maps.sub_handoff_ops);
+	SCX_FAIL_IF(!*root_link, "Failed to attach root scheduler");
+
+	/* Step 1: Move the target to the sub-cgroup */
+	SCX_FAIL_IF(cg_enter(ctx->sub_cg, pid), "Failed to move target into sub cgroup");
+
+	/*
+	 * %SCX_OPS_SWITCH_PARTIAL takes only SCHED_EXT tasks. Switching the
+	 * target makes the root, the only scheduler yet, enable it and set its
+	 * bpf_priv.
+	 */
+	SCX_EQ(sched_setscheduler(pid, SCHED_EXT, &param), 0);
+	SCX_EQ(wait_u64(&root->nr_enable, 1), 1);
+
+	/* Step 2: Attaching the sub-scheduler hands the target over */
+	*sub_link = bpf_map__attach_struct_ops(ctx->sub_skel->maps.sub_handoff_ops);
+	if (!*sub_link && errno == EOPNOTSUPP) {
+		printf("SKIP: sub-schedulers not supported\n");
+		return SCX_TEST_SKIP;
+	}
+	SCX_FAIL_IF(!*sub_link, "Failed to attach sub scheduler (%d)", errno);
+
+	/*
+	 * The sub-scheduler's ops.init_task() runs while the target is still on
+	 * the root. It sees the root's bpf_priv but must not be able to set it.
+	 * The root then exits the target, and its ops.exit_task() sets bpf_priv
+	 * and dsq_vtime, which the kernel must clear afterwards. Both fields
+	 * start at 0 on a clean handoff, so the sub-scheduler's ops.enable()
+	 * must see neither.
+	 */
+	SCX_EQ(wait_u64(&sub->nr_enable, 1), 1);
+	/* The sub-scheduler's ops.init_task() found the target on the root */
+	SCX_GT(root->sched_id, 0);
+	SCX_GT(sub->sched_id, root->sched_id);
+	SCX_EQ(sub->init_owner_id, root->sched_id);
+	SCX_EQ(sub->nr_init, 1);
+	SCX_EQ(sub->nr_init_priv, 1);
+	SCX_EQ(sub->nr_init_own, 0);
+	SCX_EQ(sub->nr_init_set, 0);
+	SCX_EQ(root->nr_exit, 1);
+	SCX_EQ(root->nr_exit_vtime_fail, 0);
+	SCX_EQ(root->nr_exit_set_fail, 0);
+	SCX_EQ(sub->nr_stale_priv, 0);
+	SCX_EQ(sub->nr_stale_vtime, 0);
+
+	/* Step 3: Detaching the sub-scheduler hands the target back */
+	SCX_ASSERT_ALIVE(ctx->sub_skel, uei);
+	bpf_link__destroy(*sub_link);
+	*sub_link = NULL;
+
+	/*
+	 * The same checks in the other direction, from the sub-scheduler's
+	 * ops.exit_task() to the root's second ops.enable(). The root's counters
+	 * also cover its first ops.init_task() and ops.enable(), when it loaded
+	 * and in step 1, where the target had no bpf_priv yet.
+	 */
+	SCX_EQ(wait_u64(&root->nr_enable, 2), 2);
+	SCX_FAIL_IF(!SCX_TIMED_WAIT_UEI(ctx->sub_skel, uei, WAIT_TIMEOUT_MS),
+		    "Sub-scheduler didn't exit");
+	SCX_EQ(ctx->sub_skel->data->uei.kind, EXIT_KIND(SCX_EXIT_UNREG));
+	SCX_EQ(root->nr_enable_set_fail, 0);
+	SCX_EQ(sub->nr_enable_set_fail, 0);
+	/* The root's second ops.init_task() found the target on the sub-scheduler */
+	SCX_EQ(root->init_owner_id, sub->sched_id);
+	SCX_EQ(root->nr_init, 2);
+	SCX_EQ(root->nr_init_priv, 1);
+	SCX_EQ(root->nr_init_own, 0);
+	SCX_EQ(root->nr_init_set, 0);
+	SCX_EQ(sub->nr_exit, 1);
+	SCX_EQ(sub->nr_exit_vtime_fail, 0);
+	SCX_EQ(sub->nr_exit_set_fail, 0);
+	SCX_EQ(root->nr_stale_priv, 0);
+	SCX_EQ(root->nr_stale_vtime, 0);
+	SCX_EQ(root->nr_enable_not_own, 0);
+	SCX_EQ(sub->nr_enable_not_own, 0);
+
+	/* Neither handoff may have made the root exit with an error */
+	SCX_ASSERT_ALIVE(ctx->root_skel, uei);
+	return SCX_TEST_PASS;
+}
+
+static enum scx_test_status run(void *ctx_ptr)
+{
+	struct sub_handoff_ctx *ctx = ctx_ptr;
+	struct bpf_link *root_link = NULL, *sub_link = NULL;
+	enum scx_test_status status;
+	int pfd[2];
+	pid_t pid;
+	char c;
+
+	SCX_FAIL_IF(pipe(pfd), "Failed to create pipe (%d)", errno);
+
+	/* The target sleeps through the handoffs and exits when the pipe closes */
+	pid = fork();
+	if (pid < 0) {
+		close(pfd[0]);
+		close(pfd[1]);
+		SCX_FAIL("Failed to fork target (%d)", errno);
+	}
+	if (pid == 0) {
+		close(pfd[1]);
+		_exit(read(pfd[0], &c, 1) == 0 ? 0 : 1);
+	}
+	close(pfd[0]);
+
+	if (wait_pid_sleeping(pid, WAIT_TIMEOUT_MS)) {
+		status = handoffs(ctx, pid, &root_link, &sub_link);
+	} else {
+		SCX_ERR("Target didn't go to sleep");
+		status = SCX_TEST_FAIL;
+	}
+
+	bpf_link__destroy(sub_link);
+	bpf_link__destroy(root_link);
+	close(pfd[1]);
+	waitpid(pid, NULL, 0);
+	return status;
+}
+
+struct scx_test sub_handoff = {
+	.name = "sub_handoff",
+	.description = "Verify that sub-scheduler handoffs reset the task fields",
+	.setup = setup,
+	.run = run,
+	.cleanup = cleanup,
+};
+REGISTER_SCX_TEST(&sub_handoff)
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* Re: [PATCH v3 4/6] sched_ext: scx_qmap: Cache task_ctx in p->scx.bpf_priv
  2026-12-06  5:37 ` [PATCH v3 4/6] sched_ext: scx_qmap: Cache task_ctx in p->scx.bpf_priv Changwoo Min
@ 2026-12-06  5:56   ` sashiko-bot
  0 siblings, 0 replies; 12+ messages in thread
From: sashiko-bot @ 2026-12-06  5:56 UTC (permalink / raw)
  To: Changwoo Min; +Cc: sched-ext

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] sched_ext: scx_qmap: unverified bpf_priv tag collision in
  lookup_task_ctx()
--

commit 5c944365906adb946e34a37a4704476bce3c8842
Author: Changwoo Min <changwoo@igalia.com>

sched_ext: scx_qmap: Cache task_ctx in p->scx.bpf_priv

This commit caches each task's task_ctx arena pointer in p->scx.bpf_priv
tagged with scx_bpf_sched_id(), so lookup_task_ctx() can avoid a task
storage lookup on the fast path.

> diff --git a/tools/sched_ext/scx_qmap.bpf.c b/tools/sched_ext/scx_qmap.bpf.c
> index 3951f1f6e3c6a..90237a1ce38aa 100644
> --- a/tools/sched_ext/scx_qmap.bpf.c
> +++ b/tools/sched_ext/scx_qmap.bpf.c

[ ... ]

> @@ -256,12 +257,49 @@ static s32 pick_direct_dispatch_cid(struct task_struct *p, s32 prev_cid,
>   */
>  #define QMAP_TOUCH_ARENA() do { asm volatile("" :: "r"(&arena)); } while (0)
>  
> +/*
> + * p->scx.bpf_priv caches @p's task_ctx so that lookup_task_ctx() takes a load
> + * instead of a task storage lookup. The field holds whatever the sched owning
> + * @p stored, and a qmap sched also sees tasks of its sub-scheds, e.g. in
> + * qmap_core_sched_before() and qmap_dump_task(). So the cached value carries
> + * this sched's id as a tag:
> + *
> + *   task_ctx_key
> + *     63-32  upper 32 bits of the arena's pointers
> + *     31     1, TASK_CTX_TAG_BIT
> + *     30-0   id from scx_bpf_sched_id(), 1 <= id < 2^31
> + *
> + *   p->scx.bpf_priv
> + *     63     1, TASK_CTX_TAG_BIT
> + *     62-32  id
> + *     31-0   lower 32 bits of @p's task_ctx pointer
> + *
> + * The arena never crosses a 4G boundary, so all its pointers share the upper
> + * 32 bits. Ids are never reused, so a value left by another sched, including
> + * one that has since unloaded, never matches. An arena pointer is a user space
> + * address, whose most significant bit is always zero. Bit 31 of the tag is the
> + * most significant bit of p->scx.bpf_priv, and setting it to 1 makes the
> + * cached value an invalid user space address, for foolproofing.
> + *
> + * qmap_enable() sets the value. The first call also sets task_ctx_key, which
> + * then never changes. qmap_exit_task() clears the value before freeing the
> + * task_ctx, as the kernel clears it only after ops.exit_task().
> + */
> +#define TASK_CTX_TAG_BIT	(1U << 31)
> +
> +static u64 task_ctx_key;
> +
>  static task_ctx_t *lookup_task_ctx(struct task_struct *p)
>  {
>  	struct task_ctx_stor_val *v;
> +	u64 key = READ_ONCE(task_ctx_key);
> +	u64 priv = scx_bpf_task_priv(p);
>  
>  	QMAP_TOUCH_ARENA();
>  
> +	if (key && (u32)(priv >> 32) == (u32)key)
> +		return (task_ctx_t *)((key & ~0xffffffffULL) | (u32)priv);

[Severity: Low]
Can lookup_task_ctx() return a bogus arena pointer when a non-qmap
sub-scheduler writes an arbitrary u64 to p->scx.bpf_priv?

p->scx.bpf_priv has no kernel-enforced tagging format, so a sub-scheduler
can store a value whose upper 32 bits match TASK_CTX_TAG_BIT | id (for
example, 0x80000001 when scx_qmap has id 1).

When qmap_core_sched_before() runs on that task, lookup_task_ctx()
reconstructs an unvalidated offset in scx_qmap's arena instead of returning
NULL.  Dereferencing it then reads unrelated arena memory (corrupting
core-sched ordering) or faults to 0 on an unmapped page.

The comment and commit message also overstate the guarantee, since non-reuse
of scheduler ids only prevents collisions between schedulers using this
tagging layout.

Checking scx_task_sched_id(p) against scx_bpf_sched_id() under the rq lock
(as documented on scx_bpf_task_set_priv()), or validating that the pointer
lies within qa.task_ctxs, would avoid false matches.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261206053728.2026272-1-changwoo@igalia.com?part=4

^ permalink raw reply	[flat|nested] 12+ messages in thread

* Re: [PATCH v3 5/6] selftests/sched_ext: Test p->scx.bpf_priv across class changes
  2026-12-06  5:37 ` [PATCH v3 5/6] selftests/sched_ext: Test p->scx.bpf_priv across class changes Changwoo Min
@ 2026-12-06  5:59   ` sashiko-bot
  0 siblings, 0 replies; 12+ messages in thread
From: sashiko-bot @ 2026-12-06  5:59 UTC (permalink / raw)
  To: Changwoo Min; +Cc: sched-ext

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] selftests/sched_ext: UAF dereferencing p->real_parent in
  is_target()
--

commit 126f4c58d88ef640789b0b03da1a002cdbbc0901
Author: Changwoo Min <changwoo@igalia.com>

selftests/sched_ext: Test p->scx.bpf_priv across class changes

This commit adds the task_bpf_priv sched_ext selftest to verify that
p->scx.bpf_priv persists across scheduling class changes, is cleared for
forked children and on scheduler unload, and rejects writes to other tasks.

> diff --git a/tools/testing/selftests/sched_ext/task_bpf_priv.bpf.c b/tools/testing/selftests/sched_ext/task_bpf_priv.bpf.c
> new file mode 100644
> index 0000000000000..8dec22de52888
> --- /dev/null
> +++ b/tools/testing/selftests/sched_ext/task_bpf_priv.bpf.c

[ ... ]

> +/* Whether @p is the test task or its child */
> +static bool is_target(struct task_struct *p)
> +{
> +	return p->tgid == target_tgid || p->real_parent->tgid == target_tgid;
> +}

[Severity: Medium]
Can dereferencing p->real_parent here trigger a use-after-free?

Even with SCX_OPS_SWITCH_PARTIAL, sched_ext_dead() invokes ops.exit_task()
for every exiting task on the system.  Once release_task() unlinks an
exiting task in __unhash_process(), its real_parent pointer is no longer
updated by forget_original_parent(), so the parent can exit and be freed
before sched_ext_dead() runs:

CPU0 (exiting task B)             CPU1 (parent A)
do_exit()
  exit_notify()
    release_task(B)
      __unhash_process(B)
        /* unlinked; B->real_parent still points to A */
                                  do_exit()
                                    forget_original_parent(A)
                                      /* misses unlinked B */
                                  ...
                                  free_task(A)
  ...
  sched_ext_dead(B)
    task_bpf_priv_exit_task(B)
      is_target(B)
        B->real_parent->tgid      <-- use-after-free

Because struct task_struct::real_parent is listed in BTF_TYPE_SAFE_RCU,
the verifier emits an unguarded raw load rather than BPF_PROBE_MEM, so
reading from the freed task_struct triggers a KASAN slab-use-after-free or
a kernel page fault if the slab page has been unmapped.

Instead of dereferencing p->real_parent, task_bpf_priv_enable() could
record the child's tgid when cur != p && cur->tgid == target_tgid, and
is_target() could match p->tgid against target_tgid and that recorded
child tgid.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261206053728.2026272-1-changwoo@igalia.com?part=5

^ permalink raw reply	[flat|nested] 12+ messages in thread

* Re: [PATCH v3 3/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup
  2026-12-06  5:37 ` [PATCH v3 3/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
@ 2026-12-06  6:00   ` sashiko-bot
  0 siblings, 0 replies; 12+ messages in thread
From: sashiko-bot @ 2026-12-06  6:00 UTC (permalink / raw)
  To: Changwoo Min; +Cc: sched-ext

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Medium] sched_ext: scx_bpf_task_set_priv() missing from
  scx_kfunc_ids_no_sub_caps
- [Low] sched_ext: scx_bpf_task_priv() takes non-const task_struct
  pointer
- [Low] sched_ext: 64-bit p->scx.bpf_priv accesses can tear on 32-bit
  x86 SMP
--

commit d733d17a1b2f82be9f9d84dff228752ded0286a8
Author: Changwoo Min <changwoo@igalia.com>

sched_ext: Add p->scx.bpf_priv for O(1) task context lookup

This commit adds an opaque u64 field p->scx.bpf_priv, a kfunc
scx_bpf_task_set_priv() to update it while the calling scheduler owns the
task, and a compat.bpf.h helper scx_bpf_task_priv() to read it locklessly.

> diff --git a/include/linux/sched/ext.h b/include/linux/sched/ext.h
> index f3564581c317c..a1793ab5f0c32 100644
> --- a/include/linux/sched/ext.h
> +++ b/include/linux/sched/ext.h
> @@ -277,6 +277,17 @@ struct sched_ext_entity {
>  	 */
>  	atomic64_t		slice_oob;
>  
> +	/*
> +	 * Opaque value owned by the task's scheduler, typically an arena
> +	 * pointer to its per-task context. The kernel never dereferences it.
> +	 * Set with scx_bpf_task_set_priv() while @p is on the scheduler,
> +	 * from after ops.init_task() until ops.exit_task(), and cleared
> +	 * after ops.exit_task(). Any BPF program can read it, so a tracing
> +	 * program can reach the context of the current task with a single
> +	 * load.
> +	 */
> +	u64			bpf_priv;
> +

[Severity: Low]
Can 64-bit accesses to p->scx.bpf_priv tear on 32-bit x86 SMP?

Both scx_bpf_task_set_priv() and __scx_disable_and_exit_task() update
p->scx.bpf_priv with WRITE_ONCE(), which splits a 64-bit store into two
32-bit stores on CONFIG_X86_32.  On the reader side, do_jit() in
arch/x86/net/bpf_jit_comp32.c compiles the 64-bit BPF_LDX load from
scx_bpf_task_priv() into two 32-bit mov loads.

CPU0 (writer)                 CPU1 (lockless BPF reader)
__scx_disable_and_exit_task()
  WRITE_ONCE(p->scx.bpf_priv, 0)
    store low 32 bits = 0
                              scx_bpf_task_priv()
                                load low 32 bits (0)
                                load high 32 bits (old tag)  <-- torn read
    store high 32 bits = 0

On CONFIG_X86_32 SMP, bpf_jit_supports_kfunc_call() is enabled and a
callback-less root scheduler can attach without trampoline support, allowing
a BPF_PROG_TYPE_SYSCALL program to write via scx_bpf_task_set_priv() while
another CPU reads concurrently.  A torn load can pair a matching scheduler ID
tag with a zeroed or stale payload, breaking the documented tagged-ID
lockless read contract.

> diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c
> index 343d82f328efc..4f575a19df761 100644
> --- a/kernel/sched/ext/ext.c
> +++ b/kernel/sched/ext/ext.c

[ ... ]

> @@ -12347,6 +12435,7 @@ static const struct btf_kfunc_id_set scx_kfunc_set_any = {
>  BTF_KFUNCS_START(scx_kfunc_ids_no_tracing)
>  BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
>  BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS)
> +BTF_ID_FLAGS(func, scx_bpf_task_set_priv, KF_IMPLICIT_ARGS | KF_RCU)
>  BTF_ID_FLAGS(func, scx_bpf_sub_grant, KF_IMPLICIT_ARGS)
>  BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS)
>  BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS)

[Severity: Medium]
Should scx_bpf_task_set_priv also be added to scx_kfunc_ids_no_sub_caps?

Because scx_bpf_task_set_priv is in scx_kfunc_ids_any and absent from
scx_kfunc_ids_no_sub_caps, scx_kfunc_context_filter() allows
ops.sub_caps_updated() to call it.  caps_updated_deliver() invokes
ops.sub_caps_updated() synchronously with locked_rq = NULL under
guard(irqsave)(), inheriting whatever scx_locked_rq() and kf_tasks[] state
the parent scheduler holds.

Calling scx_bpf_task_set_priv() there therefore depends on the parent's
locking context, either silently returning false when the parent holds an rq
lock or taking task_rq_lock() inside caps_updated_deliver() when called
unlocked.  Adding it to scx_kfunc_ids_no_sub_caps would match how
scx_bpf_cidperf_set() is restricted.

> diff --git a/tools/sched_ext/include/scx/compat.bpf.h b/tools/sched_ext/include/scx/compat.bpf.h
> index 4d2298bd7ac55..e8cb5f35eed08 100644
> --- a/tools/sched_ext/include/scx/compat.bpf.h
> +++ b/tools/sched_ext/include/scx/compat.bpf.h

[ ... ]

> +/* p->scx.bpf_priv, or 0 on kernels without it */
> +static __always_inline u64 scx_bpf_task_priv(struct task_struct *p)
> +{
> +	struct sched_ext_entity___bpf_priv *scx = (void *)&p->scx;
> +
> +	if (bpf_core_field_exists(scx->bpf_priv))
> +		return READ_ONCE(scx->bpf_priv);
> +	return 0;
> +}

[Severity: Low]
Should scx_bpf_task_priv() take a const struct task_struct *p?

It only performs a read-only load of p->scx.bpf_priv, while its companion
scx_task_sched_id() immediately below and the other task inspection helpers
in common.bpf.h all accept const struct task_struct *p.  Taking a non-const
pointer prevents callers with a const task pointer from using it without a
cast.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261206053728.2026272-1-changwoo@igalia.com?part=3

^ permalink raw reply	[flat|nested] 12+ messages in thread

* Re: [PATCH v3 1/6] sched_ext: Add scx_bpf_sched_id() and scx_task_sched_id()
  2026-12-06  5:37 ` [PATCH v3 1/6] sched_ext: Add scx_bpf_sched_id() and scx_task_sched_id() Changwoo Min
@ 2026-12-06  6:03   ` sashiko-bot
  0 siblings, 0 replies; 12+ messages in thread
From: sashiko-bot @ 2026-12-06  6:03 UTC (permalink / raw)
  To: Changwoo Min; +Cc: sched-ext

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] sched_ext: TOCTOU race between flags and sched loads in
  scx_task_sched_id()
--

commit e70589ddaf2c9dcb29ade05fb3583c3b7983b075
Author: Changwoo Min <changwoo@igalia.com>

sched_ext: Add scx_bpf_sched_id() and scx_task_sched_id()

This commit adds the scx_bpf_sched_id() kfunc to return the calling
scheduler's instance id and the scx_task_sched_id() BPF helper to return
the id of the scheduler owning a task.  It also updates
scx_set_task_state() to publish task state bits with a single
WRITE_ONCE().

> diff --git a/tools/sched_ext/include/scx/compat.bpf.h b/tools/sched_ext/include/scx/compat.bpf.h
> index 3520a749f8ce6..4d2298bd7ac55 100644
> --- a/tools/sched_ext/include/scx/compat.bpf.h
> +++ b/tools/sched_ext/include/scx/compat.bpf.h
> @@ -487,6 +487,67 @@ static inline void scx_bpf_task_set_lazy_resched(struct task_struct *p, bool laz

[ ... ]

> +static __always_inline u64 scx_task_sched_id(const struct task_struct *p)
> +{
> +	struct sched_ext_entity___task_id *scx = (void *)&p->scx;
> +	struct scx_sched___task_id *sch;
> +	u32 state;
> +	u64 id;
> +
> +	if (!bpf_ksym_exists(scx_bpf_sched_id___new))
> +		return 0;
> +
> +	/* A sched owns @p only after ops.init_task() */
> +	state = READ_ONCE(scx->flags) &
> +		bpf_core_enum_value(enum scx_ent_flags, SCX_TASK_STATE_MASK);
> +	if (state == bpf_core_enum_value(enum scx_ent_flags, SCX_TASK_NONE) ||
> +	    state == bpf_core_enum_value(enum scx_ent_flags, SCX_TASK_INIT_BEGIN) ||
> +	    state == bpf_core_enum_value(enum scx_ent_flags, SCX_TASK_DEAD))
> +		return 0;
> +
> +	/*
> +	 * Without CONFIG_EXT_SUB_SCHED, which @cgrp comes with, the kernel
> +	 * doesn't set p->scx.sched, and the root is the only scheduler.
> +	 */
> +	if (!bpf_core_field_exists(struct scx_sched___task_id, cgrp))
> +		return scx_bpf_sched_id();
> +
> +	/* Sleepable programs aren't in an RCU read section */
> +	bpf_rcu_read_lock();
> +	sch = scx->sched;
> +	id = sch ? sch->id : 0;
> +	bpf_rcu_read_unlock();
> +	return id;
> +}

[Severity: Low]
Can scx_task_sched_id() return a scheduler id for a task whose
ops.init_task() never ran on that scheduler?

Without CONFIG_EXT_SUB_SCHED, scx_task_sched_id() reads scx->flags and
calls scx_bpf_sched_id() outside RCU.  A sleepable BPF caller can read
an active state under root scheduler S1, get preempted across S1
teardown and S2 startup, and return S2's id before S2 initializes p:

CPU0 (sleepable BPF)              CPU1
scx_task_sched_id(p)
  READ_ONCE(scx->flags)
  /* sees SCX_TASK_ENABLED */
                                  scx_disable_workfn() /* S1 */
                                    scx_set_task_state(p, SCX_TASK_NONE)
                                    synchronize_rcu()
                                  scx_enable() /* S2 */
                                    rcu_assign_pointer(scx_root, S2)
  scx_bpf_sched_id()  <-- returns S2->id before S2 ops.init_task(p)

Because CPU0 is not inside bpf_rcu_read_lock(), synchronize_rcu() in
scx_disable_workfn() does not wait for it.  Wrapping the state check
and scx_bpf_sched_id() in bpf_rcu_read_lock() prevents this straddle.

With CONFIG_EXT_SUB_SCHED, an unlocked caller has a similar race with
scx_punt_task(), which sets p to SCX_TASK_NONE and then assigns
p->scx.sched without running ops.init_task(), letting scx_task_sched_id()
pair the pre-punt active state with the new scx->sched pointer.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261206053728.2026272-1-changwoo@igalia.com?part=1

^ permalink raw reply	[flat|nested] 12+ messages in thread

* Re: [PATCH v3 6/6] selftests/sched_ext: Test task field reset across sub-scheduler handoffs
  2026-12-06  5:37 ` [PATCH v3 6/6] selftests/sched_ext: Test task field reset across sub-scheduler handoffs Changwoo Min
@ 2026-12-06  6:06   ` sashiko-bot
  0 siblings, 0 replies; 12+ messages in thread
From: sashiko-bot @ 2026-12-06  6:06 UTC (permalink / raw)
  To: Changwoo Min; +Cc: sched-ext

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Low] selftests/sched_ext: SCX_EQ() double-evaluates calls in
  handoffs()
- [Low] selftests/sched_ext: sub_handoff.c duplicates helpers from
  sibling tests
--

commit 20ecdae3e4d6197a4eacc5c0de5f09501133284c
Author: Changwoo Min <changwoo@igalia.com>

selftests/sched_ext: Test task field reset across sub-scheduler handoffs

This commit adds the sub_handoff sched_ext selftest, which loads a cid-form
scheduler as both root and sub-scheduler to verify that p->scx.bpf_priv and
dsq_vtime are cleared across handoffs and that ops.init_task() observes the
previous owner.

> diff --git a/tools/testing/selftests/sched_ext/sub_handoff.c b/tools/testing/selftests/sched_ext/sub_handoff.c
> new file mode 100644
> index 0000000000000..e79eea4c95424
> --- /dev/null
> +++ b/tools/testing/selftests/sched_ext/sub_handoff.c
> @@ -0,0 +1,341 @@

[ ... ]

> +static u64 get_cgroup_id(const char *path)
> +{
> +	union {
> +		u64 id;
> +		unsigned char bytes[8];
> +	} id = {};
> +	struct file_handle *handle;
> +	int mount_id, ret;
> +
> +	handle = calloc(1, sizeof(*handle) + sizeof(id));
> +	if (!handle)
> +		return 0;
> +	handle->handle_bytes = sizeof(id);
> +	ret = name_to_handle_at(AT_FDCWD, path, handle, &mount_id, 0);
> +	if (!ret && handle->handle_bytes == sizeof(id))
> +		memcpy(id.bytes, handle->f_handle, sizeof(id));
> +	free(handle);
> +
> +	return ret ? 0 : id.id;
> +}
> +
> +static u64 now_ns(void)
> +{
> +	struct timespec ts;
> +
> +	clock_gettime(CLOCK_MONOTONIC, &ts);
> +	return (u64)ts.tv_sec * 1000000000ULL + ts.tv_nsec;
> +}

[ ... ]

> +static bool wait_pid_sleeping(pid_t pid, u64 timeout_ms)

[ ... ]

[Severity: Low]
Could get_cgroup_id(), now_ns(), and wait_pid_sleeping() be shared in
util.c and util.h instead of duplicated here?

All three already exist in tools/testing/selftests/sched_ext/sub_core_caps.c,
and cgroup_nr_cpus.c has another copy of get_cgroup_id() as cgroup_id().
The sched_ext selftest Makefile already links util.o into the runner binary.

[ ... ]

> +	SCX_EQ(sched_setscheduler(pid, SCHED_EXT, &param), 0);
> +	SCX_EQ(wait_u64(&root->nr_enable, 1), 1);

[ ... ]

> +	SCX_EQ(wait_u64(&sub->nr_enable, 1), 1);

[ ... ]

> +	SCX_EQ(wait_u64(&root->nr_enable, 2), 2);

[Severity: Low]
Can SCX_EQ() evaluate wait_u64() and sched_setscheduler() twice on failure?

SCX_EQ() expands _x in both the comparison and the failure message:

tools/testing/selftests/sched_ext/scx_test.h:
#define SCX_EQ(_x, _y) SCX_FAIL_IF((_x) != (_y), "Expected %s == %s (%lu == %lu)", \
				   #_x, #_y, (u64)(_x), (u64)(_y))

If wait_u64() times out after 30 seconds, the second evaluation blocks for
another 30 seconds and can print a contradictory actual value if the counter
updates in the meantime.  On failure, sched_setscheduler() is also called a
second time.

Storing each return value in a local variable before passing it to SCX_EQ()
avoids the duplicate calls.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261206053728.2026272-1-changwoo@igalia.com?part=6

^ permalink raw reply	[flat|nested] 12+ messages in thread

end of thread, other threads:[~2026-12-06  6:06 UTC | newest]

Thread overview: 12+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-06  5:37 [PATCH v3 0/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
2026-12-06  5:37 ` [PATCH v3 1/6] sched_ext: Add scx_bpf_sched_id() and scx_task_sched_id() Changwoo Min
2026-12-06  6:03   ` sashiko-bot
2026-12-06  5:37 ` [PATCH v3 2/6] selftests/sched_ext: Test " Changwoo Min
2026-12-06  5:37 ` [PATCH v3 3/6] sched_ext: Add p->scx.bpf_priv for O(1) task context lookup Changwoo Min
2026-12-06  6:00   ` sashiko-bot
2026-12-06  5:37 ` [PATCH v3 4/6] sched_ext: scx_qmap: Cache task_ctx in p->scx.bpf_priv Changwoo Min
2026-12-06  5:56   ` sashiko-bot
2026-12-06  5:37 ` [PATCH v3 5/6] selftests/sched_ext: Test p->scx.bpf_priv across class changes Changwoo Min
2026-12-06  5:59   ` sashiko-bot
2026-12-06  5:37 ` [PATCH v3 6/6] selftests/sched_ext: Test task field reset across sub-scheduler handoffs Changwoo Min
2026-12-06  6:06   ` sashiko-bot

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.