Skip to contentSkip to conversation

sched_ext: Make ops.cpu_acquire/release() reliable

RFC PATCH In review Kuba Piecuch 3 participants 12 messages Oct 18 – Oct 20

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

cover sched_ext: Make ops.cpu_acquire/release() reliable

Hello,

ops.cpu_acquire() and ops.cpu_release() are meant to tell the BPF scheduler when a CPU becomes available to it and when it's taken away. As they are now, they can't be used to reliably track that:

- An RT task waking up on an idle CPU doesn't trigger ops.cpu_release(). The release is only emitted from put_prev_task_scx(), i.e. when an SCX task is switched out.

- A running SCX task moving to a higher class through sched_setscheduler() or a PI boost doesn't trigger it either, as no context switch takes place.

- ops.cpu_acquire() is emitted speculatively from dispatch_one(). If a higher class task wins the pick afterwards (dispatch dropped the rq lock, RETRY_TASK, core-sched picking for a sibling), the CPU stays acquired while an RT task runs on it.

- rq->scx.cpu_released carries over from one scheduler to the next and CPU hotplug isn't handled.

Commit a3f5d4822253 ("sched_ext: Allow scx_bpf_reenqueue_local() to be called from anywhere") deprecated the callbacks, as closing these gaps was thought to require a hook invoked regardless of sched class. This series shows that it doesn't.

Whether a CPU is available to the BPF scheduler only depends on the class of rq->donor: the CPU is available while an SCX task or the idle task runs on it and released while a stop, DL, RT or fair (partial mode) task does. Every change of availability has an SCX task or the idle task on one side of the switch, so the ext and idle classes' own put_prev_task() and set_next_task() see all of them. Switches between higher class tasks never change availability. The one remaining case, a running task leaving SCX without a context switch, is caught by switched_from_scx().

kernel/sched/core.c is left untouched. The idle class gets two calls next to its existing scx_update_idle() calls and sched.h gets one new scx_rq flag.

Points worth discussing:

- Core-sched forced idle counts as available. Whether a task can be placed on a forced idle CPU depends on that task's cookie, which is for the BPF scheduler to judge.

- ops.cpu_acquire() moves from before ops.dispatch() to the point where the CPU actually switches to an SCX task or idle, so ops.dispatch() may now run on a released CPU. A speculative acquire before dispatch can't be made reliable without hooks in every class.

- The callbacks may be invoked for a remote CPU, with that CPU's rq
locked: sched_setscheduler() or a PI boost of a task running on another CPU, and scheduler enable. Patch 1 makes the legacy scx_bpf_reenqueue_local() re-enqueue the locked rq's local DSQ instead of assuming smp_processor_id().

- Every CPU starts out released, and each available online CPU is acquired when the scheduler is enabled. The callbacks are only invoked between ops.cpu_online() and ops.cpu_offline(). Because rq_online_scx() runs before ops.cpu_online() when a CPU comes up, this uses a new SCX_RQ_OPS_ONLINE flag rather than SCX_RQ_ONLINE.

- Schedulers which don't implement the callbacks only pay for a static branch.

- The callbacks stay cpu-form only, which makes them root-only by construction. cid-form variants and fan-out to sub-schedulers (gated on SCX_CAP_BASE, like ops.update_idle()) could follow if there's interest.

Patch 1 makes the legacy scx_bpf_reenqueue_local() target the locked rq. Patch 2 emits the callbacks on actual transitions and handles scheduler enable/disable and CPU hotplug. Patch 3 releases the CPU when its running task leaves SCX. Patch 4 un-deprecates the callbacks and documents the contract. Patch 5 adds selftests.

Testing was done in virtme-ng with PROVE_LOCKING, DEBUG_ATOMIC_SLEEP, SCHED_CORE and EXT_SUB_SCHED enabled. The full sched_ext selftest suite passes without splats. The new cpu_avail test checks the reported state on every context switch through a sched_switch tracepoint and covers idle -> RT, remote class changes, the legacy re-enqueue from a remote release, PI boosting, hotplug, scheduler reloads and partial mode. It fails on the base kernel (idle -> RT) and with only patches 1-2 applied (remote class change). cpu_avail_core, run in an SMT VM, checks that core-sched forced idle doesn't release a CPU while an RT task with a matching cookie does.

Not included:

- tools/sched_ext/include/scx/*autogen* isn't regenerated for the new SCX_CPU_PREEMPT_FAIR and SCX_CPU_PREEMPT_CLASS_CHANGE values. I'll add that as a separate patch in a non-RFC posting.

- Unrelated to this series: the comment on SCX_RQ_ONLINE in sched.h says it tracks the ops.cpu_online()/cpu_offline() state, but as noted above rq_online_scx() runs before ops.cpu_online() on hotplug. I can send a separate fix if that's useful.

Kuba Piecuch (5):
sched_ext: Make legacy scx_bpf_reenqueue_local() target the locked rq
sched_ext: Emit ops.cpu_acquire/release() on actual CPU transitions
sched_ext: Release the CPU when its running task leaves SCX
sched_ext: Un-deprecate ops.cpu_acquire/release() selftests/sched_ext: Add cpu_avail tests

 kernel/sched/ext/ext.c                        | 265 +++++--
 kernel/sched/ext/ext.h                        |  19 +
 kernel/sched/ext/internal.h                   |  69 +-
 kernel/sched/idle.c                           |   4 +
 kernel/sched/sched.h                          |   6 +
 tools/testing/selftests/sched_ext/Makefile    |   2 +
 .../selftests/sched_ext/cpu_avail.bpf.c       | 218 ++++++
 tools/testing/selftests/sched_ext/cpu_avail.c | 717 ++++++++++++++++++
 tools/testing/selftests/sched_ext/cpu_avail.h | 237 ++++++
 .../selftests/sched_ext/cpu_avail_core.c      | 256 +++++++
 .../testing/selftests/sched_ext/maximal.bpf.c |  10 +
 11 files changed, 1706 insertions(+), 97 deletions(-)
 create mode 100644 tools/testing/selftests/sched_ext/cpu_avail.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/cpu_avail.c
 create mode 100644 tools/testing/selftests/sched_ext/cpu_avail.h
 create mode 100644 tools/testing/selftests/sched_ext/cpu_avail_core.c

base-commit: 2f2f7eeef8b0a1a9b9ca998231419873ccae8d4e

Signature · 1 line
2.56.0.176.g3575e65682-goog
#1 lore raw

RFC PATCH 1/5 sched_ext: Make legacy scx_bpf_reenqueue_local() target the locked rq

The legacy, synchronous scx_bpf_reenqueue_local() can only be called from ops.cpu_release(). It assumes that ops.cpu_release() always runs on the CPU being released and re-enqueues the tasks on the local DSQ of smp_processor_id().

That assumption is about to stop holding. A following patch emits ops.cpu_release() when the task running on a CPU leaves SCX through sched_setscheduler() or a PI boost. That can happen from any CPU, with the target CPU's rq locked. Picking the rq from smp_processor_id() would then trip lockdep_assert_rq_held() and walk another CPU's local DSQ without holding that CPU's rq lock.

SCX_CALL_OP() already records the rq the operation is invoked for in scx_locked_rq(), and scx_bpf_dsq_reenq() / scx_bpf_reenqueue_local___v2() already resolve SCX_DSQ_LOCAL against it. Do the same in the legacy kfunc. Nothing else in reenq_local() depends on running on the target CPU: the local DSQ is protected by the rq lock, and direct dispatches to a third CPU's local DSQ are already deferred through ddsp_deferred_locals.

No functional change for the existing callers, which all run on the CPU whose rq is locked.

Also update the kerneldoc of scx_bpf_reenqueue_local___v2(), which still says that it works on the local DSQ of the caller's CPU, to match scx_bpf_dsq_reenq().

---
 kernel/sched/ext/ext.c | 19 ++++++++++++++-----
 1 file changed, 14 insertions(+), 5 deletions(-)
kernel/sched/ext/ext.c +14 -5
index f1b9d52f624a..f64438290218 100644
@@ -9501,9 +9501,10 @@ __bpf_kfunc_start_defs();
  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
  *
- * Iterate over all of the tasks currently enqueued on the local DSQ of the
- * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
- * processed tasks. Can only be called from ops.cpu_release().
+ * Iterate over all of the tasks currently enqueued on the local DSQ of the CPU
+ * ops.cpu_release() is being invoked for, and re-enqueue them in the BPF
+ * scheduler. Returns the number of processed tasks. Can only be called from
+ * ops.cpu_release().
  */
 __bpf_kfunc u32 scx_bpf_reenqueue_local(const struct bpf_prog_aux *aux)
 {
@@ -9515,7 +9516,13 @@ __bpf_kfunc u32 scx_bpf_reenqueue_local(const struct bpf_prog_aux *aux)
 	if (unlikely(!sch))
 		return 0;
 
-	rq = cpu_rq(smp_processor_id());
+	/*
+	 * Use the rq ops.cpu_release() was invoked for rather than the local
+	 * one. They are not necessarily the same CPU.
+	 */
+	rq = scx_locked_rq();
+	if (WARN_ON_ONCE(!rq))
+		return 0;
 	lockdep_assert_rq_held(rq);
 
 	return reenq_local(sch, rq, SCX_REENQ_ANY);
@@ -10057,7 +10064,9 @@ __bpf_kfunc void scx_bpf_dsq_reenq(u64 dsq_id, u64 reenq_flags,
  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
  *
  * Iterate over all of the tasks currently enqueued on the local DSQ of the
- * caller's CPU, and re-enqueue them in the BPF scheduler. Can be called from
+ * rq the current scheduler operation is locked to - e.g. the CPU
+ * ops.cpu_release() is being invoked for - or the calling CPU's when no rq is
+ * locked, and re-enqueue them in the BPF scheduler. Can be called from
  * anywhere.
  *
  * This is now a special case of scx_bpf_dsq_reenq() and may be removed in the
Signature · 1 line
2.56.0.176.g3575e65682-goog
#2 lore raw

RFC PATCH 2/5 sched_ext: Emit ops.cpu_acquire/release() on actual CPU transitions

In reply to Kuba Piecuch

ops.cpu_acquire() and ops.cpu_release() are meant to tell the BPF scheduler when a CPU becomes available to it and when it's taken away. In their current form they miss events and can get stuck in the wrong state:

- ops.cpu_release() is only emitted from put_prev_task_scx(), so a CPU going from idle straight to an RT, DL or stop task is never released. This also covers the case where ttwu() direct-dispatched a task to an idle CPU's local DSQ but a higher class task wins the next pick:
nothing on the SCX side runs at all.

- ops.cpu_acquire() is emitted speculatively from dispatch_one(), before the pick is final. If dispatch drops the rq lock and a higher class task shows up, or the pick is retried, the CPU stays "acquired" while an RT task runs. Under core scheduling, dispatch_one() also runs for the siblings, so a CPU can be acquired even though its final pick is an RT task.

- rq->scx.cpu_released is never reset. It carries over from one scheduler to the next, and CPU hotplug isn't handled.

Whether a CPU is available to the BPF scheduler only depends on the class of its scheduling context, rq->donor: the CPU is available while an SCX task or the idle task runs on it and released while a stop, DL, RT or fair (partial mode) task does. Every change of availability has an SCX task or the idle task on one side, so the ext and idle classes' own put_prev_task() and set_next_task() see all of them. No hook in the core or in the other classes is needed.

Replace switch_class() and the acquire in dispatch_one() with a small, idempotent state machine, __scx_update_cpu_avail(), which looks at the task about to become rq->donor and only invokes a callback on an actual edge. Call it from:

- set_next_task_scx(), before ops.running(): acquire.
- put_prev_task_scx(), after the outgoing task went back to the local DSQ, so that ops.cpu_release() can still re-enqueue it: release if the next task is from a higher class.
- put_prev_task_idle(), after ops.update_idle(cpu, false): release if the next task is from a higher class.
- set_next_task_idle(), before ops.update_idle(cpu, true): acquire.

Core-sched forced idle counts as available. Whether the BPF scheduler can place a task on a forced idle CPU depends on that task's cookie, which is for the BPF scheduler to decide. Idle-to-idle re-picks don't change availability and pick_task_idle() is left alone.

Every CPU starts released. When a root scheduler implementing either callback is enabled, reset all CPUs to released, turn on the static key gating the hooks and acquire every available online CPU. The key is turned off under scx_enable_mutex when the scheduler is disabled, before tasks are switched out of SCX, so the BPF scheduler doesn't see a storm of releases. In-flight callbacks run with an rq lock held and IRQs disabled and are flushed by the synchronize_rcu() before ops.exit(). Schedulers which don't implement the callbacks only pay for a static branch.

For hotplug, the callbacks are only invoked between ops.cpu_online() and ops.cpu_offline(): ops.cpu_offline() implies a release and the CPU is acquired right after ops.cpu_online() if it's available. This can't be keyed off SCX_RQ_ONLINE as rq_online_scx() runs before ops.cpu_online() when a CPU comes up: cpuset_cpu_active() rebuilds the sched domains before sched_cpu_activate() calls scx_rq_activate(). Add SCX_RQ_OPS_ONLINE, which scx_rq_activate() sets right after ops.cpu_online() and scx_rq_deactivate() clears right before ops.cpu_offline().

Add SCX_CPU_PREEMPT_FAIR for releases to a fair task in partial mode, which used to be reported as SCX_CPU_PREEMPT_UNKNOWN. It's appended to keep the existing values unchanged.

This changes when ops.cpu_acquire() is called: it's now called when the CPU actually switches to an SCX task or idle rather than before ops.dispatch(). ops.dispatch() may thus be called while the CPU is still released.

A running SCX task changing class without a context switch is not handled yet and is addressed by the next patch.

---
 kernel/sched/ext/ext.c      | 220 +++++++++++++++++++++++++-----------
 kernel/sched/ext/ext.h      |  19 ++++
 kernel/sched/ext/internal.h |   2 +
 kernel/sched/idle.c         |   4 +
 kernel/sched/sched.h        |   6 +
 5 files changed, 185 insertions(+), 66 deletions(-)
kernel/sched/ext/ext.c +154 -66
index f64438290218..4d02d2d6e6d0 100644
@@ -80,6 +80,9 @@ static bool scx_switching_all;
 DEFINE_STATIC_KEY_FALSE(__scx_switched_all);
 static DEFINE_STATIC_KEY_FALSE(__scx_tid_to_task_enabled);
 
+/* the root scheduler implements ops.cpu_acquire() or ops.cpu_release() */
+DEFINE_STATIC_KEY_FALSE(__scx_cpu_avail_enabled);
+
 /*
  * Gates cgroup ops delivery. Set at the end of the cgroup init phase of root
  * enable and cleared before root disable starts tearing down tasks, both under
@@ -2964,19 +2967,6 @@ static enum scx_dsp_verdict dispatch_one(struct rq *rq, struct task_struct *prev
 
 	scx_process_sync_ecaps(rq, prev);
 
-	if ((root_sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) &&
-	    unlikely(rq->scx.cpu_released)) {
-		/*
-		 * If the previous sched_class for the current CPU was not SCX,
-		 * notify the BPF scheduler that it again has control of the
-		 * core. This callback complements ->cpu_release(), which is
-		 * emitted in switch_class().
-		 */
-		if (root_sch->ops.cpu_acquire)
-			SCX_CALL_OP(root_sch, cpu_acquire, rq, cpu, NULL);
-		rq->scx.cpu_released = false;
-	}
-
 	if (prev->sched_class == &ext_sched_class) {
 		update_curr_scx(rq);
 
@@ -3044,10 +3034,101 @@ static enum scx_dsp_verdict dispatch_one(struct rq *rq, struct task_struct *prev
 	return verdict;
 }
 
+/*
+ * A CPU is available to the BPF scheduler while its scheduling context is an
+ * SCX task or the idle task. Core-sched forced idle counts as available:
+ * whether a task can be placed on such a CPU depends on that task's cookie,
+ * which is the BPF scheduler's call.
+ */
+static bool scx_cpu_avail(struct rq *rq, struct task_struct *next)
+{
+	return next->sched_class == &ext_sched_class || next == rq->idle;
+}
+
+static enum scx_cpu_preempt_reason cpu_release_reason(struct task_struct *next)
+{
+	if (next->sched_class == &stop_sched_class)
+		return SCX_CPU_PREEMPT_STOP;
+	if (next->sched_class == &dl_sched_class)
+		return SCX_CPU_PREEMPT_DL;
+	if (next->sched_class == &rt_sched_class)
+		return SCX_CPU_PREEMPT_RT;
+	if (next->sched_class == &fair_sched_class)
+		return SCX_CPU_PREEMPT_FAIR;
+	return SCX_CPU_PREEMPT_UNKNOWN;
+}
+
+/*
+ * ops.cpu_acquire/release() are edge-triggered on @rq->scx.cpu_released and
+ * only fire between ops.cpu_online() and ops.cpu_offline(), see
+ * scx_rq_activate() and scx_rq_deactivate().
+ */
+static void scx_cpu_release(struct rq *rq, enum scx_cpu_preempt_reason reason,
+			    struct task_struct *task)
+{
+	struct scx_sched *sch = scx_root_protected_live();
+
+	lockdep_assert_rq_held(rq);
+
+	if (rq->scx.cpu_released || !(rq->scx.flags & SCX_RQ_OPS_ONLINE))
+		return;
+
+	/* update before calling out so that a nested re-evaluation is a no-op */
+	rq->scx.cpu_released = true;
+
+	if (sch->ops.cpu_release) {
+		struct scx_cpu_release_args args = {
+			.reason = reason,
+			.task = task,
+		};
+
+		SCX_CALL_OP(sch, cpu_release, rq, cpu_of(rq), &args);
+	}
+}
+
+static void scx_cpu_acquire(struct rq *rq)
+{
+	struct scx_sched *sch = scx_root_protected_live();
+
+	lockdep_assert_rq_held(rq);
+
+	if (!rq->scx.cpu_released || !(rq->scx.flags & SCX_RQ_OPS_ONLINE))
+		return;
+
+	rq->scx.cpu_released = false;
+
+	if (sch->ops.cpu_acquire)
+		SCX_CALL_OP(sch, cpu_acquire, rq, cpu_of(rq), NULL);
+}
+
+/**
+ * __scx_update_cpu_avail - Re-evaluate whether a CPU is available
+ * @rq: rq of the CPU, locked
+ * @next: task that is (about to become) @rq->donor
+ *
+ * Availability only depends on the class of @rq->donor and every change has
+ * an SCX task or the idle task on one side. Callers re-evaluate whenever that
+ * may have happened and a callback is only invoked on an actual transition.
+ */
+void __scx_update_cpu_avail(struct rq *rq, struct task_struct *next)
+{
+	if (scx_cpu_avail(rq, next))
+		scx_cpu_acquire(rq);
+	else
+		scx_cpu_release(rq, cpu_release_reason(next), next);
+}
+
 static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first)
 {
 	struct scx_sched *sch = scx_task_sched(p);
 
+	/*
+	 * Acquire before ops.dequeue(SCX_DEQ_CORE_SCHED_EXEC) and
+	 * ops.running(). This also covers a running task switching to SCX
+	 * through sched_change_end().
+	 */
+	scx_update_cpu_avail(rq, p);
+
 	if (p->scx.flags & SCX_TASK_QUEUED) {
 		/*
 		 * Core-sched might decide to execute @p before it is
@@ -3105,57 +3186,6 @@ static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first)
 	}
 }
 
-static enum scx_cpu_preempt_reason
-preempt_reason_from_class(const struct sched_class *class)
-{
-	if (class == &stop_sched_class)
-		return SCX_CPU_PREEMPT_STOP;
-	if (class == &dl_sched_class)
-		return SCX_CPU_PREEMPT_DL;
-	if (class == &rt_sched_class)
-		return SCX_CPU_PREEMPT_RT;
-	return SCX_CPU_PREEMPT_UNKNOWN;
-}
-
-static void switch_class(struct rq *rq, struct task_struct *next)
-{
-	struct scx_sched *sch = scx_root_protected_live();
-	const struct sched_class *next_class = next->sched_class;
-
-	if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT))
-		return;
-
-	/*
-	 * The callback is conceptually meant to convey that the CPU is no
-	 * longer under the control of SCX. Therefore, don't invoke the callback
-	 * if the next class is below SCX (in which case the BPF scheduler has
-	 * actively decided not to schedule any tasks on the CPU).
-	 */
-	if (sched_class_above(&ext_sched_class, next_class))
-		return;
-
-	/*
-	 * At this point we know that SCX was preempted by a higher priority
-	 * sched_class, so invoke the ->cpu_release() callback if we have not
-	 * done so already. We only send the callback once between SCX being
-	 * preempted, and it regaining control of the CPU.
-	 *
-	 * ->cpu_release() complements ->cpu_acquire(), which is emitted the
-	 *  next time that dispatch_one() is invoked.
-	 */
-	if (!rq->scx.cpu_released) {
-		if (sch->ops.cpu_release) {
-			struct scx_cpu_release_args args = {
-				.reason = preempt_reason_from_class(next_class),
-				.task = next,
-			};
-
-			SCX_CALL_OP(sch, cpu_release, rq, cpu_of(rq), &args);
-		}
-		rq->scx.cpu_released = true;
-	}
-}
-
 static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
 			      struct task_struct *next)
 {
@@ -3254,8 +3284,14 @@ static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
 	}
 
 switch_class:
+	/*
+	 * Release the CPU if @next is from a higher class. This is done after
+	 * @p went back to the local DSQ so that ops.cpu_release() can
+	 * re-enqueue it. SCX -> idle (including core-sched forced idle) is
+	 * not a transition as both are available.
+	 */
 	if (next && next->sched_class != &ext_sched_class)
-		switch_class(rq, next);
+		scx_update_cpu_avail(rq, next);
 }
 
 static void kick_sync_wait_bal_cb(struct rq *rq)
@@ -3749,10 +3785,29 @@ static void handle_hotplug(struct rq *rq, bool online)
 void scx_rq_activate(struct rq *rq)
 {
 	handle_hotplug(rq, true);
+
+	/*
+	 * The CPU comes up released. Now that ops.cpu_online() has been
+	 * called, let ops.cpu_acquire/release() through and acquire the CPU if
+	 * it's available. This can't be done from rq_online_scx() which may
+	 * run before ops.cpu_online() when the sched domains are rebuilt.
+	 */
+	guard(rq_lock_irqsave)(rq);
+	rq->scx.flags |= SCX_RQ_OPS_ONLINE;
+	scx_update_cpu_avail(rq, rq->donor);
 }
 
 void scx_rq_deactivate(struct rq *rq)
 {
+	/*
+	 * ops.cpu_offline() implies release. No ops.cpu_acquire/release()
+	 * until ops.cpu_online().
+	 */
+	scoped_guard(rq_lock_irqsave, rq) {
+		rq->scx.flags &= ~SCX_RQ_OPS_ONLINE;
+		rq->scx.cpu_released = true;
+	}
+
 	handle_hotplug(rq, false);
 }
 
@@ -6579,6 +6634,15 @@ static void scx_root_disable(struct scx_sched *sch)
 	 */
 	mutex_lock(&scx_enable_mutex);
 
+	/*
+	 * Stop ops.cpu_acquire/release() before switching tasks out so that
+	 * the BPF scheduler doesn't see a storm of releases. This must be under
+	 * scx_enable_mutex so that it's ordered after the enable path turning
+	 * the key on. In-flight callbacks hold an rq lock with IRQs disabled
+	 * and are flushed by synchronize_rcu() before ops.exit().
+	 */
+	static_branch_disable(&__scx_cpu_avail_enabled);
+
 	was_switched_all = scx_switched_all();
 
 	static_branch_disable(&__scx_switched_all);
@@ -7991,6 +8055,30 @@ static void scx_root_enable_workfn(struct kthread_work *work)
 		goto err_disable;
 	}
 
+	/*
+	 * Every CPU starts released. Once the hooks are live, acquire the
+	 * available CPUs. CPUs which don't context switch (e.g. idle ones)
+	 * wouldn't get there otherwise. scx_root_disable() turns the key off
+	 * under scx_enable_mutex, so it can't race this.
+	 */
+	if (sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) {
+		for_each_possible_cpu(cpu) {
+			struct rq *rq = cpu_rq(cpu);
+
+			guard(rq_lock_irqsave)(rq);
+			rq->scx.cpu_released = true;
+		}
+
+		static_branch_enable(&__scx_cpu_avail_enabled);
+
+		for_each_possible_cpu(cpu) {
+			struct rq *rq = cpu_rq(cpu);
+
+			guard(rq_lock_irqsave)(rq);
+			__scx_update_cpu_avail(rq, rq->donor);
+		}
+	}
+
 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
 		static_branch_enable(&__scx_switched_all);
 
@@ -8871,7 +8959,7 @@ void __init init_sched_ext_class(void)
 		rq->scx.kick_cpus_irq_work = IRQ_WORK_INIT_HARD(kick_cpus_irq_workfn);
 
 		if (cpu_online(cpu))
-			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
+			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE | SCX_RQ_OPS_ONLINE;
 	}
 
 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
kernel/sched/ext/ext.h +19 -0
index 0b7fc46aee08..c03fd8bc0d66 100644
@@ -70,6 +70,25 @@ static inline void scx_update_idle(struct rq *rq, bool idle, bool do_notify)
 static inline void scx_update_idle(struct rq *rq, bool idle, bool do_notify) {}
 #endif
 
+#ifdef CONFIG_SCHED_CLASS_EXT
+DECLARE_STATIC_KEY_FALSE(__scx_cpu_avail_enabled);
+void __scx_update_cpu_avail(struct rq *rq, struct task_struct *next);
+
+/*
+ * @next is (about to become) @rq->donor. Notify the root BPF scheduler if this
+ * changes whether @rq's CPU is available to it. Only enabled if the root
+ * scheduler implements ops.cpu_acquire() or ops.cpu_release(). A NULL @next,
+ * from put_prev_task() without a next task, is ignored.
+ */
+static inline void scx_update_cpu_avail(struct rq *rq, struct task_struct *next)
+{
+	if (static_branch_unlikely(&__scx_cpu_avail_enabled) && next)
+		__scx_update_cpu_avail(rq, next);
+}
+#else
+static inline void scx_update_cpu_avail(struct rq *rq, struct task_struct *next) {}
+#endif
+
 #ifdef CONFIG_CGROUP_SCHED
 #ifdef CONFIG_EXT_GROUP_SCHED
 void scx_tg_init(struct task_group *tg);
kernel/sched/ext/internal.h +2 -0
index 352547aedbb7..2d8c789c1e76 100644
@@ -298,6 +298,8 @@ enum scx_cpu_preempt_reason {
 	SCX_CPU_PREEMPT_STOP,
 	/* unknown reason for SCX being preempted */
 	SCX_CPU_PREEMPT_UNKNOWN,
+	/* next task is being scheduled by &fair_sched_class (partial mode) */
+	SCX_CPU_PREEMPT_FAIR,
 };
 
 /*
kernel/sched/idle.c +4 -0
index eb73b65ce6c4..89313f697124 100644
@@ -484,12 +484,16 @@ static void put_prev_task_idle(struct rq *rq, struct task_struct *prev, struct t
 {
 	update_curr_idle(rq);
 	scx_update_idle(rq, false, true);
+	/* idle -> stop/DL/RT/fair releases the CPU from the BPF scheduler */
+	scx_update_cpu_avail(rq, next);
 	update_rq_avg_idle(rq);
 }
 
 static void set_next_task_idle(struct rq *rq, struct task_struct *next, bool first)
 {
 	update_idle_core(rq);
+	/* stop/DL/RT/fair -> idle acquires the CPU for the BPF scheduler */
+	scx_update_cpu_avail(rq, next);
 	scx_update_idle(rq, true, true);
 	schedstat_inc(rq->sched_goidle);
 	next->se.exec_start = rq_clock_task(rq);
kernel/sched/sched.h +6 -0
index 4c25fbe84fb5..7a93ee3d442d 100644
@@ -787,6 +787,12 @@ enum scx_rq_flags {
 	 */
 	SCX_RQ_ONLINE		= 1 << 0,
 	SCX_RQ_CAN_STOP_TICK	= 1 << 1,
+	/*
+	 * Set between ops.cpu_online() and ops.cpu_offline(). Unlike
+	 * %SCX_RQ_ONLINE, this is never set before ops.cpu_online() has been
+	 * called. Gates ops.cpu_acquire/release().
+	 */
+	SCX_RQ_OPS_ONLINE	= 1 << 2,
 	SCX_RQ_CLK_VALID	= 1 << 5, /* RQ clock is fresh and valid */
 	SCX_RQ_BAL_CB_PENDING	= 1 << 6, /* must queue a cb after dispatching */
 	SCX_RQ_SUB_IDLE_RENOTIFY	= 1 << 7, /* sub-scheds are owed update_idle() */
Signature · 1 line
2.56.0.176.g3575e65682-goog
#3 lore raw

Re: [RFC PATCH 2/5] sched_ext: Emit ops.cpu_acquire/release() on actual CPU transitions

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] sched_ext: late cpu_avail init in scx_root_enable_workfn() misses release --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] sched_ext: late cpu_avail init in scx_root_enable_workfn() misses release --

commit b20a6c69347521827673ce5c91d0ce10ed173b33
Author: Kuba Piecuch <[email protected]>

sched_ext: Emit ops.cpu_acquire/release() on actual CPU transitions

This commit replaces switch_class() and the speculative acquire in dispatch_one() with an edge-triggered state machine in __scx_update_cpu_avail() invoked from the ext and idle classes' put_prev_task() and set_next_task() callbacks. It also initializes CPU availability state on scheduler enablement and adds SCX_RQ_OPS_ONLINE to gate callbacks across hotplug.

Quoted 4 lines
kernel/sched/ext/ext.c +0 -0
index f644382902188..4d02d2d6e6d0d 100644

[ ... ]

Quoted 18 lines
kernel/sched/ext/ext.c +14 -0
@@ -7991,6 +8055,30 @@ static void scx_root_enable_workfn(struct kthread_work *work)
 		goto err_disable;
 	}
 
+	/*
+	 * Every CPU starts released. Once the hooks are live, acquire the
+	 * available CPUs. CPUs which don't context switch (e.g. idle ones)
+	 * wouldn't get there otherwise. scx_root_disable() turns the key off
+	 * under scx_enable_mutex, so it can't race this.
+	 */
+	if (sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) {
+		for_each_possible_cpu(cpu) {
+			struct rq *rq = cpu_rq(cpu);
+
+			guard(rq_lock_irqsave)(rq);
+			rq->scx.cpu_released = true;
+		}
+

kernel/sched/ext/ext.c static void scx_root_enable_workfn(struct kthread_work *work) · line 8081

Quoted 10 lines
kernel/sched/ext/ext.c +10 -0
+		static_branch_enable(&__scx_cpu_avail_enabled);
+
+		for_each_possible_cpu(cpu) {
+			struct rq *rq = cpu_rq(cpu);
+
+			guard(rq_lock_irqsave)(rq);
+			__scx_update_cpu_avail(rq, rq->donor);
+		}
+	}
+

[Severity: Medium]
Can this initialization ordering in scx_root_enable_workfn() miss ops.cpu_release() and leave SCX tasks stranded on a local DSQ?

Earlier in scx_root_enable_workfn(), tasks are switched to ext_sched_class and scx_bypass(sch, false) is called before __scx_cpu_avail_enabled is turned on and before the initial ops.cpu_acquire() callbacks are emitted:

scx_root_enable_workfn()
scoped_guard(sched_change, p, queue_flags)

    p->sched_class = new_class;
    sched_change_end()
      set_next_task_scx() -> ops.running()
  scx_bypass(sch, false)
    sched_change -> ops.enqueue() / ops.running()
    resched_curr(rq)

Because bypass mode is already lifted at this point, ops.running(), ops.enqueue(), and ops.dispatch() can run on CPUs and populate rq->scx.local_dsq before those CPUs are acquired.

If an RT, DL, or stop task preempts a CPU after scx_bypass(sch, false) and before the second for_each_possible_cpu() loop runs __scx_update_cpu_avail() for that CPU, put_prev_task_scx() puts the preempted SCX task back on rq->scx.local_dsq and calls scx_update_cpu_avail(rq, next).

If that preemption happens before static_branch_enable(&__scx_cpu_avail_enabled), scx_update_cpu_avail() is a no-op. If it happens between static_branch_enable(&__scx_cpu_avail_enabled) and the second loop, scx_cpu_release() sees rq->scx.cpu_released == true from the first loop:

	if (rq->scx.cpu_released || !(rq->scx.flags & SCX_RQ_OPS_ONLINE))
		return;

and returns without calling ops.cpu_release(). When the second loop then calls __scx_update_cpu_avail(rq, rq->donor), rq->donor is already the higher class task, so scx_cpu_release() again sees rq->scx.cpu_released == true and does nothing. As a result, ops.cpu_release() is never called and tasks in rq->scx.local_dsq remain stranded while the higher class task runs.

Similarly, if an idle CPU wakes up to run an SCX task between static_branch_enable(&__scx_cpu_avail_enabled) and the second loop reaching that CPU, put_prev_task_idle() calls scx_update_idle(rq, false, true) before scx_update_cpu_avail(rq, next) emits the initial ops.cpu_acquire().

Should rq->scx.cpu_released initialization and the initial __scx_update_cpu_avail() pass happen before tasks are switched into SCX and scx_bypass(sch, false) is called?

Quoted 2 lines
kernel/sched/ext/ext.c +0 -0
 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
 		static_branch_enable(&__scx_switched_all);

[ ... ]

Quoted 12 lines
kernel/sched/idle.c +2 -0
index eb73b65ce6c47..89313f6971244 100644
@@ -484,12 +484,16 @@ static void put_prev_task_idle(struct rq *rq, struct task_struct *prev, struct t
 {
 	update_curr_idle(rq);
 	scx_update_idle(rq, false, true);
+	/* idle -> stop/DL/RT/fair releases the CPU from the BPF scheduler */
+	scx_update_cpu_avail(rq, next);
 	update_rq_avg_idle(rq);
 }

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#4 lore raw

RFC PATCH 3/5 sched_ext: Release the CPU when its running task leaves SCX

In reply to Kuba Piecuch

When the task running on a CPU switches from SCX to another sched_class through sched_setscheduler() or a PI boost, the CPU is taken away from the BPF scheduler without a context switch. sched_change_begin() calls put_prev_task() with a NULL @next, so put_prev_task_scx() can't tell where the task is going, and the new class's set_next_task() doesn't notify SCX. The BPF scheduler is never told that the CPU has been released.

Release the CPU from switched_from_scx() if @p is the CPU's scheduling context. Every class @p can switch to is above SCX, so the CPU is no longer available. As the new class isn't known yet, report the new SCX_CPU_PREEMPT_CLASS_CHANGE reason, with @args->task pointing to @p. The release happens before ops.disable() for @p.

switched_from_scx() is the only reliable place for this:
put_prev_task_scx() with a NULL @next is also called for changes which keep @p in SCX, and the wakeup_preempt() call at the end of sched_change_end() is skipped if rq->next_class has already been raised.

The reverse direction needs nothing new: when a running task switches to SCX, sched_change_end() calls set_next_task_scx(), which acquires the CPU.

sched_setscheduler() and PI boosting can target a task running on another CPU, so ops.cpu_release() can now be invoked for a remote CPU, with that CPU's rq locked. The legacy scx_bpf_reenqueue_local() was already switched to the locked rq to handle this.

---
 kernel/sched/ext/ext.c      | 11 +++++++++++
 kernel/sched/ext/internal.h |  2 ++
 2 files changed, 13 insertions(+)
kernel/sched/ext/ext.c +11 -0
index 4d02d2d6e6d0..d56c692f3dfa 100644
@@ -4433,6 +4433,17 @@ static void switching_to_scx(struct rq *rq, struct task_struct *p)
 
 static void switched_from_scx(struct rq *rq, struct task_struct *p)
 {
+	/*
+	 * The running task changing class (sched_setscheduler(), PI boost)
+	 * keeps the CPU without a context switch, so neither
+	 * put_prev_task_scx() nor the idle class sees it. Every class @p can
+	 * switch to is above SCX, release the CPU. The new class isn't known
+	 * yet. The scheduler being disabled is excluded by the static key.
+	 */
+	if (static_branch_unlikely(&__scx_cpu_avail_enabled) &&
+	    task_current_donor(rq, p))
+		scx_cpu_release(rq, SCX_CPU_PREEMPT_CLASS_CHANGE, p);
+
 	if (task_dead_and_done(p))
 		return;
 
kernel/sched/ext/internal.h +2 -0
index 2d8c789c1e76..65b6ec7dc2f3 100644
@@ -300,6 +300,8 @@ enum scx_cpu_preempt_reason {
 	SCX_CPU_PREEMPT_UNKNOWN,
 	/* next task is being scheduled by &fair_sched_class (partial mode) */
 	SCX_CPU_PREEMPT_FAIR,
+	/* the running task switched from SCX to another sched_class */
+	SCX_CPU_PREEMPT_CLASS_CHANGE,
 };
 
 /*
Signature · 1 line
2.56.0.176.g3575e65682-goog
#5 lore raw

RFC PATCH 4/5 sched_ext: Un-deprecate ops.cpu_acquire/release()

In reply to Kuba Piecuch

Commit a3f5d4822253 ("sched_ext: Allow scx_bpf_reenqueue_local() to be called from anywhere") deprecated ops.cpu_acquire() and ops.cpu_release() because they missed events, and fixing that was thought to require a hook invoked regardless of sched class. The previous patches make the callbacks reliable using only hooks in the ext and idle classes: they are now emitted on every transition of a CPU between being available to the BPF scheduler and being released, and only then.

A reliable, edge-triggered view of CPU availability is useful to BPF schedulers beyond re-enqueueing preempted tasks, e.g. to keep track of which CPUs can be used for placement without tracing every context switch through the sched_switch tracepoint.

Drop the deprecation warning from scx_validate_ops() and the deprecation notes from the kerneldoc. Document the contract in the kerneldoc: what available means, the order relative to ops.running() and ops.update_idle(), that ops.dispatch() may run on a released CPU, that the callbacks may be invoked for a remote CPU, and the rules for scheduler load and CPU hotplug. Also note that for SCX_CPU_PREEMPT_CLASS_CHANGE, the task in the release arguments is the one which left SCX.

The callbacks stay cpu-form only. They remain at the tail of struct sched_ext_ops, past SCX_OPI_END, and struct sched_ext_ops_cid doesn't have them. Since cpu-form schedulers can neither be sub-schedulers nor have sub-schedulers, they are root-only by construction.

---
 kernel/sched/ext/ext.c      | 15 +++------
 kernel/sched/ext/internal.h | 65 ++++++++++++++++++++++++++++---------
 2 files changed, 54 insertions(+), 26 deletions(-)
kernel/sched/ext/ext.c +4 -11
index d56c692f3dfa..7f4496667b1a 100644
@@ -7681,14 +7681,6 @@ int scx_validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
 		return -EINVAL;
 	}
 
-	/*
-	 * cid-form's struct is shorter and doesn't include the cpu_acquire /
-	 * cpu_release tail; reading those fields off a cid-form @ops would
-	 * run past the BPF allocation. Skip for cid-form.
-	 */
-	if (!sch->is_cid_type && (ops->cpu_acquire || ops->cpu_release))
-		pr_warn_ratelimited("ops->cpu_acquire/release() are deprecated, use sched_switch TP instead\n");
-
 	/*
 	 * Sub-scheduler support is tied to the cid-form struct_ops. A sub-sched
 	 * attaches through a cid-form-only interface (sub_attach/sub_detach),
@@ -11283,9 +11275,10 @@ static int __init scx_init(void)
 	/* @priv tail must align since both share the same data block */
 	CID_OFFSET_MATCH(priv, priv);
 	/*
-	 * cid-form must end exactly at @priv - scx_validate_ops() skips
-	 * cpu_acquire/cpu_release for cid-form because reading those fields
-	 * past the BPF allocation would be UB.
+	 * cid-form must end exactly at @priv. It doesn't have the cpu-form only
+	 * cpu_acquire/cpu_release and reading them off a cid-form @ops would
+	 * run past the BPF allocation. The kernel copy in sch->ops keeps them
+	 * zero for cid-form, see scx_alloc_and_add_sched().
 	 */
 	BUILD_BUG_ON(offsetof(struct sched_ext_ops_cid, __end) !=
 		     offsetofend(struct sched_ext_ops, priv));
kernel/sched/ext/internal.h +50 -15

101 lines not on this page · raw message

Signature · 1 line
2.56.0.176.g3575e65682-goog
#6 lore raw

RFC PATCH 5/5 selftests/sched_ext: Add cpu_avail tests

In reply to Kuba Piecuch

Add tests verifying that ops.cpu_acquire() and ops.cpu_release() are invoked on every change of a CPU's availability to the BPF scheduler, and only then.

The cpu_avail BPF scheduler tracks the state reported by the callbacks per CPU, flagging double acquires and releases as well as callbacks between ops.cpu_offline() and ops.cpu_online(). A sched_switch tracepoint program checks after every pick that the reported state matches the incoming task. In full switch mode, a CPU must be released iff the task about to run has an RT or deadline priority, which covers the stop task and PI-boosted tasks too. In partial mode, tasks without the SCHED_EXT policy release it as well. The checker skips a CPU while userspace hotplugs it, as the kernel releases the CPU before ops.cpu_offline() updates the BPF side.

cpu_avail runs the following scenarios on top of the invariant checker:

- idle_to_rt: an RT task waking up on an idle CPU releases it, with the callback invoked from the idle task, and the CPU is acquired again when the RT task sleeps.
- class_change: switching a running SCX task to SCHED_FIFO from another CPU releases its CPU remotely with SCX_CPU_PREEMPT_CLASS_CHANGE and switching it back acquires the CPU. If the task happened not to be running at that moment, e.g. because the stopper preempted it, the switch is retried once.
- remote_reenq: same as class_change with tasks queued on the target CPU's local DSQ and ops.cpu_release() calling the legacy, synchronous scx_bpf_reenqueue_local(). The queued tasks must be re-enqueued.
- pi_boost: an SCX task holding a PI mutex is boosted by an RT waiter on another CPU, which releases its CPU until it's deboosted.
- churn: RT tasks, SCX tasks and class changes on all CPUs at once.
- hotplug: no callbacks while the CPU is offline and an acquire after it comes back online.
- partial: in partial mode, idle -> fair and a fair task preempting an SCX task release the CPU with SCX_CPU_PREEMPT_FAIR, and
a running SCHED_EXT task switching to SCHED_OTHER releases it with SCX_CPU_PREEMPT_CLASS_CHANGE.
- reload: every scheduler instance gets an initial acquire for every online CPU.

cpu_avail_core needs SMT and runs SCX tasks with different core-sched cookies on two siblings. The resulting forced idle must not release the CPUs. An RT task sharing the other sibling's cookie must release and re-acquire its CPU.

Also add the cpu_acquire/release() stubs back to the maximal scheduler now that they are no longer deprecated.

---
 tools/testing/selftests/sched_ext/Makefile    |   2 +
 .../selftests/sched_ext/cpu_avail.bpf.c       | 218 ++++++
 tools/testing/selftests/sched_ext/cpu_avail.c | 717 ++++++++++++++++++
 tools/testing/selftests/sched_ext/cpu_avail.h | 237 ++++++
 .../selftests/sched_ext/cpu_avail_core.c      | 256 +++++++
 .../testing/selftests/sched_ext/maximal.bpf.c |  10 +
 6 files changed, 1440 insertions(+)
 create mode 100644 tools/testing/selftests/sched_ext/cpu_avail.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/cpu_avail.c
 create mode 100644 tools/testing/selftests/sched_ext/cpu_avail.h
 create mode 100644 tools/testing/selftests/sched_ext/cpu_avail_core.c
tools/testing/selftests/sched_ext/Makefile +2 -0
index af919a56a4f4..c0861bd33d3a 100644
@@ -162,6 +162,8 @@ endef
 all_test_bpfprogs := $(foreach prog,$(wildcard *.bpf.c),$(INCLUDE_DIR)/$(patsubst %.c,%.skel.h,$(prog)))
 
 auto-test-targets :=			\
+	cpu_avail			\
+	cpu_avail_core			\
 	create_dsq			\
 	dequeue				\
 	dequeue_iter			\
tools/testing/selftests/sched_ext/cpu_avail.bpf.c new file +218 -0

218 lines not on this page · raw message

tools/testing/selftests/sched_ext/cpu_avail.c new file +717 -0

717 lines not on this page · raw message

tools/testing/selftests/sched_ext/cpu_avail.h new file +237 -0

237 lines not on this page · raw message

tools/testing/selftests/sched_ext/cpu_avail_core.c new file +256 -0

256 lines not on this page · raw message

tools/testing/selftests/sched_ext/maximal.bpf.c +10 -0
index 04a369078aac..c2ee5437df65 100644
@@ -67,6 +67,14 @@ void BPF_STRUCT_OPS(maximal_set_cpumask, struct task_struct *p,
 void BPF_STRUCT_OPS(maximal_update_idle, s32 cpu, bool idle)
 {}
 
+void BPF_STRUCT_OPS(maximal_cpu_acquire, s32 cpu,
+		    struct scx_cpu_acquire_args *args)
+{}
+
+void BPF_STRUCT_OPS(maximal_cpu_release, s32 cpu,
+		    struct scx_cpu_release_args *args)
+{}
+
 SEC("tp_btf/sched_switch")
 int BPF_PROG(maximal_sched_switch, bool preempt, struct task_struct *prev,
 	     struct task_struct *next, unsigned int prev_state)
@@ -149,6 +157,8 @@ struct sched_ext_ops maximal_ops = {
 	.set_weight		= (void *) maximal_set_weight,
 	.set_cpumask		= (void *) maximal_set_cpumask,
 	.update_idle		= (void *) maximal_update_idle,
+	.cpu_acquire		= (void *) maximal_cpu_acquire,
+	.cpu_release		= (void *) maximal_cpu_release,
 	.cpu_online		= (void *) maximal_cpu_online,
 	.cpu_offline		= (void *) maximal_cpu_offline,
 	.init_task		= (void *) maximal_init_task,
Signature · 1 line
2.56.0.176.g3575e65682-goog
#7 lore raw

Re: [RFC PATCH 5/5] selftests/sched_ext: Add cpu_avail tests

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] selftests/sched_ext: spinners in test_churn() inherit single-CPU affinity --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] selftests/sched_ext: spinners in test_churn() inherit single-CPU affinity --

commit 8fdb05fa56aeeeb8544b8552cb1d015e3ebd3eff
Author: Kuba Piecuch <[email protected]>

selftests/sched_ext: Add cpu_avail tests

This commit adds the cpu_avail and cpu_avail_core selftests to verify that ops.cpu_acquire() and ops.cpu_release() accurately track CPU availability across various scheduling transitions, hotplug events, and core scheduling.

Quoted 5 lines
tools/testing/selftests/sched_ext/cpu_avail.c new file +0 -0
new file mode 100644
index 0000000000000..3796f94b05a93

[ ... ]

Quoted 55 lines
tools/testing/selftests/sched_ext/cpu_avail.c new file +55 -0
+/*
+ * Run RT tasks, SCX tasks and sched_setscheduler() class changes on all CPUs
+ * at once. The sched_switch checker must not find any inconsistencies.
+ */
+static enum scx_test_status test_churn(struct cpu_avail_ctx *ctx)
+{
+	struct cpu_avail__bss *bss = ctx->skel->bss;
+	struct task_spec spinner = { .cpu = -1, .policy = SCHED_OTHER };
+	struct task_spec rt = {
+		.policy = SCHED_FIFO, .prio = 20,
+		.period_us = 1000, .run_us = 200, .duration_ms = 1500,
+	};
+	enum scx_test_status ret = SCX_TEST_FAIL;
+	int nr_spinners = 0, nr_rts = 0, cpu, i;
+	pid_t *spinners, *rts;
+	u64 checks = bss->nr_checks;
+	u64 end;
+
+	spinners = calloc(ctx->nr_cpus, sizeof(pid_t));
+	rts = calloc(ctx->nr_cpus, sizeof(pid_t));
+	if (!spinners || !rts) {
+		SCX_ERR("Failed to allocate");
+		goto out;
+	}
+
+	for (cpu = 0; cpu < ctx->nr_cpus; cpu++) {
+		if (!cpu_is_online(cpu))
+			continue;
+
+		spinners[nr_spinners] = spawn_task(&spinner);
+		if (spinners[nr_spinners] < 0) {
+			SCX_ERR("Failed to fork (%d)", errno);
+			goto out;
+		}
+		nr_spinners++;
+
+		rt.cpu = cpu;
+		rts[nr_rts] = spawn_task(&rt);
+		if (rts[nr_rts] < 0) {
+			SCX_ERR("Failed to fork (%d)", errno);
+			goto out;
+		}
+		nr_rts++;
+	}
+
+	/* flip a spinner between SCX and RT while the RT tasks run */
+	end = now_ns() + 1500 * 1000000ULL;
+	for (i = 0; now_ns() < end; i++) {
+		if (set_policy(spinners[0], i % 2 ? SCHED_OTHER : SCHED_FIFO,
+			       i % 2 ? 0 : 1)) {
+			SCX_ERR("Failed to set policy (%d)", errno);
+			goto out;
+		}
+		sleep_ms(2);
+	}

[ ... ]

Quoted 4 lines
tools/testing/selftests/sched_ext/cpu_avail.c new file +4 -0
+static enum scx_test_status setup(void **ctxp)
+{
+	struct cpu_avail_ctx *ctx;
+	int cpu;

[ ... ]

Quoted 6 lines
tools/testing/selftests/sched_ext/cpu_avail.c new file +6 -0
+	if (sched_getaffinity(0, sizeof(ctx->orig_mask), &ctx->orig_mask) ||
+	    pin_to_cpu(0, ctx->ctl_cpu)) {
+		SCX_ERR("Failed to pin to CPU %d", ctx->ctl_cpu);
+		free(ctx);
+		return SCX_TEST_FAIL;
+	}

[ ... ]

Quoted 5 lines
tools/testing/selftests/sched_ext/cpu_avail.h new file +0 -0
new file mode 100644
index 0000000000000..97659e1061b87

[ ... ]

Quoted 13 lines
tools/testing/selftests/sched_ext/cpu_avail.h new file +13 -0
+static inline pid_t fork_task(const struct task_spec *spec, int *go_fd)
+{
+	int fds[2];
+	pid_t pid;
+	char c;
+
+	if (pipe(fds))
+		return -1;
+
+	pid = fork();
+	if (pid < 0) {
+		close(fds[0]);
+		close(fds[1]);

tools/testing/selftests/sched_ext/cpu_avail.h line 146

Quoted 10 lines
tools/testing/selftests/sched_ext/cpu_avail.h new file +10 -0
+		return -1;
+	}
+
+	if (!pid) {
+		close(fds[1]);
+		if (read(fds[0], &c, 1) != 1)
+			exit(EXIT_FAILURE);
+		close(fds[0]);
+		if (spec->cpu >= 0 && pin_to_cpu(0, spec->cpu))
+			exit(EXIT_FAILURE);

[Severity: Medium]
Does setting spec->cpu = -1 in test_churn() leave all spinner tasks pinned to ctx->ctl_cpu instead of running across all CPUs?

In setup(), the parent test runner pins itself to ctx->ctl_cpu via pin_to_cpu(0, ctx->ctl_cpu). When test_churn() spawns spinners with spinner.cpu = -1 via spawn_task() -> fork_task(), fork_task() only changes affinity when spec->cpu >= 0, so the child inherits the parent's single-CPU affinity mask on ctx->ctl_cpu.

Because p->nr_cpus_allowed is 1, cpu_avail_enqueue() in tools/testing/selftests/sched_ext/cpu_avail.bpf.c queues all spinners onto SCX_DSQ_LOCAL for ctx->ctl_cpu rather than SCX_DSQ_GLOBAL:

	/* queue pinned tasks on the local DSQ of the CPU they're enqueued on */
	if (p->nr_cpus_allowed == 1)
		scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL, slice, enq_flags);
	else
		scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, slice, enq_flags);

In addition, when test_churn() switches spinners[0] (an infinite busy-loop task with period_us == 0) to SCHED_FIFO on iteration i = 0, spinners[0] is pinned to the same ctx->ctl_cpu as the SCHED_OTHER test runner. This immediately preempts and starves the test runner until RT throttling kicks in, where the runner then has to wait behind all the other spinners queued on ctx->ctl_cpu's local DSQ (which on machines with many CPUs can stall runnable tasks on ctx->ctl_cpu past the 10-second watchdog timeout).

Should fork_task() restore a full CPU affinity mask (such as ctx->orig_mask) when spec->cpu < 0?

Quoted 6 lines
tools/testing/selftests/sched_ext/cpu_avail.h new file +6 -0
+		if (spec->policy != SCHED_OTHER &&
+		    set_policy(0, spec->policy, spec->prio))
+			exit(EXIT_FAILURE);
+		task_body(spec);
+		exit(EXIT_SUCCESS);
+	}

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#8 lore raw
In reply to Kuba Piecuch
Quoted 4 lines · Kuba Piecuch

- ops.cpu_acquire() moves from before ops.dispatch() to the point where the CPU actually switches to an SCX task or idle, so ops.dispatch() may now run on a released CPU. A speculative acquire before dispatch can't be made reliable without hooks in every class.

I'd like to reconsider this part of the approach, for two reasons.

First, it changes the semantics of ops.cpu_acquire() relative to the original implementation. Schedulers could so far assume that the CPU is acquired whenever ops.dispatch() runs. With this patchset they can't.

Second, it loses a case ops.cpu_release() should cover. Say an RT task blocks, ops.dispatch() inserts T into the local DSQ, the rq lock gets dropped, another RT task wakes up on the CPU, the SCX pick returns RETRY_TASK and the RT task wins. That's an RT -> RT switch, so the CPU never becomes available, no ops.cpu_release() is invoked and T sits on the local DSQ until the CPU picks from SCX again.

The standard answer to that would be SCX_ENQ_IMMED, but IMMED isn't bulletproof either. It relies on rq->next_class being raised through wakeup_preempt() whenever a higher-class task is about to take the CPU, and there are several ways around that:

- sched_setscheduler() or a PI boost promoting a queued task to RT/DL:
sched_change_end() doesn't call wakeup_preempt() for non-running tasks, switched_to_rt() only does resched_curr() and switched_to_dl() calls wakeup_preempt_dl() directly.

- DL replenishment (dl_task_timer()), CFS bandwidth unthrottling (partial mode) and RT group unthrottling enqueue and resched_curr() without going through wakeup_preempt().

- When the ext dl_server picks an SCX task, next_class becomes ext although RT tasks are queued, so rq_is_open() accepts IMMED inserts. Once the server runs out of budget, RT takes over without any wakeup.

- With core scheduling, a forced idle pick resets next_class to idle while tasks remain on the local DSQ, so a later RT wakeup goes to wakeup_preempt_idle() rather than wakeup_preempt_scx().

In all of these, IMMED tasks end up stranded on the local DSQ behind the higher-class task.

Making next_class exact would mean touching rt, dl, fair and core, and still wouldn't cover the dl_server and forced idle cases. What I think would fix it is a single SCX hook in __schedule(), right after the pick:

	next = pick_next_task(rq, &rf);
	rq->next_class = next->sched_class;
	scx_settle_pick(rq, next);

gated on scx_enabled() and next's class being above ext. At that point the pick is final, the hook runs on the CPU that's going to run next (core-sched siblings settle in their own __schedule()), and a preempted prev as well as anything ops.dispatch() inserted are already on the local DSQ. If rq->scx.nr_immed is non-zero, the hook schedules a re-enqueue of the IMMED tasks, whatever made the higher-class task runnable.

The same hook also allows fixing ops.cpu_acquire/release() while preserving the original semantics. ops.cpu_acquire() stays in dispatch_one(), before ops.dispatch(), and the hook releases the CPU if it's still acquired when the pick lands above ext, with the task actually picked in args->task. That correctly handles every abandoned pick (RETRY_TASK, the ext dl_server returning NULL, core-sched restarts), and in the example with an RT task above ops.cpu_release() gets to re-enqueue T. The release calls v1 adds to put_prev_task_scx() and put_prev_task_idle() go away. The rest of v1 (class changes, hotplug, enable/disable) stays.

Tejun, Peter, would a hook like this be acceptable? The core.c footprint is one line, it's a static branch when SCX isn't enabled, and the out-of-line call only happens when the pick goes to a class above SCX. If you're OK with it, I'd send the IMMED fix first, separately (Fixes: 98d709cba319 ("sched_ext: Implement SCX_ENQ_IMMED")), and rebase v2 of this series on top of it.

Thanks,
Kuba

reviewer
#9 lore raw

Hello, Kuba.

Quoted 6 lines · Kuba Piecuch

Tejun, Peter, would a hook like this be acceptable? The core.c footprint is one line, it's a static branch when SCX isn't enabled, and the out-of-line call only happens when the pick goes to a class above SCX. If you're OK with it, I'd send the IMMED fix first, separately (Fixes: 98d709cba319 ("sched_ext: Implement SCX_ENQ_IMMED")), and rebase v2 of this series on top of it.

I don't really see a lot of utility in ops.cpu_acquire/release(). As it currently stands, it doesn't add anything that can't be covered by IMMED, and given how asynchronous the events are, I'm not sure an edge-triggered view of CPU availability is particularly useful. IMMED works because it's something the kernel can check and enforce. If there are holes in it, let's plug them, but I don't think the holes justify keeping or updating ops.cpu_acquire/release().

Can you please send the IMMED fixes separately?

Thanks.

--
tejun

#10 lore raw

Hi Tejun,

Quoted 2 lines · Tejun Heo

I don't really see a lot of utility in ops.cpu_acquire/release(). As it currently stands, it doesn't add anything that can't be covered by IMMED,

That's true if the only thing you do from ops.cpu_release() is re-enqueue the local DSQ. It may not be true if you're trying to do other things like e.g. kicking the sibling CPU in scx_pair.

Fixing ops.cpu_release() would let us get rid of the sched_switch hack in scx_pair, which we know isn't perfect at detecting CPU preemption by a higher sched_class.

Quoted 5 lines

and given how asynchronous the events are, I'm not sure an edge-triggered view of CPU availability is particularly useful. IMMED works because it's something the kernel can check and enforce. If there are holes in it, let's plug them, but I don't think the holes justify keeping or updating ops.cpu_acquire/release().

ops.cpu_acquire() is synchronously invoked in the dispatch path, and ops.cpu_release() would be invoked when the sched_class of rq->donor goes above ext_sched_class, so either in __schedule() or when changing the sched_class of a running task. It doesn't strike me as particularly asynchronous.

Part of my motivation is Google's BPF schedulers, which are composed of subschedulers, and we explicitly track which CPU is owned by which subscheduler. Having a reliable CPU preemption callback would help with porting them over to sched_ext.

Quoted 1 line

Can you please send the IMMED fixes separately?

Will do.

Thanks,
Kuba

reviewer
#11 lore raw

Hello, Kuba.

Quoted 7 lines · Kuba Piecuch

That's true if the only thing you do from ops.cpu_release() is re-enqueue the local DSQ. It may not be true if you're trying to do other things like e.g. kicking the sibling CPU in scx_pair.

Fixing ops.cpu_release() would let us get rid of the sched_switch hack in scx_pair, which we know isn't perfect at detecting CPU preemption by a higher sched_class.

What I don't like about ops.cpu_acquire/release() is that they track whether the CPU is occupied by a sched_class higher than SCX, which seems a bit out of scope for a sched_class. Wanting to know that is fine, but it's global system state and would be better tracked by hooking into system events than built into sched_ext. I don't think the acquire/release semantics are a good fit for it either.

Quoted 4 lines

Part of my motivation is Google's BPF schedulers, which are composed of subschedulers, and we explicitly track which CPU is owned by which subscheduler. Having a reliable CPU preemption callback would help with porting them over to sched_ext.

If sched_switch isn't enough, how about adding a tracepoint which tracks the sched_class currently in effect on each CPU? That should cover both scx_pair and your use case, and would be useful outside sched_ext too.

Thanks.

--
tejun