Skip to contentSkip to conversation

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

PATCH In review Changwoo Min 2 participants 8 messages Dec 1

Subsystems (3)
lore
Share & tools
lore

Changwoo Min

author reviewer
#0 lore raw

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

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_data, an opaque u64 that the task's scheduler sets with scx_bpf_task_set_data(), typically to an arena pointer to its task context. Any BPF program, tracing programs included, reads it with a plain load. The kernel clears it after ops.disable().

With sub-schedulers, a task a scheduler reaches may belong to another scheduler. scx_bpf_sched_id() and scx_bpf_task_sched_id() let a scheduler tag the value with its own id, which is never reused, and recognize its own values.

- Patch 1 adds scx_bpf_sched_id() and scx_bpf_task_sched_id().
- Patch 3 adds p->scx.bpf_data and scx_bpf_task_set_data().
- Patch 4 converts scx_qmap as an example.
- Patches 2 and 5 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 with this series. 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 (7c9543b954aa).

Changwoo Min (5):
sched_ext: Add scx_bpf_sched_id() and scx_bpf_task_sched_id() selftests/sched_ext: Test scx_bpf_sched_id() and

    scx_bpf_task_sched_id()

sched_ext: Add p->scx.bpf_data for O(1) task context lookup
sched_ext: scx_qmap: Cache task_ctx in p->scx.bpf_data selftests/sched_ext: Test p->scx.bpf_data across class changes

 include/linux/sched/ext.h                     |  12 ++
 kernel/sched/ext/ext.c                        |  89 ++++++++++++-
 tools/sched_ext/include/scx/compat.bpf.h      |  46 +++++++
 tools/sched_ext/scx_qmap.bpf.c                |  58 +++++++++
 tools/testing/selftests/sched_ext/Makefile    |   2 +
 .../selftests/sched_ext/sched_id.bpf.c        |  47 +++++++
 tools/testing/selftests/sched_ext/sched_id.c  | 103 +++++++++++++++
 .../selftests/sched_ext/task_bpf_data.bpf.c   |  64 +++++++++
 .../selftests/sched_ext/task_bpf_data.c       | 123 ++++++++++++++++++
 9 files changed, 540 insertions(+), 4 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/task_bpf_data.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/task_bpf_data.c
Signature · 1 line
2.56.1
author reviewer
#1 lore raw

PATCH 1/5 sched_ext: Add scx_bpf_sched_id() and scx_bpf_task_sched_id()

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 scx_bpf_sched_id(), the calling scheduler's id, and scx_bpf_task_sched_id(), the id of the scheduler that owns a task, both 0 for none. Any context may call them.

---
 kernel/sched/ext/ext.c                   | 35 ++++++++++++++++++++++++
 tools/sched_ext/include/scx/compat.bpf.h | 22 +++++++++++++++
 2 files changed, 57 insertions(+)
kernel/sched/ext/ext.c +35 -0
index a3cf580b0333..cdceeffbcc65 100644
@@ -11933,6 +11933,39 @@ __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_sched_id - Id of the scheduler that owns a task
+ * @p: task of interest
+ *
+ * Return the instance id of the scheduler @p is on, see scx_bpf_sched_id(), 0
+ * if @p is not on any. Without the rq lock of @p, @p may move to another
+ * scheduler right after.
+ */
+__bpf_kfunc u64 scx_bpf_task_sched_id(struct task_struct *p)
+{
+	struct scx_sched *sch;
+
+	guard(rcu)();
+	sch = scx_task_sched_rcu(p);
+	return sch ? sch->id : 0;
+}
+
 /**
  * scx_bpf_task_cid - cid a task is currently associated with
  * @p: task of interest
@@ -12255,6 +12288,8 @@ 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_sched_id, KF_RCU)
 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)
tools/sched_ext/include/scx/compat.bpf.h +22 -0
index 3520a749f8ce..41882c6497ac 100644
@@ -487,6 +487,28 @@ 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.x: Add scx_bpf_sched_id() and scx_bpf_task_sched_id(). Ids start at 1,
+ * increase monotonically and are never reused. 0 means no scheduler, including
+ * on kernels without the kfuncs.
+ */
+u64 scx_bpf_sched_id___new(void) __ksym __weak;
+u64 scx_bpf_task_sched_id___new(struct task_struct *p) __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;
+}
+
+static inline u64 scx_bpf_task_sched_id(struct task_struct *p)
+{
+	if (bpf_ksym_exists(scx_bpf_task_sched_id___new))
+		return scx_bpf_task_sched_id___new(p);
+	return 0;
+}
+
 /*
  * v7.1: New scx_bpf_dsq_reenq() that allows re-enqueues on more DSQs. This
  * will eventually deprecate scx_bpf_reenqueue_local().
Signature · 1 line
2.56.1
author reviewer
#2 lore raw

PATCH 2/5 selftests/sched_ext: Test scx_bpf_sched_id() and scx_bpf_task_sched_id()

In reply to Changwoo Min

Load a partial-switch scheduler and move the test task onto it. The task's owner id must equal the scheduler's id and be nonzero, and both must read 0 once the scheduler is unloaded. A second instance must get a larger id.

---
 tools/testing/selftests/sched_ext/Makefile    |   1 +
 .../selftests/sched_ext/sched_id.bpf.c        |  47 ++++++++
 tools/testing/selftests/sched_ext/sched_id.c  | 103 ++++++++++++++++++
 3 files changed, 151 insertions(+)
 create mode 100644 tools/testing/selftests/sched_ext/sched_id.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/sched_id.c
tools/testing/selftests/sched_ext/Makefile +1 -0
index fe63dbd53f56..ef59c463cd33 100644
@@ -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			\
tools/testing/selftests/sched_ext/sched_id.bpf.c new file +47 -0

47 lines not on this page · raw message

tools/testing/selftests/sched_ext/sched_id.c new file +103 -0

103 lines not on this page · raw message

Signature · 1 line
2.56.1
author reviewer
#3 lore raw

PATCH 3/5 sched_ext: Add p->scx.bpf_data for O(1) task context lookup

In reply to Changwoo Min

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

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

The value is valid while @p is enabled on the scheduler that set it. scx_reset_task_fields() clears it after ops.disable(), which covers @p leaving the ext class, moving to another sub-scheduler and exiting. ops.enable() runs again whenever @p comes back.

scx_bpf_task_set_data() follows the rules of scx_bpf_task_set_dsq_vtime(). It accepts any caller and refuses a task that is not enabled on the calling scheduler, except in ops.enable(), where @p is still SCX_TASK_READY. A write can race @p leaving and outlive the clear, and synchronizing such writes is left to the scheduler, as for dsq_vtime.

The value means something only to the scheduler that set it. With sub-schedulers, a task a scheduler reaches as a waker or from a tracing program may belong to another one. A scheduler can tag the value with its scx_bpf_sched_id() to recognize its own.

---
 include/linux/sched/ext.h                | 12 ++++++
 kernel/sched/ext/ext.c                   | 54 ++++++++++++++++++++++--
 tools/sched_ext/include/scx/compat.bpf.h | 24 +++++++++++
 3 files changed, 86 insertions(+), 4 deletions(-)
include/linux/sched/ext.h +12 -0
index f3564581c317..2c2ce144601d 100644
@@ -277,6 +277,18 @@ 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_data() while @p is enabled on the
+	 * scheduler, from ops.enable() on, and cleared when @p leaves the
+	 * scheduler's control, after ops.disable(). Any BPF program can read
+	 * it, so a tracing program can reach the context of the current task
+	 * with a single load. A write from outside @p's own ops can outlive
+	 * the clear, see scx_bpf_task_set_data().
+	 */
+	u64			bpf_data;
+
 	/*
 	 * Sub-sched cap rejected reenq context, valid only while
 	 * %SCX_TASK_REENQ_CAP is set. @reenq_reason_caps is the SCX_CAP_* bits
kernel/sched/ext/ext.c +50 -4

78 lines not on this page · raw message

tools/sched_ext/include/scx/compat.bpf.h +24 -0
index 41882c6497ac..a67f0e18a783 100644
@@ -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.x: Add p->scx.bpf_data and scx_bpf_task_set_data(). */
+bool scx_bpf_task_set_data___new(struct task_struct *p, u64 data) __ksym __weak;
+
+static inline bool scx_bpf_task_set_data(struct task_struct *p, u64 data)
+{
+	if (bpf_ksym_exists(scx_bpf_task_set_data___new))
+		return scx_bpf_task_set_data___new(p, data);
+	return false;
+}
+
+struct sched_ext_entity___bpf_data {
+	u64 bpf_data;
+} __attribute__((preserve_access_index));
+
+/* p->scx.bpf_data, or 0 on kernels without it */
+static __always_inline u64 scx_bpf_task_data(struct task_struct *p)
+{
+	struct sched_ext_entity___bpf_data *scx = (void *)&p->scx;
+
+	if (bpf_core_field_exists(scx->bpf_data))
+		return READ_ONCE(scx->bpf_data);
+	return 0;
+}
+
 /*
  * v7.x: Add scx_bpf_sched_id() and scx_bpf_task_sched_id(). Ids start at 1,
  * increase monotonically and are never reused. 0 means no scheduler, including
Signature · 1 line
2.56.1
reviewer
#4 lore raw

Hi Changwoo,

thanks for working at this! Then I can finally remove the ugly p->scx.dsq_vtime hack. :)

Comments below.

Quoted 41 lines · Changwoo Min

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

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

The value is valid while @p is enabled on the scheduler that set it. scx_reset_task_fields() clears it after ops.disable(), which covers @p leaving the ext class, moving to another sub-scheduler and exiting. ops.enable() runs again whenever @p comes back.

scx_bpf_task_set_data() follows the rules of scx_bpf_task_set_dsq_vtime(). It accepts any caller and refuses a task that is not enabled on the calling scheduler, except in ops.enable(), where @p is still SCX_TASK_READY. A write can race @p leaving and outlive the clear, and synchronizing such writes is left to the scheduler, as for dsq_vtime.

The value means something only to the scheduler that set it. With sub-schedulers, a task a scheduler reaches as a waker or from a tracing program may belong to another one. A scheduler can tag the value with its scx_bpf_sched_id() to recognize its own.

---
 include/linux/sched/ext.h                | 12 ++++++
 kernel/sched/ext/ext.c                   | 54 ++++++++++++++++++++++--
 tools/sched_ext/include/scx/compat.bpf.h | 24 +++++++++++
 3 files changed, 86 insertions(+), 4 deletions(-)
include/linux/sched/ext.h +1 -0
index f3564581c317..2c2ce144601d 100644
@@ -277,6 +277,18 @@ struct sched_ext_entity {
 	 */
 	atomic64_t		slice_oob;
 
+	/*

include/linux/sched/ext.h struct sched_ext_entity { · line 290

Quoted 10 lines
include/linux/sched/ext.h +10 -0
+	 * 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_data() while @p is enabled on the
+	 * scheduler, from ops.enable() on, and cleared when @p leaves the
+	 * scheduler's control, after ops.disable(). Any BPF program can read
+	 * it, so a tracing program can reach the context of the current task
+	 * with a single load. A write from outside @p's own ops can outlive
+	 * the clear, see scx_bpf_task_set_data().
+	 */
+	u64			bpf_data;

Should we rename this p->scx.bpf_priv, with scx_bpf_task_set_priv() and scx_bpf_task_priv(), to make the scheduler-private ownership clearer?

Quoted 67 lines
include/linux/sched/ext.h +1 -0
+
 	/*
 	 * Sub-sched cap rejected reenq context, valid only while
 	 * %SCX_TASK_REENQ_CAP is set. @reenq_reason_caps is the SCX_CAP_* bits
kernel/sched/ext/ext.c +38 -4
index cdceeffbcc65..bca27ced9d8d 100644
@@ -4749,16 +4749,17 @@ void scx_enable_task(struct scx_sched *sch, struct task_struct *p)
  * @rq: @p's rq, locked
  * @p: task leaving its sched's control
  *
- * The vtime, the slice and what rides on it, the reenqueue count and the
- * watchdog wait belong to the sched while it controls @p. The control ends when
- * @p is taken off the sched or leaves the ext class while staying on the sched.
- * Reset them so that @p starts clean wherever it goes.
+ * The vtime, the slice and what rides on it, the reenqueue count, the BPF data
+ * and the watchdog wait belong to the sched while it controls @p. The control
+ * ends when @p is taken off the sched or leaves the ext class while staying on
+ * the sched. Reset them so that @p starts clean wherever it goes.
  */
 static void scx_reset_task_fields(struct rq *rq, struct task_struct *p)
 {
 	lockdep_assert_rq_held(rq);
 
 	p->scx.dsq_vtime = 0;
+	p->scx.bpf_data = 0;
 	scx_task_slice_ended(rq, p);
 	scx_set_task_slice(p, 0);
 	p->scx.reenq_cnt = 0;
@@ -10886,6 +10887,50 @@ __bpf_kfunc bool scx_bpf_task_set_lazy_resched(struct task_struct *p, bool lazy,
 	return true;
 }
 
+/**
+ * scx_bpf_task_set_data - Set the BPF data of a task
+ * @p: task of interest
+ * @data: opaque value to store in @p->scx.bpf_data
+ * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
+ *
+ * Store @data in @p->scx.bpf_data, where any BPF program can read it with a
+ * plain load. The value is valid while @p is enabled on the calling scheduler.
+ * The kernel clears it when @p leaves the scheduler's control, after
+ * ops.disable(), and ops.enable() runs again when @p comes back.
+ *
+ * From @p's own ops, ops.enable() included, @p can't leave the scheduler
+ * concurrently. Elsewhere, e.g. from a timer or a tracing program, the write
+ * can race @p leaving and outlive the clear, as with
+ * scx_bpf_task_set_dsq_vtime(). Synchronizing such writes is the BPF
+ * scheduler's responsibility.
+ *
+ * Return %true if @data was stored, %false if @p is not on the calling
+ * scheduler or is neither enabled on it nor being enabled by ops.enable().
+ */
+__bpf_kfunc bool scx_bpf_task_set_data(struct task_struct *p, u64 data,
+				       const struct bpf_prog_aux *aux)
+{
+	struct scx_sched *sch;
+	u32 state;
+
+	guard(rcu)();
+	sch = scx_prog_sched(aux);
+	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
+		return false;
+
+	/*
+	 * ops.enable() runs while @p is still %SCX_TASK_READY but already on the

kernel/sched/ext/ext.c __bpf_kfunc bool scx_bpf_task_set_lazy_resched(struct task_struct *p, bool lazy, · line 10932

Quoted 10 lines
kernel/sched/ext/ext.c +10 -0
+	 * ext class. A %SCX_TASK_READY @p on another class is not enabled.
+	 */
+	state = scx_get_task_state(p);
+	if (state != SCX_TASK_ENABLED &&
+	    (state != SCX_TASK_READY || p->sched_class != &ext_sched_class))
+		return false;
+
+	p->scx.bpf_data = data;
+	return true;
+}

An ops.exit_task() callback can use this kfunc to repopulate bpf_data after the kernel has cleared it. During sub-scheduler handoff, the task is still READY/ext and associated with the outgoing scheduler, so this check accepts the write. The incoming scheduler's ops.enable() then receives the outgoing scheduler's value instead of zero. I reproduced this without any concurrent writer.

Can we move the ENABLED transition into __scx_enable_task(), immediately before the enable callback and fold away the wrapper? ops.enable() can't fail, so this would let the check here become simply:

	if (scx_get_task_state(p) != SCX_TASK_ENABLED)
		return false;

I reproduced this inside virtme-ng and verified that this change fixes it. Thoughts?

Thanks,
-Andrea

 kernel/sched/ext/ext.c | 24 +++++++-----------------
 1 file changed, 7 insertions(+), 17 deletions(-)
kernel/sched/ext/ext.c +7 -17
index bca27ced9d8da..7ed1319c12dcf 100644
@@ -4686,7 +4686,7 @@ int __scx_init_task(struct scx_sched *sch, struct task_struct *p,
 	return 0;
 }
 
-static void __scx_enable_task(struct scx_sched *sch, struct task_struct *p)
+void scx_enable_task(struct scx_sched *sch, struct task_struct *p)
 {
 	struct rq *rq = task_rq(p);
 	u32 weight;
@@ -4712,6 +4712,9 @@ static void __scx_enable_task(struct scx_sched *sch, struct task_struct *p)
 	p->scx.weight = sched_weight_to_cgroup(weight);
 	p->scx.lazy_resched = sch->ops.flags & SCX_OPS_LAZY_RESCHED;
 
+	/* Task kfuncs must recognize @p as enabled from ops.enable() on. */
+	scx_set_task_state(p, SCX_TASK_ENABLED);
+
 	if (SCX_HAS_OP(sch, enable)) {
 		if (scx_is_cid_type()) {
 			struct scx_cmask *cmask = scx_fill_cmask_scratch(sch, p->cpus_ptr);
@@ -4738,12 +4741,6 @@ static void __scx_enable_task(struct scx_sched *sch, struct task_struct *p)
 		SCX_CALL_OP_TASK(sch, set_weight, rq, p, p->scx.weight);
 }
 
-void scx_enable_task(struct scx_sched *sch, struct task_struct *p)
-{
-	__scx_enable_task(sch, p);
-	scx_set_task_state(p, SCX_TASK_ENABLED);
-}
-
 /**
  * scx_reset_task_fields - Reset what @p carries from its sched's control
  * @rq: @p's rq, locked
@@ -10904,27 +10901,20 @@ __bpf_kfunc bool scx_bpf_task_set_lazy_resched(struct task_struct *p, bool lazy,
  * scx_bpf_task_set_dsq_vtime(). Synchronizing such writes is the BPF
  * scheduler's responsibility.
  *
- * Return %true if @data was stored, %false if @p is not on the calling
- * scheduler or is neither enabled on it nor being enabled by ops.enable().
+ * Return %true if @data was stored, %false if @p is not enabled on the calling
+ * scheduler.
  */
 __bpf_kfunc bool scx_bpf_task_set_data(struct task_struct *p, u64 data,
 				       const struct bpf_prog_aux *aux)
 {
 	struct scx_sched *sch;
-	u32 state;
 
 	guard(rcu)();
 	sch = scx_prog_sched(aux);
 	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
 		return false;
 
-	/*
-	 * ops.enable() runs while @p is still %SCX_TASK_READY but already on the
-	 * ext class. A %SCX_TASK_READY @p on another class is not enabled.
-	 */
-	state = scx_get_task_state(p);
-	if (state != SCX_TASK_ENABLED &&
-	    (state != SCX_TASK_READY || p->sched_class != &ext_sched_class))
+	if (scx_get_task_state(p) != SCX_TASK_ENABLED)
 		return false;
 
 	p->scx.bpf_data = data;
author reviewer
#5 lore raw

Thanks Andrea for the review!

Quoted 48 lines · Andrea Righi

Hi Changwoo,

thanks for working at this! Then I can finally remove the ugly p->scx.dsq_vtime hack. :)

Comments below.

Quoted 40 lines · Changwoo Min

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

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

The value is valid while @p is enabled on the scheduler that set it. scx_reset_task_fields() clears it after ops.disable(), which covers @p leaving the ext class, moving to another sub-scheduler and exiting. ops.enable() runs again whenever @p comes back.

scx_bpf_task_set_data() follows the rules of scx_bpf_task_set_dsq_vtime(). It accepts any caller and refuses a task that is not enabled on the calling scheduler, except in ops.enable(), where @p is still SCX_TASK_READY. A write can race @p leaving and outlive the clear, and synchronizing such writes is left to the scheduler, as for dsq_vtime.

The value means something only to the scheduler that set it. With sub-schedulers, a task a scheduler reaches as a waker or from a tracing program may belong to another one. A scheduler can tag the value with its scx_bpf_sched_id() to recognize its own.

---
  include/linux/sched/ext.h                | 12 ++++++
  kernel/sched/ext/ext.c                   | 54 ++++++++++++++++++++++--
  tools/sched_ext/include/scx/compat.bpf.h | 24 +++++++++++
  3 files changed, 86 insertions(+), 4 deletions(-)
include/linux/sched/ext.h +0 -0
index f3564581c317..2c2ce144601d 100644
@@ -277,6 +277,18 @@ struct sched_ext_entity {
  	 */
  	atomic64_t		slice_oob;
 
Quoted 14 lines

include/linux/sched/ext.h struct sched_ext_entity { · line 290

Quoted 11 lines
include/linux/sched/ext.h +11 -0
+	/*
+	 * 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_data() while @p is enabled on the
+	 * scheduler, from ops.enable() on, and cleared when @p leaves the
+	 * scheduler's control, after ops.disable(). Any BPF program can read
+	 * it, so a tracing program can reach the context of the current task
+	 * with a single load. A write from outside @p's own ops can outlive
+	 * the clear, see scx_bpf_task_set_data().
+	 */
+	u64			bpf_data;

Should we rename this p->scx.bpf_priv, with scx_bpf_task_set_priv() and scx_bpf_task_priv(), to make the scheduler-private ownership clearer?

bpf_priv more clearly expresses the intent. I will rename it bpf_priv, scx_bpf_task_set_priv() and scx_bpf_task_priv() as you suggested.

Quoted 77 lines
Quoted 77 lines
include/linux/sched/ext.h +1 -0
+
  	/*
  	 * Sub-sched cap rejected reenq context, valid only while
  	 * %SCX_TASK_REENQ_CAP is set. @reenq_reason_caps is the SCX_CAP_* bits
kernel/sched/ext/ext.c +47 -4
index cdceeffbcc65..bca27ced9d8d 100644
@@ -4749,16 +4749,17 @@ void scx_enable_task(struct scx_sched *sch, struct task_struct *p)
   * @rq: @p's rq, locked
   * @p: task leaving its sched's control
   *
- * The vtime, the slice and what rides on it, the reenqueue count and the
- * watchdog wait belong to the sched while it controls @p. The control ends when
- * @p is taken off the sched or leaves the ext class while staying on the sched.
- * Reset them so that @p starts clean wherever it goes.
+ * The vtime, the slice and what rides on it, the reenqueue count, the BPF data
+ * and the watchdog wait belong to the sched while it controls @p. The control
+ * ends when @p is taken off the sched or leaves the ext class while staying on
+ * the sched. Reset them so that @p starts clean wherever it goes.
   */
  static void scx_reset_task_fields(struct rq *rq, struct task_struct *p)
  {
  	lockdep_assert_rq_held(rq);
 
  	p->scx.dsq_vtime = 0;
+	p->scx.bpf_data = 0;
  	scx_task_slice_ended(rq, p);
  	scx_set_task_slice(p, 0);
  	p->scx.reenq_cnt = 0;
@@ -10886,6 +10887,50 @@ __bpf_kfunc bool scx_bpf_task_set_lazy_resched(struct task_struct *p, bool lazy,
  	return true;
  }
 
+/**
+ * scx_bpf_task_set_data - Set the BPF data of a task
+ * @p: task of interest
+ * @data: opaque value to store in @p->scx.bpf_data
+ * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
+ *
+ * Store @data in @p->scx.bpf_data, where any BPF program can read it with a
+ * plain load. The value is valid while @p is enabled on the calling scheduler.
+ * The kernel clears it when @p leaves the scheduler's control, after
+ * ops.disable(), and ops.enable() runs again when @p comes back.
+ *
+ * From @p's own ops, ops.enable() included, @p can't leave the scheduler
+ * concurrently. Elsewhere, e.g. from a timer or a tracing program, the write
+ * can race @p leaving and outlive the clear, as with
+ * scx_bpf_task_set_dsq_vtime(). Synchronizing such writes is the BPF
+ * scheduler's responsibility.
+ *
+ * Return %true if @data was stored, %false if @p is not on the calling
+ * scheduler or is neither enabled on it nor being enabled by ops.enable().
+ */
+__bpf_kfunc bool scx_bpf_task_set_data(struct task_struct *p, u64 data,
+				       const struct bpf_prog_aux *aux)
+{
+	struct scx_sched *sch;
+	u32 state;
+
+	guard(rcu)();
+	sch = scx_prog_sched(aux);
+	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
+		return false;
+
+	/*
+	 * ops.enable() runs while @p is still %SCX_TASK_READY but already on the
+	 * ext class. A %SCX_TASK_READY @p on another class is not enabled.
+	 */
+	state = scx_get_task_state(p);
+	if (state != SCX_TASK_ENABLED &&
+	    (state != SCX_TASK_READY || p->sched_class != &ext_sched_class))
+		return false;
+
+	p->scx.bpf_data = data;
+	return true;
Quoted 8 lines

kernel/sched/ext/ext.c __bpf_kfunc bool scx_bpf_task_set_lazy_resched(struct task_struct *p, bool lazy, · line 10932

Quoted 1 line
kernel/sched/ext/ext.c +1 -0
+}

An ops.exit_task() callback can use this kfunc to repopulate bpf_data after the kernel has cleared it. During sub-scheduler handoff, the task is still READY/ext and associated with the outgoing scheduler, so this check accepts the write. The incoming scheduler's ops.enable() then receives the outgoing scheduler's value instead of zero. I reproduced this without any concurrent writer.

You are right. I didn't consider this path. I think we should call scx_reset_task_fields() *after* ops.exit_task() to prevent leaking bpf_priv (and dsq_vtime and slice) to the other scx scheduler.

Quoted 10 lines

Can we move the ENABLED transition into __scx_enable_task(), immediately before the enable callback and fold away the wrapper? ops.enable() can't fail, so this would let the check here become simply:

	if (scx_get_task_state(p) != SCX_TASK_ENABLED)
		return false;

I reproduced this inside virtme-ng and verified that this change fixes it. Thoughts?

I agree. This is cleaner. I will change it as you suggested.

Thanks!
Changwoo Min

author reviewer
#6 lore raw

PATCH 4/5 sched_ext: scx_qmap: Cache task_ctx in p->scx.bpf_data

In reply to Changwoo Min

Show how a scheduler uses p->scx.bpf_data. 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.

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.

---
 tools/sched_ext/scx_qmap.bpf.c | 58 ++++++++++++++++++++++++++++++++++
 1 file changed, 58 insertions(+)
tools/sched_ext/scx_qmap.bpf.c +58 -0
index 3951f1f6e3c6..079082711f69 100644
@@ -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_data.
  *
  * 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,47 @@ 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_data 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_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_data
+ *     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_data, 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. The kernel clears the value when @p leaves this sched.
+ */
+#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 data = READ_ONCE(p->scx.bpf_data);
 
 	QMAP_TOUCH_ARENA();
 
+	if (key && (u32)(data >> 32) == (u32)key)
+		return (task_ctx_t *)((key & ~0xffffffffULL) | (u32)data);
+
 	v = bpf_task_storage_get(&task_ctx_stor, p, 0, 0);
 	if (!v || !v->taskc)
 		return NULL;
@@ -1062,6 +1098,27 @@ 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_data(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)
 {
@@ -2252,6 +2309,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,
Signature · 1 line
2.56.1
author reviewer
#7 lore raw

PATCH 5/5 selftests/sched_ext: Test p->scx.bpf_data across class changes

In reply to Changwoo Min

Under a partial-switch scheduler that sets p->scx.bpf_data from ops.enable(), move the test task through SCHED_EXT, SCHED_FIFO and SCHED_EXT again, then unload the scheduler. After each step, a syscall program reads the value and sets it again without the rq lock. The value must be set while the task is on SCHED_EXT. Otherwise it must be cleared, and the write must fail.

The task also forks while on SCHED_EXT. ops.enable() must find the value cleared for every task it enables, the child included.

---
 tools/testing/selftests/sched_ext/Makefile    |   1 +
 .../selftests/sched_ext/task_bpf_data.bpf.c   |  64 +++++++++
 .../selftests/sched_ext/task_bpf_data.c       | 123 ++++++++++++++++++
 3 files changed, 188 insertions(+)
 create mode 100644 tools/testing/selftests/sched_ext/task_bpf_data.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/task_bpf_data.c
tools/testing/selftests/sched_ext/Makefile +1 -0
index ef59c463cd33..c0a3046a36ab 100644
@@ -201,6 +201,7 @@ auto-test-targets :=			\
 	sched_id			\
 	sub_caps_kfunc			\
 	sub_core_caps			\
+	task_bpf_data			\
 	test_example			\
 	total_bw			\
 	unlocked_kfunc			\
tools/testing/selftests/sched_ext/task_bpf_data.bpf.c new file +64 -0

64 lines not on this page · raw message

tools/testing/selftests/sched_ext/task_bpf_data.c new file +123 -0

123 lines not on this page · raw message

Signature · 1 line
2.56.1