Skip to contentSkip to conversation

sched_ext: sub: Don't run ops.sub_caps_updated() in an SCX op context

RFC PATCH New Kuba Piecuch 2 participants 4 messages Nov 25

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

RFC PATCH 1/1 sched_ext: sub: Don't run ops.sub_caps_updated() in an SCX op context

scx_bpf_sub_grant() and scx_bpf_sub_revoke() are in scx_kfunc_ids_any, so a parent scheduler can call them from any op. Before returning, they deliver ops.sub_caps_updated() to the affected children synchronously:

  caps_updated_deliver()
    SCX_CALL_OP(sch, sub_caps_updated, NULL, cu->cmask_arena_out, caps);

__SCX_CALL_OP() leaves scx_locked_rq_state untouched when locked_rq is NULL. Unlike other SCX ops, which either always run unlocked or always hold a known rq lock, ops.sub_caps_updated() inherits whatever context its parent happened to call grant or revoke from:

1) Inconsistent locking context across calls. When the parent calls grant/revoke from ops.sub_attach() or a BPF timer, scx_locked_rq() is NULL; when it calls them from an rq-locked op, scx_locked_rq() still points at the parent's rq. For example, scx_qmap nested three deep runs a grandchild's ops.sub_caps_updated() under the middle scheduler's rq lock when ops.sub_ecaps_updated() picks up a pending PART_REDISTRIBUTE in execute_partition() -> apply_partition().

ops.sub_caps_updated() has no scx_kf_allow_flags[] entry (only the universal any/idle/cid kfunc sets are allowed), yet kfuncs in scx_kfunc_ids_any consult scx_locked_rq() and the child has no safe way to probe which state it is in: scx_bpf_locked_rq() aborts the child when unlocked, SCX_DSQ_LOCAL in scx_bpf_dsq_reenq() and scx_bpf_dsq_nr_queued() resolves to scx_locked_rq() ?: this_rq(), and scx_bpf_cidperf_set() (for example on cids where SCX_CAP_PERF is already effective) works across all cids when unlocked but aborts the child on any cid outside the parent's rq:

CPU 2, parent P, child sub-scheduler C
enqueue_task_scx(rq2, p) // rq2 locked
SCX_CALL_OP_TASK(P, enqueue, rq2, p) // scx_locked_rq() = rq2
P.enqueue(p)
scx_bpf_sub_grant(C, SCX_CAP_PERF, cids)
caps_updated_deliver()
SCX_CALL_OP(C, sub_caps_updated, NULL) // still rq2
C.sub_caps_updated()
scx_bpf_cidperf_set(cid of CPU 1, ...)
scx_cpuperf_set()
scx_error("Invalid target CPU 1") // C aborted

sched_ext: BPF sub-scheduler "sub_caps_ctx" disabled (runtime error)
sched_ext: sub_caps_ctx: Invalid target CPU 1
bpf__sched_ext_ops_cid_sub_caps_updated+0x57/0xb7 bpf__sched_ext_ops_cid_enqueue+0x50/0xb0

2) Parent lock hold time across subtree cascades. ops.sub_caps_updated() is meant to track held shard caps and propagate grant/revoke to children. A single grant or revoke can synchronously fan out across a subtree of descendant callbacks (up to SCX_SUB_MAX_DEPTH levels, with multiple children per level) while the parent's rq lock, p->pi_lock (from ops.select_cpu()) or scx_dump_lock (from ops.dump*()) remains held, delaying other CPUs contending on that lock.

3) Dump state leakage. When the call comes from ops.dump*(), scx_dump_data.cpu remains set, so a child calling scx_bpf_dump() passes the check in scx_bpf_dump_bstr() and writes into the parent's dump instead of failing.

Sending as an RFC because there is no obvious best way to resolve this:

- Restricting scx_bpf_sub_grant() and scx_bpf_sub_revoke() to unlocked ops would avoid deferred delivery, but would disallow repartitioning from rq-locked callbacks such as scx_qmap's ops.sub_ecaps_updated().

- Keeping synchronous delivery as-is, handling scx_dump_data separately (or rejecting grant/revoke during dump), and documenting that ops.sub_caps_updated() inherits the caller's locking context would avoid irq_work while keeping kfuncs deadlock-free, at the cost of an inconsistent locked/unlocked context and holding parent locks across subtree cascades.

- Deferring delivery to irq_work when called from an SCX op context (this series) keeps grant/revoke callable from any op while giving ops.sub_caps_updated() a consistent unlocked context and releasing parent locks and dump state before subtree callbacks run, at the cost of extra irq_work, hotplug, PM and teardown machinery.

Patch 1 adds caps_updated_deliver_or_defer() for grant/revoke. When the caller has an rq locked, has kf_tasks[] set, is in ops.select_cpu() or is dumping (the new scx_in_dump()), the to_deliver list is spliced onto a global pending list and a per-cpu hard irq_work delivers it. Each cpu uses its own hard irq_work so concurrent deliveries across cpus cannot clear IRQ_WORK_BUSY early, and so a dying cpu on PREEMPT_RT doesn't strand work after its irq_work thread is parked; if this cpu is already offline (such as ops.update_idle() when hotplug parks the migration thread), an online cpu's irq_work is kicked instead. While PM is in progress, kicking is suppressed so irq_work_queue() never runs in the syscore phase, and scx_sub_pm_end() kicks any queued deliveries once the PM cycle ends. Otherwise delivery stays synchronous, as before. Queued scx_caps_updated nodes stay in flight, so later changes keep coalescing into them. scx_free_pshards() drops a dying scheduler's queued entries and flushes every cpu's irq_work before freeing the pshards.

Patch 2 adds the sub_caps_ctx selftest. A cid-form root grants/revokes SCX_CAP_PERF to a child from ops.enqueue() and SCX_CAP_PREEMPT from ops.select_cid(). The child calls scx_bpf_cidperf_set() on every cid from ops.sub_caps_updated(). Without patch 1, sub_caps_ctx fails with:

Scheduler exited unexpectedly (kind=1024 code=0 msg='Invalid target CPU 0')

The patches were written with the help of an AI coding assistant.

Kuba Piecuch (2):
sched_ext: sub: Defer ops.sub_caps_updated() out of SCX op contexts selftests/sched_ext: Test that ops.sub_caps_updated() runs unlocked

 kernel/sched/ext/ext.c                        |   6 +
 kernel/sched/ext/internal.h                   |   8 +
 kernel/sched/ext/sub.c                        | 129 +++++++++++++-
 tools/testing/selftests/sched_ext/Makefile    |   1 +
 .../selftests/sched_ext/sub_caps_ctx.bpf.c    | 136 +++++++++++++++
 .../selftests/sched_ext/sub_caps_ctx.c        | 165 ++++++++++++++++++
 6 files changed, 441 insertions(+), 4 deletions(-)
 create mode 100644 tools/testing/selftests/sched_ext/sub_caps_ctx.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/sub_caps_ctx.c

base-commit: 97e1c7d467d07734f8f5c8c64730e1f7c415bd46

Signature · 1 line
2.56.1.839.g22a8290db9-goog
#1 lore raw

RFC PATCH 1/2 sched_ext: sub: Defer ops.sub_caps_updated() out of SCX op contexts

scx_bpf_sub_grant() and scx_bpf_sub_revoke() are in scx_kfunc_ids_any and deliver ops.sub_caps_updated() synchronously with a NULL locked_rq. __SCX_CALL_OP() leaves scx_locked_rq_state untouched when locked_rq is NULL, so ops.sub_caps_updated() inherits whatever context its parent called grant or revoke from:

- From ops.sub_attach() or a BPF timer, scx_locked_rq() is NULL. From an rq-locked op (such as ops.enqueue(), or scx_qmap repartitioning a grandchild from ops.sub_ecaps_updated()), scx_locked_rq() points at the parent's rq. Unlike other callbacks, the child cannot safely tell which state it is in: scx_bpf_locked_rq() aborts the child when unlocked, scx_bpf_cidperf_set() aborts it with "Invalid target CPU" on any cid outside the parent's rq, and SCX_DSQ_LOCAL in scx_bpf_dsq_reenq() and scx_bpf_dsq_nr_queued() resolves to scx_locked_rq() ?: this_rq().

- Because ops.sub_caps_updated() may propagate grant/revoke to its own children, synchronous delivery can fan out across a subtree of descendant callbacks while holding the parent's rq lock, p->pi_lock (from ops.select_cpu()) or scx_dump_lock (from ops.dump*()), extending lock hold time.

- From ops.dump*(), scx_dump_data.cpu remains set, so a child calling scx_bpf_dump() writes into the parent's dump instead of failing.

Give ops.sub_caps_updated() a consistent unlocked context by deferring delivery when grant or revoke runs in an SCX op context (an rq lock held, kf_tasks[] set, ops.select_cpu() or ops.dump*()). Queue the deliveries on a global list and kick a per-cpu hard irq_work, or an online cpu's when this cpu is going down. Suppress the kick while PM is in progress, where irq_work_queue() can malfunction in the syscore phase, and kick any queued deliveries from scx_sub_pm_end(). Queued nodes stay in flight so later updates keep coalescing into them. Before freeing a scheduler's pshards, scx_free_pshards() drops its queued entries and flushes every cpu's irq_work.

Fixes 5f2a9a4c2e6c ("sched_ext: Add coalescing sub_caps_updated() notifier for sub-schedulers")
---
 kernel/sched/ext/ext.c      |   6 ++
 kernel/sched/ext/internal.h |   8 +++
 kernel/sched/ext/sub.c      | 129 ++++++++++++++++++++++++++++++++++--
 3 files changed, 139 insertions(+), 4 deletions(-)
kernel/sched/ext/ext.c +6 -0
index efa1d01d03af..570d6c923904 100644
@@ -7964,6 +7964,12 @@ static void ops_dump_exit(void)
 	scx_dump_data.cpu = -1;
 }
 
+/* whether this cpu is in scx_dump_state(), where scx_bpf_dump() is allowed */
+bool scx_in_dump(void)
+{
+	return READ_ONCE(scx_dump_data.cpu) == raw_smp_processor_id();
+}
+
 static void scx_dump_task(struct scx_sched *sch, struct seq_buf *s, struct scx_dump_ctx *dctx,
 			  struct rq *rq, struct task_struct *p, char marker)
 {
kernel/sched/ext/internal.h +8 -0
index 58652370da5a..69846ac85a44 100644
@@ -909,6 +909,8 @@ struct sched_ext_ops {
 	 * cpu, once it is in effect.
 	 *
 	 * May call scx_bpf_sub_grant() / scx_bpf_sub_revoke() on children.
+	 * Even if the parent called grant / revoke under an rq lock or from
+	 * ops.select_cpu() or ops.dump*(), this callback runs unlocked.
 	 */
 	void (*sub_caps_updated)(const struct scx_cmask *cmask, u64 caps);
 
@@ -1666,6 +1668,11 @@ enum scx_cap_flags {
  *
  * (3) leads to deferred delivery. Events accumulate during grant/revoke and are
  * delivered after the shard lock is released.
+ *
+ * When grant or revoke runs in an SCX op context (an rq lock held,
+ * ops.select_cpu() or ops.dump*()), caps_updated_deliver_or_defer() defers the
+ * delivery to an irq_work so that ops.sub_caps_updated() always runs unlocked
+ * instead of inheriting the caller's context.
  */
 struct scx_caps_updated {
 	raw_spinlock_t		lock;
@@ -2314,6 +2321,7 @@ bool scx_consume_dispatch_q(struct scx_sched *sch, struct rq *rq,
 			    struct scx_dispatch_q *dsq, u64 enq_flags);
 bool scx_consume_global_dsq(struct scx_sched *sch, struct rq *rq);
 bool scx_rq_online(struct rq *rq);
+bool scx_in_dump(void);
 void scx_flush_dispatch_buf(struct scx_sched *sch, struct rq *rq);
 s32 scx_init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id, struct scx_sched *sch);
 __printf(2, 3) void scx_dump_line(struct seq_buf *s, const char *fmt, ...);
kernel/sched/ext/sub.c +125 -4

177 lines not on this page · raw message

Signature · 1 line
2.56.1.839.g22a8290db9-goog
#2 lore raw

RFC PATCH 2/2 selftests/sched_ext: Test that ops.sub_caps_updated() runs unlocked

In reply to Kuba Piecuch

Add sub_caps_ctx. A cid-form root grants and revokes caps to a child sub-scheduler from ops.enqueue() (SCX_CAP_PERF) and ops.select_cid() (SCX_CAP_PREEMPT). The child calls scx_bpf_cidperf_set() on every cid from ops.sub_caps_updated(), which aborts the child if the callback inherits the parent's rq lock. The test is skipped on a single cpu, where the only cid is the parent's rq.

---
 tools/testing/selftests/sched_ext/Makefile    |   1 +
 .../selftests/sched_ext/sub_caps_ctx.bpf.c    | 136 +++++++++++++++
 .../selftests/sched_ext/sub_caps_ctx.c        | 165 ++++++++++++++++++
 3 files changed, 302 insertions(+)
 create mode 100644 tools/testing/selftests/sched_ext/sub_caps_ctx.bpf.c
 create mode 100644 tools/testing/selftests/sched_ext/sub_caps_ctx.c
tools/testing/selftests/sched_ext/Makefile +1 -0
index 9a776a8a36ff..caedba9dcde9 100644
@@ -196,6 +196,7 @@ auto-test-targets :=			\
 	select_cpu_dispatch_bad_dsq	\
 	select_cpu_dispatch_dbl_dsp	\
 	select_cpu_vtime		\
+	sub_caps_ctx			\
 	rt_stall			\
 	test_example			\
 	total_bw			\
tools/testing/selftests/sched_ext/sub_caps_ctx.bpf.c new file +136 -0

136 lines not on this page · raw message

tools/testing/selftests/sched_ext/sub_caps_ctx.c new file +165 -0

165 lines not on this page · raw message

Signature · 1 line
2.56.1.839.g22a8290db9-goog
#3 lore raw

Re: [RFC PATCH 2/2] selftests/sched_ext: Test that ops.sub_caps_updated() runs unlocked

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [Medium] selftests/sched_ext: colliding fixed map_extra arena mapping in sub_caps_ctx - [Low]…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [Medium] selftests/sched_ext: colliding fixed map_extra arena mapping in sub_caps_ctx
- [Low] selftests/sched_ext: hardcoded /sys/fs/cgroup and hand-rolled I/O in setup()
- [Low] selftests/sched_ext: setup() leaks CGRP_PATH directory on error paths
- [Low] selftests/sched_ext: run() leaves worker child processes unreaped on failure
- [Low] selftests/sched_ext: silent SCX_TEST_SKIP returns in setup() --

commit 4d12e206bd2b4220ed100124b368c1ee420871bc
Author: Kuba Piecuch <[email protected]>

selftests/sched_ext: Test that ops.sub_caps_updated() runs unlocked

This commit adds the sub_caps_ctx selftest to verify that a child sub-scheduler's ops.sub_caps_updated() callback runs without holding the parent's rq lock when capabilities are granted or revoked from ops.enqueue() and ops.select_cid().

Quoted 6 lines
tools/testing/selftests/sched_ext/sub_caps_ctx.bpf.c new file +0 -0
new file mode 100644
index 0000000000000..e6613fc23d15e
@@ -0,0 +1,136 @@

[ ... ]

tools/testing/selftests/sched_ext/sub_caps_ctx.bpf.c line 27

Quoted 10 lines
tools/testing/selftests/sched_ext/sub_caps_ctx.bpf.c new file +10 -0
+struct {
+	__uint(type, BPF_MAP_TYPE_ARENA);
+	__uint(map_flags, BPF_F_MMAPABLE);
+	__uint(max_entries, 1 << 8);
+#if defined(__TARGET_ARCH_arm64) || defined(__aarch64__)
+	__ulong(map_extra, 0x1ull << 32);
+#else
+	__ulong(map_extra, 0x1ull << 44);
+#endif
+} arena SEC(".maps");

[Severity: Medium]
Does setting a fixed map_extra address cause the child skeleton's arena mapping to collide with the parent's?

When map_extra is non-zero, libbpf maps the arena with MAP_FIXED at that user virtual address. Because setup() loads both test_ctx.parent and test_ctx.child in the same process, loading test_ctx.child overwrites test_ctx.parent's user arena mapping at the same address, and cleanup() later calls munmap() twice on that range. Also, 0x1ull << 44 exceeds the user virtual address space on architectures such as riscv64 SV39, causing skeleton load to fail. Since userspace never accesses this arena, can map_extra be omitted as in enable_cmask.bpf.c and unlocked_kfunc_cid.bpf.c?

[ ... ]

Quoted 6 lines
tools/testing/selftests/sched_ext/sub_caps_ctx.c new file +0 -0
new file mode 100644
index 0000000000000..5881a6312cb65
@@ -0,0 +1,165 @@

[ ... ]

Quoted 12 lines
tools/testing/selftests/sched_ext/sub_caps_ctx.c new file +12 -0
+#define CGRP_ROOT	"/sys/fs/cgroup"
+#define CGRP_PATH	CGRP_ROOT "/sub_caps_ctx"
+#define NR_WORKERS	8
+
+struct ctx {
+	struct sub_caps_ctx *parent;
+	struct sub_caps_ctx *child;
+	struct bpf_link *parent_link;
+	struct bpf_link *child_link;
+};
+
+static struct ctx test_ctx;

tools/testing/selftests/sched_ext/sub_caps_ctx.c line 48

Quoted 10 lines
tools/testing/selftests/sched_ext/sub_caps_ctx.c new file +10 -0
+
+static void write_file(const char *path, const char *buf)
+{
+	FILE *f = fopen(path, "w");
+
+	if (!f)
+		return;
+	fputs(buf, f);
+	fclose(f);
+}

[Severity: Low]
Could this reuse cg_find_unified_root(), cg_write(), cg_create(), and cg_destroy() from cgroup_util.h (as cgroup_nr_cpus.c does) instead of hardcoding /sys/fs/cgroup and ignoring errors in write_file()?

If cgroup2 is mounted elsewhere and /sys/fs/cgroup is a tmpfs or cgroup v1 mount, write_file() silently fails or writes a regular file while mkdir() and stat() in setup() still succeed, causing bpf_map__attach_struct_ops() for the child in run() to fail with -ENOENT instead of skipping the test.

tools/testing/selftests/sched_ext/sub_caps_ctx.c line 60

Quoted 12 lines
tools/testing/selftests/sched_ext/sub_caps_ctx.c new file +12 -0
+
+static enum scx_test_status setup(void **ctx)
+{
+	struct sub_caps_ctx *skel;
+	struct stat st;
+
+	if (!__COMPAT_struct_has_field("sched_ext_ops_cid", "sub_caps_updated"))
+		return SCX_TEST_SKIP;
+
+	/* a single cid is always the parent's rq, which scx_bpf_cidperf_set() accepts */
+	if (sysconf(_SC_NPROCESSORS_ONLN) < 2)
+		return SCX_TEST_SKIP;

[Severity: Low]
Should these two skip paths print a reason message explaining which prerequisite was missing before returning SCX_TEST_SKIP?

Quoted 6 lines
tools/testing/selftests/sched_ext/sub_caps_ctx.c new file +6 -0
+
+	write_file(CGRP_ROOT "/cgroup.subtree_control", "+cpu");
+	if (mkdir(CGRP_PATH, 0755) && errno != EEXIST) {
+		fprintf(stderr, "Failed to create %s (%s)\n", CGRP_PATH, strerror(errno));
+		return SCX_TEST_SKIP;
+	}

tools/testing/selftests/sched_ext/sub_caps_ctx.c line 76

Quoted 10 lines
tools/testing/selftests/sched_ext/sub_caps_ctx.c new file +10 -0
+	SCX_FAIL_IF(stat(CGRP_PATH, &st), "Failed to stat %s", CGRP_PATH);
+
+	skel = SCX_OPS_CID_OPEN(sub_caps_ctx_ops, sub_caps_ctx);
+	SCX_OPS_LOAD(skel, sub_caps_ctx_ops, sub_caps_ctx, uei);
+	test_ctx.parent = skel;
+
+	skel = SCX_OPS_CID_OPEN(sub_caps_ctx_ops, sub_caps_ctx);
+	skel->struct_ops.sub_caps_ctx_ops->sub_cgroup_id = st.st_ino;
+	SCX_OPS_LOAD(skel, sub_caps_ctx_ops, sub_caps_ctx, uei);
+	test_ctx.child = skel;

[Severity: Low]
Does setup() leak the CGRP_PATH directory if stat() or skeleton loading fails? The test runner does not invoke cleanup() when setup() fails or aborts via SCX_OPS_CID_OPEN() / SCX_OPS_LOAD(), leaving CGRP_PATH behind on the host cgroup filesystem.

[ ... ]

tools/testing/selftests/sched_ext/sub_caps_ctx.c line 114

Quoted 9 lines
tools/testing/selftests/sched_ext/sub_caps_ctx.c new file +9 -0
+	for (i = 0; i < NR_WORKERS; i++) {
+		pids[i] = fork();
+		SCX_FAIL_IF(pids[i] < 0, "Failed to fork");
+		if (!pids[i])
+			worker();
+	}
+	for (i = 0; i < NR_WORKERS; i++)
+		SCX_FAIL_IF(waitpid(pids[i], &status, 0) != pids[i] || status,
+			    "Worker %d failed", i);

[Severity: Low]
If fork() fails after spawning some workers, or waitpid() fails on one worker, does SCX_FAIL_IF() return without reaping the remaining children? Because the runner executes all tests in a single process and cleanup() does not wait on pids[], any remaining workers continue running into cleanup() and subsequent tests and are left as zombies.

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