xref: /linux/kernel/sched/ext/sub.c (revision 0dc90ce1be18ea6b18b545f4752de64cfc140ccd)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * BPF extensible scheduler class: Documentation/scheduler/sched-ext.rst
4  *
5  * Sub-scheduler hierarchy support.
6  *
7  * A sub-scheduler is an scx_sched attached to a cgroup subtree under another
8  * scx_sched. This file holds the sub-scheduler implementation: the scheduler
9  * tree walk, capability delegation, per-shard cap state and its sync, and the
10  * sub-scheduler enable/disable paths. The core dispatch/enqueue machinery it
11  * builds on lives in ext.c.
12  *
13  * Copyright (c) 2026 Meta Platforms, Inc. and affiliates.
14  * Copyright (c) 2026 Tejun Heo <tj@kernel.org>
15  */
16 #include <linux/rhashtable.h>
17 #include "internal.h"
18 #include "cid.h"
19 #include "arena.h"
20 #include "sub.h"
21 #include "inlines.h"
22 
23 #ifdef CONFIG_EXT_SUB_SCHED
24 
25 /*
26  * On while any sub-scheduler exists so that a root-only system doesn't pay for
27  * the sub-sched portions of hot paths. See scx_has_subs().
28  */
29 DEFINE_STATIC_KEY_FALSE(__scx_has_subs);
30 
31 /**
32  * scx_skip_subtree_pre - Skip @pos's subtree in a pre-order walk
33  * @pos: current position
34  * @root: walk root
35  *
36  * In a walk started by scx_next_descendant_pre(), continue past @pos's subtree:
37  * return @pos's next sibling, or the closest ancestor's next sibling, or NULL
38  * if @pos's subtree is the last under @root. Same locking rules.
39  */
40 struct scx_sched *scx_skip_subtree_pre(struct scx_sched *pos, struct scx_sched *root)
41 {
42 	struct scx_sched *next;
43 
44 	lockdep_assert(lockdep_is_held(&scx_enable_mutex) ||
45 		       lockdep_is_held(&scx_sched_lock) ||
46 		       rcu_read_lock_any_held());
47 
48 	while (pos != root) {
49 		next = list_next_or_null_rcu(&scx_parent(pos)->children, &pos->sibling,
50 					     struct scx_sched, sibling);
51 		if (next)
52 			return next;
53 		pos = scx_parent(pos);
54 	}
55 	return NULL;
56 }
57 
58 /**
59  * scx_next_descendant_pre - find the next descendant for pre-order walk
60  * @pos: the current position (%NULL to initiate traversal)
61  * @root: sched whose descendants to walk
62  *
63  * To be used by scx_for_each_descendant_pre(). Find the next descendant to
64  * visit for pre-order traversal of @root's descendants. @root is included in
65  * the iteration and the first node to be visited.
66  */
67 struct scx_sched *scx_next_descendant_pre(struct scx_sched *pos, struct scx_sched *root)
68 {
69 	struct scx_sched *next;
70 
71 	lockdep_assert(lockdep_is_held(&scx_enable_mutex) ||
72 		       lockdep_is_held(&scx_sched_lock) ||
73 		       rcu_read_lock_any_held());
74 
75 	/* if first iteration, visit @root */
76 	if (!pos)
77 		return root;
78 
79 	/* visit the first child if exists */
80 	next = list_first_or_null_rcu(&pos->children, struct scx_sched, sibling);
81 	if (next)
82 		return next;
83 
84 	/* no child, visit my or the closest ancestor's next sibling */
85 	return scx_skip_subtree_pre(pos, root);
86 }
87 
88 static struct scx_sched *scx_find_sub_sched(u64 cgroup_id)
89 {
90 	return rhashtable_lookup(&scx_sched_hash, &cgroup_id,
91 				 scx_sched_hash_params);
92 }
93 
94 void scx_set_task_sched(struct task_struct *p, struct scx_sched *sch)
95 {
96 	rcu_assign_pointer(p->scx.sched, sch);
97 }
98 
99 struct cgroup *sch_cgroup(struct scx_sched *sch)
100 {
101 	return sch->cgrp;
102 }
103 
104 /* for each descendant of @cgrp including self, set ->scx_sched to @sch */
105 void set_cgroup_sched(struct cgroup *cgrp, struct scx_sched *sch)
106 {
107 	struct cgroup *pos;
108 	struct cgroup_subsys_state *css;
109 
110 	cgroup_for_each_live_descendant_pre(pos, css, cgrp)
111 		rcu_assign_pointer(pos->scx_sched, sch);
112 }
113 
114 static void free_pshard(struct scx_pshard *pshard)
115 {
116 	struct scx_caps_updated *cu;
117 
118 	if (!pshard)
119 		return;
120 	cu = &pshard->caps_updated;
121 	if (cu->cmask_arena_out)
122 		scx_arena_free(pshard->sch, cu->cmask_arena_out,
123 			       struct_size_t(struct scx_cmask, bits,
124 					     SCX_CMASK_NR_WORDS(pshard->nr_cids)));
125 	kfree(pshard);
126 }
127 
128 void scx_free_pshards(struct scx_sched *sch)
129 {
130 	s32 si;
131 
132 	if (!sch->pshard)
133 		return;
134 	for (si = 0; si < sch->nr_pshards; si++)
135 		free_pshard(sch->pshard[si]);
136 	kfree(sch->pshard);
137 }
138 
139 static struct scx_pshard *alloc_pshard(struct scx_sched *sch, s32 shard_idx, s32 node)
140 {
141 	const struct scx_cid_shard *shard = &scx_cid_shard_ranges[shard_idx];
142 	size_t cmask_size = struct_size_t(struct scx_cmask, bits,
143 					  SCX_CMASK_NR_WORDS(shard->nr_cids));
144 	struct scx_pshard *pshard;
145 	struct scx_caps_updated *cu;
146 	s32 i;
147 
148 	pshard = kzalloc_node(sizeof(*pshard), GFP_KERNEL, node);
149 	if (!pshard)
150 		return NULL;
151 
152 	raw_spin_lock_init(&pshard->lock);
153 	pshard->sch = sch;
154 	pshard->base = shard->base_cid;
155 	pshard->nr_cids = shard->nr_cids;
156 
157 	for (i = 0; i < __SCX_NR_CAPS; i++)
158 		scx_cmask_init(&pshard->caps[i].cmask, shard->base_cid, shard->nr_cids);
159 
160 	cu = &pshard->caps_updated;
161 	raw_spin_lock_init(&cu->lock);
162 	INIT_LIST_HEAD(&cu->node_in_flight);
163 	__scx_cmask_init(&cu->cmask, shard->base_cid, shard->nr_cids, SCX_CID_SHARD_MAX_CPUS);
164 
165 	cu->cmask_arena_out = scx_arena_alloc(sch, cmask_size);
166 	if (!cu->cmask_arena_out) {
167 		free_pshard(pshard);
168 		return NULL;
169 	}
170 
171 	scx_cmask_init(cu->cmask_arena_out, shard->base_cid, shard->nr_cids);
172 
173 	return pshard;
174 }
175 
176 s32 scx_alloc_pshards(struct scx_sched *sch)
177 {
178 	struct scx_pshard **pshard;
179 	s32 si;
180 
181 	if (!sch->is_cid_type || !sch->arena_pool)
182 		return 0;
183 
184 	pshard = kzalloc_objs(pshard[0], scx_nr_cid_shards, GFP_KERNEL);
185 	if (!pshard)
186 		return -ENOMEM;
187 
188 	for (si = 0; si < scx_nr_cid_shards; si++) {
189 		pshard[si] = alloc_pshard(sch, si, scx_shard_node[si]);
190 		if (!pshard[si]) {
191 			while (--si >= 0)
192 				free_pshard(pshard[si]);
193 			kfree(pshard);
194 			return -ENOMEM;
195 		}
196 	}
197 
198 	sch->nr_pshards = scx_nr_cid_shards;
199 	/*
200 	 * Publish only after every entry is built so a reader observing
201 	 * @sch->pshard never sees a partially-filled array. Pair the store
202 	 * with a barrier and READ_ONCE() on the read side.
203 	 */
204 	smp_wmb();
205 	WRITE_ONCE(sch->pshard, pshard);
206 	return 0;
207 }
208 
209 /*
210  * Seed the root's caps fully. Root owns all cids on all caps at enable time.
211  * Children acquire caps via scx_bpf_sub_grant().
212  */
213 void scx_init_root_caps(struct scx_sched *sch)
214 {
215 	s32 si, i;
216 
217 	for (si = 0; si < sch->nr_pshards; si++) {
218 		struct scx_pshard *ps = sch->pshard[si];
219 
220 		for (i = 0; i < __SCX_NR_CAPS; i++)
221 			scx_cmask_fill(&ps->caps[i].cmask);
222 	}
223 }
224 
225 /**
226  * scx_local_or_reject_dsq - Pick the local or reject DSQ for an insert
227  * @sch: enqueuing sub-sched
228  * @rq: rq whose local DSQ @p targets
229  * @p: task being inserted
230  * @enq_flags: in/out, unhonored flags are cleared
231  *
232  * Return @rq's local DSQ if @sch holds the required caps on @rq's cid,
233  * otherwise @rq's reject DSQ after recording the reenq reason on @p.
234  *
235  * %SCX_ENQ_IMMED and %SCX_ENQ_PREEMPT are cleared when diverting to reject.
236  * %SCX_ENQ_PREEMPT is also cleared on a fallback migration-disabled admission.
237  *
238  * Bypass doesn't need special-casing as a bypassing sched's tasks are enqueued
239  * to and run by its nearest non-bypassing ancestor. If root is bypassing, it
240  * always holds all caps.
241  */
242 struct scx_dispatch_q *scx_local_or_reject_dsq(struct scx_sched *sch, struct rq *rq,
243 					       struct task_struct *p, u64 *enq_flags)
244 {
245 	if (!scx_has_subs())
246 		return &rq->scx.local_dsq;
247 
248 	s32 cid = __scx_cpu_to_cid(cpu_of(rq));
249 	struct scx_sched *asch = rq->scx.remote_activate_sch ?: sch;
250 	u64 needed = scx_caps_for_enq(*enq_flags);
251 	u64 missing;
252 
253 	/*
254 	 * On a remote activation the scheduling sched (@asch) differs from
255 	 * @p's owner (@sch). Check caps against the scheduling sched.
256 	 */
257 	if (*enq_flags & SCX_ENQ_PREEMPT)
258 		needed |= scx_caps_for_preempt(asch, rq);
259 	missing = scx_missing_caps(asch, cpu_of(rq), needed);
260 
261 	/* requirements met */
262 	if (likely(!missing))
263 		return &rq->scx.local_dsq;
264 
265 	/*
266 	 * The task must run on this CPU regardless of caps: the rq is draining
267 	 * offline (BPF scheduler bypassed), the task is migration-disabled, or a
268 	 * migration is pending. Admit despite the missing caps and count it.
269 	 * Refuse preemptions.
270 	 */
271 	if (unlikely(!scx_rq_online(rq) || is_migration_disabled(p) ||
272 		     p->migration_pending)) {
273 		__scx_add_event(sch, SCX_EV_SUB_FORCED_ADMIT, 1);
274 		*enq_flags &= ~SCX_ENQ_PREEMPT;
275 		return &rq->scx.local_dsq;
276 	}
277 
278 	p->scx.reenq_reason_caps = missing;
279 	p->scx.reenq_reason_cid = cid;
280 
281 	/*
282 	 * Only local DSQ can honor IMMED and dsq_inc_nr() WARNs on IMMED into
283 	 * others. Strip both the enq flag and the sticky task flag - the
284 	 * latter can carry in from an earlier admitted IMMED insert. Strip
285 	 * PREEMPT too.
286 	 */
287 	*enq_flags &= ~(SCX_ENQ_IMMED | SCX_ENQ_PREEMPT);
288 	p->scx.flags &= ~SCX_TASK_IMMED;
289 
290 	return &rq->scx.reject_dsq;
291 }
292 
293 /* @p lost the caps needed to stay on @rq's local DSQ? Record reason if so. */
294 bool scx_task_reenq_on_cap_revoke(struct rq *rq, struct task_struct *p)
295 {
296 	u64 missing;
297 
298 	/* migration-disabled tasks are admitted regardless of caps */
299 	if (is_migration_disabled(p))
300 		return false;
301 
302 	missing = scx_missing_caps(scx_task_sched(p), cpu_of(rq), scx_caps_for_task(p));
303 	if (likely(!missing))
304 		return false;
305 
306 	p->scx.reenq_reason_caps = missing;
307 	p->scx.reenq_reason_cid = __scx_cpu_to_cid(cpu_of(rq));
308 	return true;
309 }
310 
311 /*
312  * Drain @rq->scx.reject_dsq, reenqueueing each task so the BPF re-decides
313  * from p->scx.reenq_reason_*.
314  *
315  * A task can be re-rejected repeatedly, and there's no repeat limit here.
316  * Rejection can't happen for root, and sub-scheds can be safely ejected after
317  * triggering the stall watchdog.
318  */
319 void scx_reenq_reject(struct rq *rq)
320 {
321 	LIST_HEAD(tasks);
322 	struct task_struct *p, *n;
323 
324 	lockdep_assert_rq_held(rq);
325 
326 	if (!scx_has_subs() || list_empty(&rq->scx.reject_dsq.list))
327 		return;
328 
329 	/*
330 	 * Move to a private list so a task re-rejected by the
331 	 * scx_do_enqueue_task() below isn't revisited this round.
332 	 */
333 	list_for_each_entry_safe(p, n, &rq->scx.reject_dsq.list, scx.dsq_list.node) {
334 		/* migration_pending tasks should have bypassed to local DSQ */
335 		if (WARN_ON_ONCE(p->migration_pending))
336 			continue;
337 
338 		scx_dispatch_dequeue(rq, p);
339 
340 		if (WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK))
341 			p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
342 		p->scx.flags |= SCX_TASK_REENQ_CAP;
343 
344 		list_add_tail(&p->scx.dsq_list.node, &tasks);
345 	}
346 
347 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
348 		list_del_init(&p->scx.dsq_list.node);
349 
350 		scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
351 
352 		p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
353 	}
354 }
355 
356 /* record a caps change, see struct scx_caps_updated */
357 static void caps_updated_record(struct scx_pshard *ps, const struct scx_cmask *cids, u64 caps,
358 				struct list_head *to_deliver)
359 {
360 	struct scx_caps_updated *cu = &ps->caps_updated;
361 
362 	guard(raw_spinlock)(&cu->lock);
363 	scx_cmask_or(&cu->cmask, cids);
364 	cu->caps |= caps;
365 	if (list_empty(&cu->node_in_flight))
366 		list_add_tail(&cu->node_in_flight, to_deliver);
367 }
368 
369 /* deliver queued caps_updated callbacks, see struct scx_caps_updated */
370 static void caps_updated_deliver(struct list_head *to_deliver)
371 {
372 	struct scx_caps_updated *cu, *tmp;
373 
374 	list_for_each_entry_safe(cu, tmp, to_deliver, node_in_flight) {
375 		struct scx_pshard *ps = container_of(cu, struct scx_pshard, caps_updated);
376 		struct scx_sched *sch = ps->sch;
377 
378 		while (true) {
379 			u64 caps = 0;
380 
381 			/*
382 			 * During enable, has_op is set after ops.sub_attach(),
383 			 * so !has_op means the op is absent or the sched isn't
384 			 * live yet - e.g. caps grant from ops.sub_attach().
385 			 * Either way don't consume - leave for
386 			 * scx_sub_seed_caps() to deliver once live.
387 			 */
388 			scoped_guard (raw_spinlock, &cu->lock) {
389 				if (cu->caps && SCX_HAS_OP(sch, sub_caps_updated) &&
390 				    likely(!READ_ONCE(sch->aborting))) {
391 					struct scx_cmask_ref ref;
392 
393 					caps = cu->caps;
394 					scx_cmask_ref_init_kern(sch, cu->cmask_arena_out,
395 								ps->base, ps->nr_cids, &ref);
396 					scx_cmask_ref_copy(&ref, &cu->cmask);
397 					scx_cmask_clear(&cu->cmask);
398 					cu->caps = 0;
399 				} else {
400 					list_del_init(&cu->node_in_flight);
401 				}
402 			}
403 			if (!caps)
404 				break;
405 
406 			/* caps != 0 only when deliverable (has_op, above) */
407 			SCX_CALL_OP(sch, sub_caps_updated, NULL,
408 				    scx_kaddr_to_arena(sch, cu->cmask_arena_out),
409 				    caps);
410 		}
411 	}
412 }
413 
414 /*
415  * Deliver caps owed to @sch that couldn't be delivered earlier (e.g. a grant
416  * taken during its sub_attach(), before has_op was set). Called once @sch is
417  * enabled.
418  */
419 static void scx_sub_seed_caps(struct scx_sched *sch)
420 {
421 	LIST_HEAD(to_deliver);
422 	s32 si;
423 
424 	guard(irqsave)();
425 
426 	for (si = 0; si < sch->nr_pshards; si++) {
427 		struct scx_pshard *ps = sch->pshard[si];
428 		struct scx_caps_updated *cu = &ps->caps_updated;
429 
430 		scoped_guard (raw_spinlock, &cu->lock) {
431 			if (cu->caps && list_empty(&cu->node_in_flight))
432 				list_add_tail(&cu->node_in_flight, &to_deliver);
433 		}
434 	}
435 	caps_updated_deliver(&to_deliver);
436 }
437 
438 static u64 calc_effective_caps(struct scx_pshard *ps, s32 cid)
439 {
440 	u64 ecaps = 0;
441 	u32 cap_bit;
442 
443 	for (cap_bit = 0; cap_bit < __SCX_NR_CAPS; cap_bit++)
444 		if (scx_cmask_test(cid, &ps->caps[cap_bit].cmask))
445 			ecaps |= BIT_U64(cap_bit) | scx_caps_implied(BIT_U64(cap_bit));
446 	return ecaps;
447 }
448 
449 /**
450  * queue_sync_ecaps - Queue ecaps update for a (sch, cid) pair
451  * @sch: sched to update
452  * @cid: cid to update
453  *
454  * Queue an ecaps update for @sch's @cid and kick the cpu so that it syncs in
455  * balance_one().
456  */
457 static void queue_sync_ecaps(struct scx_sched *sch, s32 cid)
458 {
459 	s32 cpu = __scx_cid_to_cpu(cid);
460 	struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
461 
462 	/*
463 	 * Pairs with smp_mb() in scx_process_sync_ecaps(). Either the check
464 	 * below sees the node off the list and queues it, or the in-flight sync
465 	 * sees the caps[] update made before this call.
466 	 */
467 	smp_mb();
468 
469 	/* @cid's pshard->lock excludes concurrent queueing attempts */
470 	if (llist_on_list(&pcpu->ecaps_to_sync_node))
471 		return;
472 	if (llist_add(&pcpu->ecaps_to_sync_node, &cpu_rq(cpu)->scx.ecaps_to_sync))
473 		scx_kick_cpu(scx_root, cpu, 0);
474 }
475 
476 /* discard @rq's queued ecaps syncs */
477 static void discard_queued_syncs(struct rq *rq)
478 {
479 	struct llist_node *pos, *tmp;
480 
481 	lockdep_assert_rq_held(rq);
482 
483 	llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync))
484 		init_llist_node(pos);
485 }
486 
487 /**
488  * scx_process_sync_ecaps - Sync this cpu's ecaps to pshard->caps[]
489  * @rq: the cid's cpu rq
490  * @prev: @rq's previous task from the in-progress balance
491  *
492  * pshard->caps[] is the target configuration. pcpu->ecaps is the effective
493  * transposed copy owned by the cid's cpu and written only here under @rq's
494  * lock.
495  *
496  * A sched that newly gains baseline access here is owed an update_idle() so it
497  * learns the cid's idle state. Such a gain arms the per-rq
498  * %SCX_RQ_SUB_IDLE_RENOTIFY gate so the next idle pick delivers it.
499  */
500 void scx_process_sync_ecaps(struct rq *rq, struct task_struct *prev)
501 {
502 	s32 cpu = cpu_of(rq);
503 	s32 cid, shard;
504 	struct llist_node *batch, *pos, *tmp;
505 	u64 lost_all = 0;
506 
507 	lockdep_assert_rq_held(rq);
508 
509 	if (!scx_has_subs() || likely(llist_empty(&rq->scx.ecaps_to_sync)))
510 		return;
511 
512 	/*
513 	 * ecaps are zeroed while the cpu is inactive and must stay zero.
514 	 * Discard queued syncs instead of processing them - the
515 	 * scx_online_ecaps() reseed re-syncs every sched on activation.
516 	 * cpu_active() clears before the offline zeroing and sets before the
517 	 * reseed is queued, so this test can neither miss a racing sync nor
518 	 * eat the reseed.
519 	 */
520 	if (unlikely(!cpu_active(cpu))) {
521 		discard_queued_syncs(rq);
522 		return;
523 	}
524 
525 	/* @cid is valid here: the cpu is active with queued syncs */
526 	cid = __scx_cpu_to_cid(cpu);
527 	shard = scx_cid_to_shard[cid];
528 
529 	batch = llist_del_all(&rq->scx.ecaps_to_sync);
530 	llist_for_each_safe(pos, tmp, batch) {
531 		struct scx_sched_pcpu *pcpu =
532 			container_of(pos, struct scx_sched_pcpu, ecaps_to_sync_node);
533 		struct scx_pshard *ps = pcpu->sch->pshard[shard];
534 		u64 old, ecaps, lost, gained;
535 
536 		init_llist_node(pos);
537 
538 		/* pairs with smp_mb() in queue_sync_ecaps(), see there */
539 		smp_mb();
540 
541 		old = READ_ONCE(pcpu->ecaps);
542 		ecaps = calc_effective_caps(ps, cid);
543 		WRITE_ONCE(pcpu->ecaps, ecaps);
544 
545 		lost = old & ~ecaps;
546 		gained = ecaps & ~old;
547 		lost_all |= lost;
548 
549 		/*
550 		 * Tell the sched its effective caps on this cid changed. The
551 		 * invocation is equivalent to the dispatch path and may drop
552 		 * and re-acquire the rq lock temporarily while the rest of
553 		 * @batch is held privately, see scx_discard_ecaps_to_sync().
554 		 */
555 		if (ecaps != pcpu->reported_ecaps &&
556 		    SCX_HAS_OP(pcpu->sch, sub_ecaps_updated) &&
557 		    !scx_bypassing(pcpu->sch, cpu)) {
558 			struct scx_dsp_ctx *dspc = &pcpu->dsp_ctx;
559 
560 			dspc->rq = rq;
561 			/* stash @prev so nested dispatches can access it */
562 			rq->scx.sub_dispatch_prev = prev;
563 			SCX_CALL_OP(pcpu->sch, sub_ecaps_updated, rq, scx_cpu_arg(cpu),
564 				    pcpu->reported_ecaps, ecaps);
565 			rq->scx.sub_dispatch_prev = NULL;
566 			scx_flush_dispatch_buf(pcpu->sch, rq);
567 			pcpu->reported_ecaps = ecaps;
568 		}
569 
570 		/*
571 		 * Gaining baseline access owes an update_idle() so the sched
572 		 * learns the cpu's idle state. Arm the per-rq gate so the next
573 		 * idle pick flushes it. Losing access drops any pending notify.
574 		 */
575 		if (gained & SCX_CAP_BASE) {
576 			pcpu->idle_renotify = true;
577 			rq->scx.flags |= SCX_RQ_SUB_IDLE_RENOTIFY;
578 		} else if (lost & SCX_CAP_BASE) {
579 			pcpu->idle_renotify = false;
580 		}
581 	}
582 
583 	/*
584 	 * Losing a cap can strand already-queued tasks. Schedule a reenq scan
585 	 * to move the now-capless ones off the local DSQ. The scan tests
586 	 * against the effective caps and thus must come after the ecaps sync.
587 	 */
588 	if (lost_all & SCX_CAPS_REENQ_ON_LOSS)
589 		scx_schedule_reenq_local(rq, SCX_REENQ_CAP_REVOKE);
590 }
591 
592 /**
593  * scx_unbypass_replay_ecaps - Replay a bypass-suppressed ecaps notification
594  * @rq: rq of the cpu leaving bypass
595  * @sch: scheduler that just left bypass on @rq's cpu
596  *
597  * scx_process_sync_ecaps() consumes syncs while bypassing without delivering
598  * ops.sub_ecaps_updated(), leaving reported_ecaps stale. Nothing re-queues a
599  * sync when bypass lifts, so without a replay a cid that never changes again
600  * would never be notified. The attach-time initial grants are the acute case
601  * as they are consumed during the enable bypass window. Re-queue a sync for
602  * any undelivered delta so the next balance delivers it.
603  */
604 void scx_unbypass_replay_ecaps(struct rq *rq, struct scx_sched *sch)
605 {
606 	s32 cpu = cpu_of(rq);
607 	struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
608 	struct scx_pshard *ps;
609 	s32 cid;
610 
611 	lockdep_assert_rq_held(rq);
612 
613 	/* root holds every cap and never uses ecaps */
614 	if (!sch->level)
615 		return;
616 
617 	if (READ_ONCE(pcpu->ecaps) == pcpu->reported_ecaps)
618 		return;
619 
620 	cid = __scx_cpu_to_cid(cpu);
621 	ps = sch->pshard[scx_cid_to_shard[cid]];
622 
623 	guard(raw_spinlock)(&ps->lock);
624 	queue_sync_ecaps(sch, cid);
625 }
626 
627 /*
628  * A cpu came back. Re-seed each sub-sched's ecaps on the cpu's cid. The sync
629  * recomputes effective caps from the pshard and fires ops.sub_ecaps_updated()
630  * only on a real change since offline.
631  */
632 void scx_online_ecaps(struct rq *rq)
633 {
634 	s32 cid = __scx_cpu_to_cid(cpu_of(rq));
635 	s32 shard = scx_cid_to_shard[cid];
636 	struct scx_sched *pos;
637 
638 	guard(rq_lock_irqsave)(rq);
639 
640 	scx_for_each_descendant_pre(pos, scx_root) {
641 		struct scx_pshard *ps;
642 
643 		/* root holds every cap and never uses ecaps */
644 		if (pos == scx_root)
645 			continue;
646 
647 		ps = pos->pshard[shard];
648 		guard(raw_spinlock)(&ps->lock);
649 		queue_sync_ecaps(pos, cid);
650 	}
651 }
652 
653 /*
654  * A cpu is going down. Zero each sub-sched's in-effect ecaps so cap checks
655  * treat the cpu as capless while offline. Pending and late-queued syncs are
656  * discarded at consumption by scx_process_sync_ecaps() while the cpu is
657  * inactive. Leave reported_ecaps. Ownership is unchanged, so the
658  * scx_online_ecaps() reseed reports only a genuine delta. No callback fires
659  * here.
660  */
661 void scx_offline_ecaps(struct rq *rq)
662 {
663 	s32 cpu = cpu_of(rq);
664 	struct scx_sched *pos;
665 
666 	guard(rq_lock_irqsave)(rq);
667 
668 	scx_for_each_descendant_pre(pos, scx_root) {
669 		/* root holds every cap and never uses ecaps */
670 		if (pos == scx_root)
671 			continue;
672 
673 		WRITE_ONCE(per_cpu_ptr(pos->pcpu, cpu)->ecaps, 0);
674 	}
675 }
676 
677 /*
678  * @pcpu's sched was unhashed before the grace period, so nothing re-queues its
679  * sync node. Remove the node from @rq's pending list so the pcpu can be freed.
680  */
681 void scx_discard_ecaps_to_sync(s32 cpu, struct scx_sched_pcpu *pcpu)
682 {
683 	struct rq *rq = cpu_rq(cpu);
684 	struct llist_node *head = NULL, *tail = NULL;
685 	struct llist_node *pos, *tmp;
686 
687 	/*
688 	 * llist can't unlink a single node. Take all queued nodes, drop @pcpu's
689 	 * and resplice the rest. Nodes in the taken batch read as on-list
690 	 * throughout, so queue_sync_ecaps() stays correct.
691 	 */
692 	if (llist_on_list(&pcpu->ecaps_to_sync_node)) {
693 		scoped_guard (rq_lock_irqsave, rq) {
694 			llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) {
695 				if (pos == &pcpu->ecaps_to_sync_node) {
696 					init_llist_node(pos);
697 				} else {
698 					pos->next = head;
699 					head = pos;
700 					if (!tail)
701 						tail = pos;
702 				}
703 			}
704 			if (head)
705 				llist_add_batch(head, tail, &rq->scx.ecaps_to_sync);
706 		}
707 	}
708 
709 	/*
710 	 * An in-flight scx_process_sync_ecaps() batch may still hold the node
711 	 * privately across dispatch-induced rq unlocks, reading as on-list.
712 	 *
713 	 * Because a bypassing sched gets no op call, init_llist_node() and all
714 	 * @pcpu accesses share one contiguous lock hold, off-list under the rq
715 	 * lock means @pcpu won't be accessed again.
716 	 */
717 	while (true) {
718 		scoped_guard (rq_lock_irqsave, rq) {
719 			if (!llist_on_list(&pcpu->ecaps_to_sync_node))
720 				return;
721 		}
722 		cpu_relax();
723 	}
724 }
725 
726 /**
727  * scx_discard_stale_ecaps_syncs - Discard ecaps syncs from earlier schedulers
728  *
729  * To be called during root enable before the scheduler goes live. An earlier
730  * root's sub-sched may not have gone through its RCU free path yet (e.g. a
731  * still-open link fd defers it) and can leave queued ecaps syncs behind.
732  * Processing them would decode the dead sched's pshards with the current cid
733  * layout. Discard them instead. The backing scx_sched_pcpu's are still
734  * allocated as the free path removes ecaps_to_sync_node before freeing.
735  */
736 void scx_discard_stale_ecaps_syncs(void)
737 {
738 	s32 cpu;
739 
740 	for_each_possible_cpu(cpu) {
741 		struct rq *rq = cpu_rq(cpu);
742 
743 		guard(rq_lock_irqsave)(rq);
744 		discard_queued_syncs(rq);
745 	}
746 }
747 
748 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq);
749 
750 void drain_descendants(struct scx_sched *sch)
751 {
752 	/*
753 	 * Child scheds that finished the critical part of disabling will take
754 	 * themselves off @sch->children. Wait for it to drain. As propagation
755 	 * is recursive, empty @sch->children means that all proper descendant
756 	 * scheds reached unlinking stage.
757 	 */
758 	wait_event(scx_unlink_waitq, list_empty(&sch->children));
759 }
760 
761 /**
762  * scx_rehome_task - Move a task to a sched it has been initialized for
763  * @to: sched taking over @p, @p's init on it already complete
764  * @p: task to re-home
765  *
766  * Exit @p from its current sched and switch it over to @to, overriding the
767  * state to %SCX_TASK_READY to account for the already completed init. A task
768  * on a non-ext class, possible under an %SCX_OPS_SWITCH_PARTIAL root, stays
769  * %READY and is enabled by switching_to_scx() if it switches over.
770  */
771 static void scx_rehome_task(struct scx_sched *to, struct task_struct *p)
772 {
773 	lockdep_assert_held(&p->pi_lock);
774 	lockdep_assert_rq_held(task_rq(p));
775 
776 	scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
777 		scx_disable_and_exit_task(scx_task_sched(p), p);
778 		scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
779 		scx_set_task_state(p, SCX_TASK_INIT);
780 		scx_set_task_sched(p, to);
781 		scx_set_task_state(p, SCX_TASK_READY);
782 		if (p->sched_class == &ext_sched_class)
783 			scx_enable_task(to, p);
784 	}
785 }
786 
787 /**
788  * scx_punt_task - Hand a task to a failed sched without initialization
789  * @to: failed and bypassed sched taking custody of @p
790  * @p: task to punt
791  *
792  * Take @p off its current sched and put it on @to at %SCX_TASK_NONE. @to is
793  * dying and its teardown will re-home @p properly.
794  *
795  * Used when @to must take over @p but failed to initialize it. Bypass keeps
796  * scheduling decisions away from @to but @p can still trigger its task ops,
797  * which may confuse the BPF side. @to is dying anyway. The exit paths skip
798  * %NONE tasks (see __scx_disable_and_exit_task() and switched_from_scx()).
799  */
800 static void scx_punt_task(struct scx_sched *to, struct task_struct *p)
801 {
802 	lockdep_assert_held(&p->pi_lock);
803 	lockdep_assert_rq_held(task_rq(p));
804 	WARN_ON_ONCE(!READ_ONCE(to->bypass_depth));
805 
806 	scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
807 		scx_disable_and_exit_task(scx_task_sched(p), p);
808 		scx_set_task_sched(p, to);
809 	}
810 }
811 
812 static void scx_fail_parent(struct scx_sched *sch,
813 			    struct task_struct *failed, s32 fail_code)
814 {
815 	struct scx_sched *parent = scx_parent(sch);
816 	struct scx_task_iter sti;
817 	struct task_struct *p;
818 
819 	scx_error(parent, "ops.init_task() failed (%d) for %s[%d] while disabling a sub-scheduler",
820 		  fail_code, failed->comm, failed->pid);
821 
822 	/*
823 	 * Once $parent is bypassed, tasks can be punted into it. This may
824 	 * cause downstream failures on the BPF side but $parent is dying
825 	 * anyway.
826 	 */
827 	scx_bypass(parent, true);
828 
829 	scx_task_iter_start(&sti, sch->cgrp);
830 	while ((p = scx_task_iter_next_locked(&sti))) {
831 		if (scx_task_on_sched(parent, p))
832 			continue;
833 
834 		scx_punt_task(parent, p);
835 	}
836 	scx_task_iter_stop(&sti);
837 }
838 
839 void scx_sub_disable(struct scx_sched *sch)
840 {
841 	struct scx_sched *parent = scx_parent(sch);
842 	struct scx_task_iter sti;
843 	struct task_struct *p;
844 	int ret;
845 
846 	/*
847 	 * Guarantee forward progress and wait for descendants to be disabled.
848 	 * To limit disruptions, $parent is not bypassed. Tasks are fully
849 	 * prepped and then inserted back into $parent.
850 	 */
851 	scx_bypass(sch, true);
852 	drain_descendants(sch);
853 
854 	/*
855 	 * Here, every runnable task is guaranteed to make forward progress and
856 	 * we can safely use blocking synchronization constructs. Actually
857 	 * disable ops.
858 	 */
859 	mutex_lock(&scx_enable_mutex);
860 	percpu_down_write(&scx_fork_rwsem);
861 	scx_cgroup_lock();
862 
863 	/*
864 	 * An enable that failed before scx_link_sched() never owned a cgroup or
865 	 * task and won't be waited on by an ancestor's drain_descendants().
866 	 * Nothing to reparent and walking the tasks can misbehave as the task
867 	 * ownership invariant (either owned by self or parent) does not hold.
868 	 */
869 	if (list_empty(&sch->sibling))
870 		goto dump;
871 
872 	set_cgroup_sched(sch_cgroup(sch), parent);
873 
874 	scx_task_iter_start(&sti, sch->cgrp);
875 	while ((p = scx_task_iter_next_locked(&sti))) {
876 		struct rq *rq;
877 		struct rq_flags rf;
878 
879 		/* filter out duplicate visits */
880 		if (scx_task_on_sched(parent, p))
881 			continue;
882 
883 		/*
884 		 * By the time control reaches here, all linked descendant
885 		 * schedulers should have been disabled.
886 		 */
887 		WARN_ON_ONCE(!scx_task_on_sched(sch, p));
888 
889 		/*
890 		 * @p is pinned by the iter: css_task_iter_next() takes a
891 		 * reference and holds it until the next iter_next() call, so
892 		 * @p->usage is guaranteed > 0.
893 		 */
894 		get_task_struct(p);
895 
896 		scx_task_iter_unlock(&sti);
897 
898 		/*
899 		 * $p is READY or ENABLED on @sch. Initialize for $parent,
900 		 * disable and exit from @sch, and then switch over to $parent.
901 		 *
902 		 * If a task fails to initialize for $parent, the only available
903 		 * action is disabling $parent too. While this allows disabling
904 		 * of a child sched to cause the parent scheduler to fail, the
905 		 * failure can only originate from ops.init_task() of the
906 		 * parent. A child can't directly affect the parent through its
907 		 * own failures.
908 		 */
909 		ret = __scx_init_task(parent, p, false);
910 		if (ret) {
911 			scx_fail_parent(sch, p, ret);
912 			put_task_struct(p);
913 			break;
914 		}
915 
916 		rq = task_rq_lock(p, &rf);
917 
918 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
919 			/*
920 			 * sched_ext_dead() raced us between __scx_init_task()
921 			 * and this rq lock and ran exit_task() on @sch (the
922 			 * sched @p was on at that point), not on $parent.
923 			 * $parent's just-completed init is owed an exit_task()
924 			 * and we issue it here.
925 			 */
926 			scx_sub_init_cancel_task(parent, p);
927 			task_rq_unlock(rq, p, &rf);
928 			put_task_struct(p);
929 			continue;
930 		}
931 
932 		scx_rehome_task(parent, p);
933 
934 		task_rq_unlock(rq, p, &rf);
935 		put_task_struct(p);
936 	}
937 	scx_task_iter_stop(&sti);
938 
939 dump:
940 	scx_disable_dump(sch);
941 
942 	scx_cgroup_unlock();
943 	percpu_up_write(&scx_fork_rwsem);
944 
945 	/*
946 	 * All tasks are moved off of @sch but there may still be on-going
947 	 * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use
948 	 * the expedited version as ancestors may be waiting in bypass mode.
949 	 * Also, tell the parent that there is no need to keep running bypass
950 	 * DSQs for us.
951 	 */
952 	synchronize_rcu_expedited();
953 	scx_disable_bypass_dsp(sch);
954 
955 	scx_unlink_sched(sch);
956 
957 	mutex_unlock(&scx_enable_mutex);
958 
959 	/*
960 	 * @sch is now unlinked from the parent's children list. Notify and call
961 	 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called
962 	 * after unlinking and releasing all locks. See scx_claim_exit().
963 	 */
964 	wake_up_all(&scx_unlink_waitq);
965 
966 	if (parent->ops.sub_detach && sch->sub_attached) {
967 		struct scx_sub_detach_args sub_detach_args = {
968 			.ops = &sch->ops,
969 			.cgroup_path = sch->cgrp_path,
970 		};
971 		SCX_CALL_OP(parent, sub_detach, NULL,
972 			    &sub_detach_args);
973 	}
974 
975 	scx_log_sched_disable(sch);
976 
977 	if (sch->ops.exit)
978 		SCX_CALL_OP(sch, exit, NULL, sch->exit_info);
979 
980 	/*
981 	 * @sch's non-ops programs such as timers and tracers can fire after
982 	 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from
983 	 * resolving to @sch and drain in-flight resolvers.
984 	 */
985 	WRITE_ONCE(sch->dead, true);
986 	synchronize_rcu();
987 
988 	if (sch->sub_kset)
989 		kobject_del(&sch->sub_kset->kobj);
990 	/* not added if enable failed before scx_sched_sysfs_add() */
991 	if (sch->kobj.state_in_sysfs)
992 		kobject_del(&sch->kobj);
993 }
994 
995 /* verify that a scheduler can be attached to @cgrp and return the parent */
996 static struct scx_sched *find_parent_sched(struct cgroup *cgrp)
997 {
998 	struct scx_sched *parent = cgrp->scx_sched;
999 	struct scx_sched *pos;
1000 
1001 	lockdep_assert_held(&scx_sched_lock);
1002 
1003 	/* can't attach twice to the same cgroup */
1004 	if (parent->cgrp == cgrp)
1005 		return ERR_PTR(-EBUSY);
1006 
1007 	/* does $parent allow sub-scheds? */
1008 	if (!parent->ops.sub_attach)
1009 		return ERR_PTR(-EOPNOTSUPP);
1010 
1011 	/* can't insert between $parent and its exiting children */
1012 	list_for_each_entry(pos, &parent->children, sibling)
1013 		if (cgroup_is_descendant(pos->cgrp, cgrp))
1014 			return ERR_PTR(-EBUSY);
1015 
1016 	return parent;
1017 }
1018 
1019 static bool assert_task_ready_or_enabled(struct task_struct *p)
1020 {
1021 	u32 state = scx_get_task_state(p);
1022 
1023 	switch (state) {
1024 	case SCX_TASK_READY:
1025 	case SCX_TASK_ENABLED:
1026 		return true;
1027 	default:
1028 		WARN_ONCE(true, "sched_ext: Invalid task state %d for %s[%d] during enabling sub sched",
1029 			  state, p->comm, p->pid);
1030 		return false;
1031 	}
1032 }
1033 
1034 void scx_sub_enable_workfn(struct kthread_work *work)
1035 {
1036 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
1037 	struct sched_ext_ops *ops = cmd->ops;
1038 	struct cgroup *cgrp;
1039 	struct scx_sched *parent, *sch;
1040 	struct scx_task_iter sti;
1041 	struct task_struct *p;
1042 	s32 i, ret;
1043 
1044 	mutex_lock(&scx_enable_mutex);
1045 
1046 	if (!scx_enabled()) {
1047 		ret = -ENODEV;
1048 		goto out_unlock;
1049 	}
1050 
1051 	/* See scx_root_enable_workfn() for the @ops->priv check. */
1052 	if (rcu_access_pointer(ops->priv)) {
1053 		ret = -EBUSY;
1054 		goto out_unlock;
1055 	}
1056 
1057 	cgrp = cgroup_get_from_id(ops->sub_cgroup_id);
1058 	if (IS_ERR(cgrp)) {
1059 		ret = PTR_ERR(cgrp);
1060 		goto out_unlock;
1061 	}
1062 
1063 	raw_spin_lock_irq(&scx_sched_lock);
1064 	parent = find_parent_sched(cgrp);
1065 	if (IS_ERR(parent)) {
1066 		raw_spin_unlock_irq(&scx_sched_lock);
1067 		ret = PTR_ERR(parent);
1068 		goto out_put_cgrp;
1069 	}
1070 	kobject_get(&parent->kobj);
1071 	raw_spin_unlock_irq(&scx_sched_lock);
1072 
1073 	/*
1074 	 * Flip the hot-path gates before ops->priv is published - the sub's
1075 	 * programs can e.g. kick cpus from that point on. The matching dec is
1076 	 * at the end of scx_sched_free_rcu_work().
1077 	 */
1078 	static_branch_inc(&__scx_has_subs);
1079 
1080 	/* scx_alloc_and_add_sched() consumes @cgrp whether it succeeds or not */
1081 	sch = scx_alloc_and_add_sched(cmd, cgrp, parent);
1082 	kobject_put(&parent->kobj);
1083 	if (IS_ERR(sch)) {
1084 		static_branch_dec(&__scx_has_subs);
1085 		ret = PTR_ERR(sch);
1086 		goto out_unlock;
1087 	}
1088 
1089 	/*
1090 	 * Validate before scx_link_sched() publishes @sch, so an invalid sub
1091 	 * never becomes visible with an unallocated pshard.
1092 	 */
1093 	ret = scx_validate_ops(sch, ops);
1094 	if (ret)
1095 		goto err_disable;
1096 
1097 	/*
1098 	 * Allocate pshard[] before scx_link_sched() publishes @sch into the
1099 	 * parent's RCU children list. A concurrent revoke walking the tree
1100 	 * would otherwise dereference sch->pshard[si] while it's still NULL.
1101 	 * Unlike the root path, the cid shard layout is stable at this point.
1102 	 *
1103 	 * scx_alloc_pshards() skips allocation when @sch's arena pool isn't
1104 	 * initialized, so scx_arena_pool_init() must run first.
1105 	 */
1106 	ret = scx_arena_pool_init(sch);
1107 	if (ret)
1108 		goto err_disable;
1109 
1110 	ret = scx_alloc_pshards(sch);
1111 	if (ret)
1112 		goto err_disable;
1113 
1114 	ret = scx_link_sched(sch);
1115 	if (ret)
1116 		goto err_disable;
1117 
1118 	ret = scx_sched_sysfs_add(sch);
1119 	if (ret)
1120 		goto err_disable;
1121 
1122 	if (sch->level >= SCX_SUB_MAX_DEPTH) {
1123 		scx_error(sch, "max nesting depth %d violated",
1124 			  SCX_SUB_MAX_DEPTH);
1125 		goto err_disable;
1126 	}
1127 
1128 	if (sch->ops.init) {
1129 		ret = SCX_CALL_OP_RET(sch, init, NULL);
1130 		if (ret) {
1131 			ret = scx_ops_sanitize_err(sch, "init", ret);
1132 			scx_error(sch, "ops.init() failed (%d)", ret);
1133 			goto err_disable;
1134 		}
1135 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
1136 	}
1137 
1138 	ret = scx_set_cmask_scratch_alloc(sch);
1139 	if (ret)
1140 		goto err_disable;
1141 
1142 	struct scx_sub_attach_args sub_attach_args = {
1143 		.ops = &sch->ops,
1144 		.cgroup_path = sch->cgrp_path,
1145 	};
1146 
1147 	ret = SCX_CALL_OP_RET(parent, sub_attach, NULL,
1148 			      &sub_attach_args);
1149 	if (ret) {
1150 		ret = scx_ops_sanitize_err(sch, "sub_attach", ret);
1151 		scx_error(sch, "parent rejected (%d)", ret);
1152 		goto err_disable;
1153 	}
1154 	sch->sub_attached = true;
1155 
1156 	scx_bypass(sch, true);
1157 
1158 	for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++)
1159 		if (((void (**)(void))ops)[i])
1160 			set_bit(i, sch->has_op);
1161 
1162 	percpu_down_write(&scx_fork_rwsem);
1163 	scx_cgroup_lock();
1164 
1165 	/*
1166 	 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see
1167 	 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down.
1168 	 */
1169 	set_cgroup_sched(sch_cgroup(sch), sch);
1170 	if (!(cgrp->self.flags & CSS_ONLINE)) {
1171 		scx_error(sch, "cgroup is not online");
1172 		goto err_unlock_and_disable;
1173 	}
1174 
1175 	/*
1176 	 * Initialize tasks for the new child $sch without exiting them for
1177 	 * $parent so that the tasks can always be reverted back to $parent
1178 	 * sched on child init failure.
1179 	 */
1180 	WARN_ON_ONCE(scx_enabling_sub_sched);
1181 	scx_enabling_sub_sched = sch;
1182 
1183 	scx_task_iter_start(&sti, sch->cgrp);
1184 	while ((p = scx_task_iter_next_locked(&sti))) {
1185 		struct rq *rq;
1186 		struct rq_flags rf;
1187 
1188 		/*
1189 		 * Task iteration may visit the same task twice when racing
1190 		 * against exiting. Use %SCX_TASK_SUB_INIT to mark tasks which
1191 		 * finished __scx_init_task() and skip if set.
1192 		 *
1193 		 * A task may exit and get freed between __scx_init_task()
1194 		 * completion and scx_enable_task(). In such cases,
1195 		 * scx_disable_and_exit_task() must exit the task for both the
1196 		 * parent and child scheds.
1197 		 */
1198 		if (p->scx.flags & SCX_TASK_SUB_INIT)
1199 			continue;
1200 
1201 		/* @p is pinned by the iter; see scx_sub_disable() */
1202 		get_task_struct(p);
1203 
1204 		if (!assert_task_ready_or_enabled(p)) {
1205 			ret = -EINVAL;
1206 			goto abort;
1207 		}
1208 
1209 		scx_task_iter_unlock(&sti);
1210 
1211 		/*
1212 		 * As $p is still on $parent, it can't be transitioned to INIT.
1213 		 * Let's worry about task state later. Use __scx_init_task().
1214 		 */
1215 		ret = __scx_init_task(sch, p, false);
1216 		if (ret)
1217 			goto abort;
1218 
1219 		rq = task_rq_lock(p, &rf);
1220 
1221 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
1222 			/*
1223 			 * sched_ext_dead() raced us between __scx_init_task()
1224 			 * and this rq lock and ran exit_task() on $parent (the
1225 			 * sched @p was on at that point), not on @sch. @sch's
1226 			 * just-completed init is owed an exit_task() and we
1227 			 * issue it here.
1228 			 */
1229 			scx_sub_init_cancel_task(sch, p);
1230 			task_rq_unlock(rq, p, &rf);
1231 			put_task_struct(p);
1232 			continue;
1233 		}
1234 
1235 		p->scx.flags |= SCX_TASK_SUB_INIT;
1236 		task_rq_unlock(rq, p, &rf);
1237 
1238 		put_task_struct(p);
1239 	}
1240 	scx_task_iter_stop(&sti);
1241 
1242 	/*
1243 	 * All tasks are prepped. Disable/exit tasks for $parent and enable for
1244 	 * the new @sch.
1245 	 */
1246 	scx_task_iter_start(&sti, sch->cgrp);
1247 	while ((p = scx_task_iter_next_locked(&sti))) {
1248 		/*
1249 		 * Use clearing of %SCX_TASK_SUB_INIT to detect and skip
1250 		 * duplicate iterations.
1251 		 */
1252 		if (!(p->scx.flags & SCX_TASK_SUB_INIT))
1253 			continue;
1254 
1255 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
1256 			/*
1257 			 * $p must be either READY or ENABLED. If ENABLED,
1258 			 * __scx_disabled_and_exit_task() first disables and
1259 			 * makes it READY. However, after exiting $p, it will
1260 			 * leave $p as READY.
1261 			 */
1262 			assert_task_ready_or_enabled(p);
1263 			__scx_disable_and_exit_task(parent, p);
1264 
1265 			/*
1266 			 * $p is now only initialized for @sch and READY, which
1267 			 * is what we want. Assign it to @sch and, if it's on
1268 			 * the ext class, enable. A non-ext task, possible under
1269 			 * an %SCX_OPS_SWITCH_PARTIAL root, stays READY and is
1270 			 * enabled by switching_to_scx() if it switches over.
1271 			 */
1272 			scx_set_task_sched(p, sch);
1273 			if (p->sched_class == &ext_sched_class)
1274 				scx_enable_task(sch, p);
1275 
1276 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
1277 		}
1278 	}
1279 	scx_task_iter_stop(&sti);
1280 
1281 	scx_enabling_sub_sched = NULL;
1282 
1283 	scx_cgroup_unlock();
1284 	percpu_up_write(&scx_fork_rwsem);
1285 
1286 	scx_bypass(sch, false);
1287 
1288 	/* @sch is enabled; deliver any caps owed since its sub_attach() */
1289 	scx_sub_seed_caps(sch);
1290 
1291 	pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name);
1292 	kobject_uevent(&sch->kobj, KOBJ_ADD);
1293 	ret = 0;
1294 	goto out_unlock;
1295 
1296 out_put_cgrp:
1297 	cgroup_put(cgrp);
1298 out_unlock:
1299 	mutex_unlock(&scx_enable_mutex);
1300 	cmd->ret = ret;
1301 	return;
1302 
1303 abort:
1304 	put_task_struct(p);
1305 	scx_task_iter_stop(&sti);
1306 
1307 	/*
1308 	 * Undo __scx_init_task() for tasks we marked. scx_enable_task() never
1309 	 * ran for @sch on them, so calling scx_disable_task() here would invoke
1310 	 * ops.disable() without a matching ops.enable(). scx_enabling_sub_sched
1311 	 * must stay set until SUB_INIT is cleared from every marked task -
1312 	 * scx_disable_and_exit_task() reads it when a task exits concurrently.
1313 	 */
1314 	scx_task_iter_start(&sti, sch->cgrp);
1315 	while ((p = scx_task_iter_next_locked(&sti))) {
1316 		if (p->scx.flags & SCX_TASK_SUB_INIT) {
1317 			scx_sub_init_cancel_task(sch, p);
1318 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
1319 		}
1320 	}
1321 	scx_task_iter_stop(&sti);
1322 	scx_enabling_sub_sched = NULL;
1323 err_unlock_and_disable:
1324 	/* we'll soon enter disable path, keep bypass on */
1325 	scx_cgroup_unlock();
1326 	percpu_up_write(&scx_fork_rwsem);
1327 err_disable:
1328 	mutex_unlock(&scx_enable_mutex);
1329 	/*
1330 	 * Some enable failures only return an errno (e.g. -ENOMEM from an
1331 	 * allocation) without calling scx_error(). Record it so
1332 	 * scx_flush_disable_work() runs the disable and ops.exit() fires.
1333 	 */
1334 	scx_error(sch, "scx_sub_enable() failed (%d)", ret);
1335 	scx_flush_disable_work(sch);
1336 	cmd->ret = 0;
1337 }
1338 
1339 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb,
1340 				      unsigned long action, void *data)
1341 {
1342 	struct cgroup *cgrp = data;
1343 	struct cgroup *parent = cgroup_parent(cgrp);
1344 
1345 	if (!cgroup_on_dfl(cgrp))
1346 		return NOTIFY_OK;
1347 
1348 	switch (action) {
1349 	case CGROUP_LIFETIME_ONLINE:
1350 		/* inherit ->scx_sched from $parent */
1351 		if (parent)
1352 			rcu_assign_pointer(cgrp->scx_sched, parent->scx_sched);
1353 		break;
1354 	case CGROUP_LIFETIME_OFFLINE:
1355 		/* if there is a sched attached, shoot it down */
1356 		if (cgrp->scx_sched && cgrp->scx_sched->cgrp == cgrp)
1357 			scx_exit(cgrp->scx_sched, SCX_EXIT_UNREG_KERN,
1358 				 SCX_ECODE_RSN_CGROUP_OFFLINE,
1359 				 "cgroup %llu going offline", cgroup_id(cgrp));
1360 		break;
1361 	}
1362 
1363 	return NOTIFY_OK;
1364 }
1365 
1366 static struct notifier_block scx_cgroup_lifetime_nb = {
1367 	.notifier_call = scx_cgroup_lifetime_notify,
1368 };
1369 
1370 static s32 __init scx_cgroup_lifetime_notifier_init(void)
1371 {
1372 	return blocking_notifier_chain_register(&cgroup_lifetime_notifier,
1373 						&scx_cgroup_lifetime_nb);
1374 }
1375 core_initcall(scx_cgroup_lifetime_notifier_init);
1376 
1377 static void scx_pstack_recursion(struct bpf_prog *prog, const char *op)
1378 {
1379 	struct scx_sched *sch;
1380 
1381 	guard(rcu)();
1382 	sch = scx_prog_sched(prog->aux);
1383 	if (unlikely(!sch))
1384 		return;
1385 
1386 	scx_error(sch, "%s recursion detected", op);
1387 }
1388 
1389 void scx_pstack_recursion_on_dispatch(struct bpf_prog *prog)
1390 {
1391 	scx_pstack_recursion(prog, "dispatch");
1392 }
1393 
1394 void scx_pstack_recursion_on_caps_updated(struct bpf_prog *prog)
1395 {
1396 	scx_pstack_recursion(prog, "sub_caps_updated");
1397 }
1398 
1399 __bpf_kfunc_start_defs();
1400 
1401 /**
1402  * scx_bpf_sub_dispatch - Trigger dispatching on a child scheduler
1403  * @cgroup_id: cgroup ID of the child scheduler to dispatch
1404  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1405  *
1406  * Allows a parent scheduler to trigger dispatching on one of its direct
1407  * child schedulers. The child scheduler runs its dispatch operation to
1408  * move tasks from dispatch queues to the local runqueue.
1409  *
1410  * Returns: true on success, false if cgroup_id is invalid, not a direct
1411  * child, or caller lacks dispatch permission.
1412  */
1413 __bpf_kfunc bool scx_bpf_sub_dispatch(u64 cgroup_id, const struct bpf_prog_aux *aux)
1414 {
1415 	struct rq *this_rq = this_rq();
1416 	struct scx_sched *parent, *child;
1417 
1418 	guard(rcu)();
1419 	parent = scx_prog_sched(aux);
1420 	if (unlikely(!parent))
1421 		return false;
1422 
1423 	child = scx_find_sub_sched(cgroup_id);
1424 
1425 	if (unlikely(!child))
1426 		return false;
1427 
1428 	if (unlikely(scx_parent(child) != parent)) {
1429 		scx_error(parent, "trying to dispatch a distant sub-sched on cgroup %llu",
1430 			  cgroup_id);
1431 		return false;
1432 	}
1433 
1434 	/*
1435 	 * Skip a child that does not effectively hold the base cap on this cpu:
1436 	 * its inserts would only be rejected. ecaps are synced at the top of
1437 	 * balance_one() before dispatch, so this reflects the in-effect state.
1438 	 */
1439 	if (scx_missing_caps(child, cpu_of(this_rq), SCX_CAP_BASE))
1440 		return false;
1441 
1442 	return scx_dispatch_sched(child, this_rq, this_rq->scx.sub_dispatch_prev,
1443 				  true);
1444 }
1445 
1446 /* Validate common inputs. On success, *parent_out and *child_out are set. */
1447 static s32 sub_cap_preamble(u64 cgroup_id, u64 caps, const struct bpf_prog_aux *aux,
1448 			    struct scx_sched **parent_out, struct scx_sched **child_out)
1449 {
1450 	struct scx_sched *parent, *child;
1451 
1452 	parent = scx_prog_sched(aux);
1453 	if (unlikely(!parent))
1454 		return -ENODEV;
1455 
1456 	if (!scx_is_cid_type()) {
1457 		scx_error(parent, "sub-cap kfuncs require a cid-form scheduler");
1458 		return -EOPNOTSUPP;
1459 	}
1460 
1461 	child = scx_find_sub_sched(cgroup_id);
1462 	if (unlikely(!child))
1463 		return -ENODEV;
1464 
1465 	if (unlikely(scx_parent(child) != parent)) {
1466 		scx_error(parent, "%s: sub-%llu is not a direct child",
1467 			  parent->cgrp_path, cgroup_id);
1468 		return -EINVAL;
1469 	}
1470 
1471 	if (unlikely(caps & ~__SCX_CAP_ALL)) {
1472 		scx_error(parent, "invalid caps 0x%llx", caps);
1473 		return -EINVAL;
1474 	}
1475 
1476 	*parent_out = parent;
1477 	*child_out = child;
1478 	return 0;
1479 }
1480 
1481 /**
1482  * scx_bpf_sub_grant - Grant @caps on @cmask__ign's cids to a direct child
1483  * @cgroup_id: cgroup id of the direct child sub-sched
1484  * @caps: bitmask of SCX_CAP_* to grant
1485  * @cmask__ign: cid cmask to grant @caps on (arena pointer)
1486  * @denied_out__ign: optional arena cmask accumulating refused cids
1487  * @aux: implicit BPF argument
1488  *
1489  * A cid in @cmask__ign is granted to the child only if the parent holds every
1490  * requested cap on it. Refused cids are OR'd into @denied_out__ign when
1491  * provided. Refusals outside @denied_out__ign's range are not recorded.
1492  *
1493  * All-or-nothing keeps the caller-visible result binary per cid, so
1494  * @denied_out__ign is one mask to interpret rather than a per-cap matrix.
1495  *
1496  * Return 0 on full success, -EPERM if any cid was refused, or a negative
1497  * errno on other failures.
1498  */
1499 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps,
1500 				  const struct scx_cmask *cmask__ign,
1501 				  struct scx_cmask *denied_out__ign,
1502 				  const struct bpf_prog_aux *aux)
1503 {
1504 	struct scx_cmask_ref ref, denied_ref;
1505 	struct scx_sched *parent, *child;
1506 	bool any_denied = false;
1507 	LIST_HEAD(to_deliver);
1508 	s32 si, ret;
1509 
1510 	guard(irqsave)();
1511 
1512 	ret = sub_cap_preamble(cgroup_id, caps, aux, &parent, &child);
1513 	if (ret)
1514 		return ret;
1515 
1516 	ret = scx_cmask_ref_init(parent, cmask__ign, &ref);
1517 	if (ret) {
1518 		scx_error(parent, "invalid cmask (%d)", ret);
1519 		return ret;
1520 	}
1521 
1522 	if (denied_out__ign) {
1523 		ret = scx_cmask_ref_init(parent, denied_out__ign, &denied_ref);
1524 		if (ret) {
1525 			scx_error(parent, "invalid denied_out (%d)", ret);
1526 			return ret;
1527 		}
1528 	}
1529 
1530 	/* apply the grant one shard at a time */
1531 	for (si = ref.shard_first; si < ref.shard_end; si++) {
1532 		SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS);
1533 		struct scx_pshard *pps = parent->pshard[si];
1534 		struct scx_pshard *cps = child->pshard[si];
1535 		u64 granted_caps = 0;
1536 		u32 cap_bit;
1537 
1538 		scx_cmask_ref_shard(&ref, si, slice);
1539 		if (scx_cmask_empty(slice))
1540 			continue;
1541 
1542 		SCX_CMASK_DEFINE_SHARD(granted_cids, slice->base, slice->nr_cids);
1543 		SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids);
1544 		SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids);
1545 
1546 		scx_cmask_copy(granted_cids, slice);
1547 
1548 		scoped_guard (raw_spinlock, &pps->lock) {
1549 			guard(raw_spinlock_nested)(&cps->lock);
1550 
1551 			/*
1552 			 * Narrow granted_cids to cids the parent holds every
1553 			 * requested cap on. All-or-nothing per cid.
1554 			 */
1555 			scx_for_each_cap_bit(cap_bit, caps)
1556 				scx_cmask_and(granted_cids, &pps->caps[cap_bit].cmask);
1557 
1558 			/*
1559 			 * For each requested cap, fold the newly-set cids into
1560 			 * the child and accumulate the delta.
1561 			 */
1562 			scx_for_each_cap_bit(cap_bit, caps) {
1563 				struct scx_cmask *ccm = &cps->caps[cap_bit].cmask;
1564 
1565 				scx_cmask_copy(delta, granted_cids);
1566 				scx_cmask_andnot(delta, ccm);
1567 				if (scx_cmask_empty(delta))
1568 					continue;
1569 
1570 				scx_cmask_or(ccm, delta);
1571 				scx_cmask_or(changed_cids, delta);
1572 				granted_caps |= BIT_U64(cap_bit);
1573 			}
1574 
1575 			if (granted_caps) {
1576 				s32 cid;
1577 
1578 				caps_updated_record(cps, changed_cids, granted_caps,
1579 						    &to_deliver);
1580 				/*
1581 				 * The sync arms an update_idle() re-notify if
1582 				 * the cid gains baseline access, so the holder
1583 				 * learns of an already-idle cid.
1584 				 */
1585 				scx_cmask_for_each_cid(cid, changed_cids)
1586 					queue_sync_ecaps(child, cid);
1587 			}
1588 		}
1589 
1590 		/* record cids that didn't make it through into @denied_out */
1591 		if (!scx_cmask_subset(slice, granted_cids)) {
1592 			any_denied = true;
1593 			if (denied_out__ign) {
1594 				SCX_CMASK_DEFINE_SHARD(denied, slice->base, slice->nr_cids);
1595 
1596 				scx_cmask_copy(denied, slice);
1597 				scx_cmask_andnot(denied, granted_cids);
1598 				scx_cmask_ref_or(&denied_ref, denied);
1599 			}
1600 		}
1601 	}
1602 
1603 	caps_updated_deliver(&to_deliver);
1604 
1605 	return any_denied ? -EPERM : 0;
1606 }
1607 
1608 /**
1609  * scx_bpf_sub_revoke - Revoke @caps on @cmask__ign's cids from @child
1610  * @cgroup_id: cgroup id of the direct child sub-sched
1611  * @caps: bitmask of SCX_CAP_* to revoke
1612  * @cmask__ign: cid cmask to revoke @caps on (arena pointer)
1613  * @aux: implicit BPF argument
1614  *
1615  * Clear @caps bits on @cmask__ign from the child named by @cgroup_id and all
1616  * its descendants. The origin parent's pshard lock is held across the subtree
1617  * walk so a concurrent grant from the origin parent observes the revoked
1618  * state.
1619  */
1620 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps,
1621 				    const struct scx_cmask *cmask__ign,
1622 				    const struct bpf_prog_aux *aux)
1623 {
1624 	struct scx_cmask_ref ref;
1625 	struct scx_sched *parent, *child, *pos;
1626 	LIST_HEAD(to_deliver);
1627 	s32 si, ret;
1628 
1629 	guard(irqsave)();
1630 
1631 	if (sub_cap_preamble(cgroup_id, caps, aux, &parent, &child))
1632 		return;
1633 
1634 	ret = scx_cmask_ref_init(parent, cmask__ign, &ref);
1635 	if (ret) {
1636 		scx_error(parent, "invalid cmask (%d)", ret);
1637 		return;
1638 	}
1639 
1640 	/* per-shard, walk child's subtree and clear @caps */
1641 	for (si = ref.shard_first; si < ref.shard_end; si++) {
1642 		SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS);
1643 
1644 		scx_cmask_ref_shard(&ref, si, slice);
1645 		if (scx_cmask_empty(slice))
1646 			continue;
1647 
1648 		/*
1649 		 * Pre-order with subtree skip: a descendant that cleared
1650 		 * nothing means no descendant of it can hold @caps on these
1651 		 * cids either.
1652 		 */
1653 		guard(raw_spinlock)(&parent->pshard[si]->lock);
1654 		pos = scx_next_descendant_pre(NULL, child);
1655 		while (pos) {
1656 			struct scx_pshard *ps = pos->pshard[si];
1657 			SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids);
1658 			SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids);
1659 			u64 revoked_caps = 0;
1660 			u32 cap_bit;
1661 
1662 			scoped_guard (raw_spinlock_nested, &ps->lock) {
1663 				/*
1664 				 * For each cap, clear lost cids and accumulate
1665 				 * the per-cap diff for notification.
1666 				 */
1667 				scx_for_each_cap_bit(cap_bit, caps) {
1668 					struct scx_cmask *cm = &ps->caps[cap_bit].cmask;
1669 
1670 					scx_cmask_copy(delta, cm);
1671 					scx_cmask_and(delta, slice);
1672 					if (scx_cmask_empty(delta))
1673 						continue;
1674 
1675 					scx_cmask_andnot(cm, delta);
1676 					scx_cmask_or(changed_cids, delta);
1677 					revoked_caps |= BIT_U64(cap_bit);
1678 				}
1679 
1680 				if (revoked_caps) {
1681 					s32 cid;
1682 
1683 					caps_updated_record(ps, changed_cids, revoked_caps,
1684 							    &to_deliver);
1685 					scx_cmask_for_each_cid(cid, changed_cids)
1686 						queue_sync_ecaps(pos, cid);
1687 				}
1688 			}
1689 
1690 			if (revoked_caps)
1691 				pos = scx_next_descendant_pre(pos, child);
1692 			else
1693 				pos = scx_skip_subtree_pre(pos, child);
1694 		}
1695 	}
1696 
1697 	caps_updated_deliver(&to_deliver);
1698 }
1699 
1700 /**
1701  * scx_bpf_sub_caps - Read self's or a direct child's cap cmasks
1702  * @cgroup_id: 0 for self, or a direct child's cgroup id
1703  * @caps: one or more SCX_CAP_* bits
1704  * @out__ign: arena cmask to receive the union of @caps within its range
1705  * @aux: implicit BPF argument
1706  *
1707  * Read the cap cmasks granted on each cid for self (@cgroup_id 0) or a direct
1708  * child - the literal granted set. A sched can read only itself or a direct
1709  * child.
1710  *
1711  * Return 0, -ENODEV if @cgroup_id names no direct child, or -EINVAL on bad
1712  * inputs.
1713  */
1714 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__ign,
1715 				 const struct bpf_prog_aux *aux)
1716 {
1717 	struct scx_cmask_ref ref;
1718 	struct scx_sched *sch, *target;
1719 	struct scx_pshard **pshard;
1720 	s32 si, ret;
1721 
1722 	guard(irqsave)();
1723 
1724 	sch = scx_prog_sched(aux);
1725 	if (unlikely(!sch))
1726 		return -ENODEV;
1727 
1728 	if (!scx_is_cid_type()) {
1729 		scx_error(sch, "sub-cap kfuncs require a cid-form scheduler");
1730 		return -EOPNOTSUPP;
1731 	}
1732 
1733 	if (unlikely(caps & ~__SCX_CAP_ALL)) {
1734 		scx_error(sch, "invalid caps 0x%llx", caps);
1735 		return -EINVAL;
1736 	}
1737 
1738 	/* @cgroup_id 0 reads self, otherwise a direct child */
1739 	if (cgroup_id) {
1740 		target = scx_find_sub_sched(cgroup_id);
1741 		if (unlikely(!target))
1742 			return -ENODEV;
1743 		if (unlikely(scx_parent(target) != sch)) {
1744 			scx_error(sch, "%s: sub-%llu is not a direct child",
1745 				  sch->cgrp_path, cgroup_id);
1746 			return -EINVAL;
1747 		}
1748 	} else {
1749 		target = sch;
1750 	}
1751 
1752 	/*
1753 	 * The target's caps storage may not be set up yet (e.g. a self-read
1754 	 * during ops.init_cids()). Pairs with the publish in
1755 	 * scx_alloc_pshards(): a non-NULL pshard has every element set.
1756 	 */
1757 	pshard = READ_ONCE(target->pshard);
1758 	if (unlikely(!pshard)) {
1759 		scx_error(sch, "scx_bpf_sub_caps() called before caps storage is initialized");
1760 		return -ENODEV;
1761 	}
1762 
1763 	ret = scx_cmask_ref_init(sch, out__ign, &ref);
1764 	if (ret) {
1765 		scx_error(sch, "invalid out (%d)", ret);
1766 		return ret;
1767 	}
1768 
1769 	for (si = ref.shard_first; si < ref.shard_end; si++) {
1770 		const struct scx_cid_shard *shard = &scx_cid_shard_ranges[si];
1771 		SCX_CMASK_DEFINE_SHARD(local_out, shard->base_cid, shard->nr_cids);
1772 		u32 cap_bit;
1773 
1774 		scx_for_each_cap_bit(cap_bit, caps)
1775 			scx_cmask_or(local_out, &pshard[si]->caps[cap_bit].cmask);
1776 		scx_cmask_ref_copy(&ref, local_out);
1777 	}
1778 	return 0;
1779 }
1780 
1781 /**
1782  * scx_bpf_sub_kill_bstr - Kill a direct child sub-scheduler
1783  * @cgroup_id: cgroup id of the direct child to kill
1784  * @fmt: reason message format string
1785  * @data: format string parameters packaged using ___bpf_fill() macro
1786  * @data__sz: @data len, must end in '__sz' for the verifier
1787  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1788  *
1789  * Evict a direct child sub-scheduler, disabling it with the supplied reason.
1790  * The child and its subtree are torn down asynchronously through the usual
1791  * disable path.
1792  *
1793  * Unlike scx_bpf_exit(), no exit code is taken: the child is a separate
1794  * scheduler with its own exit-code semantics, so a code chosen by the parent
1795  * would have no defined meaning. The reason string carries the intent.
1796  *
1797  * Return 0 on success or -ENODEV if @cgroup_id names no sub-scheduler, which
1798  * can race with the child detaching on its own and so is not a scheduler error.
1799  * Naming a sched that exists but is not a direct child aborts the parent.
1800  */
1801 __printf(2, 0)
1802 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt,
1803 				      unsigned long long *data, u32 data__sz,
1804 				      const struct bpf_prog_aux *aux)
1805 {
1806 	struct scx_sched *parent, *child;
1807 	s32 ret;
1808 
1809 	guard(rcu)();
1810 
1811 	parent = scx_prog_sched(aux);
1812 	if (unlikely(!parent))
1813 		return -ENODEV;
1814 
1815 	if (!scx_is_cid_type()) {
1816 		scx_error(parent, "sub-cap kfuncs require a cid-form scheduler");
1817 		return -EOPNOTSUPP;
1818 	}
1819 
1820 	child = scx_find_sub_sched(cgroup_id);
1821 	if (unlikely(!child))
1822 		return -ENODEV;
1823 
1824 	if (unlikely(scx_parent(child) != parent)) {
1825 		scx_error(parent, "%s: sub-%llu is not a direct child",
1826 			  parent->cgrp_path, cgroup_id);
1827 		return -EINVAL;
1828 	}
1829 
1830 	guard(raw_spinlock_irqsave)(&scx_exit_bstr_buf_lock);
1831 	ret = scx_bstr_format(parent, &scx_exit_bstr_buf, fmt, data, data__sz);
1832 	if (ret < 0)
1833 		return ret;
1834 	scx_exit(child, SCX_EXIT_PARENT_KILL, 0, "%s", scx_exit_bstr_buf.line);
1835 	return 0;
1836 }
1837 
1838 __bpf_kfunc_end_defs();
1839 
1840 #endif	/* CONFIG_EXT_SUB_SCHED */
1841