xref: /linux/kernel/sched/ext/sub.c (revision 5d7f3375cd574fc83f0cd30839b21455c0e79ae2)
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  * On while a loaded sched implements ops.sub_cid_sched_updated(), see
33  * scx_ops_cid_sched_updated_enable().
34  */
35 static DEFINE_STATIC_KEY_FALSE(__scx_ops_cid_sched_updated_enabled);
36 static s32 scx_nr_ops_cid_sched_updated;	/* such scheds, under scx_enable_mutex */
37 
38 /* latched at root enable before any rescue runs */
39 static s32 scx_rescue_bw_1024;
40 static s64 scx_rescue_quantum_ns;
41 static s64 scx_rescue_sat_delta_ns;
42 static unsigned long scx_rescue_decay_halflife;
43 static unsigned long scx_rescue_overload_after;
44 
45 /**
46  * scx_skip_subtree_pre - Skip @pos's subtree in a pre-order walk
47  * @pos: current position
48  * @root: walk root
49  *
50  * In a walk started by scx_next_descendant_pre(), continue past @pos's subtree:
51  * return @pos's next sibling, or the closest ancestor's next sibling, or NULL
52  * if @pos's subtree is the last under @root. Same locking rules.
53  */
54 struct scx_sched *scx_skip_subtree_pre(struct scx_sched *pos, struct scx_sched *root)
55 {
56 	struct scx_sched *next;
57 
58 	lockdep_assert(lockdep_is_held(&scx_enable_mutex) ||
59 		       lockdep_is_held(&scx_sched_lock) ||
60 		       rcu_read_lock_any_held());
61 
62 	while (pos != root) {
63 		next = list_next_or_null_rcu(&scx_parent(pos)->children, &pos->sibling,
64 					     struct scx_sched, sibling);
65 		if (next)
66 			return next;
67 		pos = scx_parent(pos);
68 	}
69 	return NULL;
70 }
71 
72 /**
73  * scx_next_descendant_pre - find the next descendant for pre-order walk
74  * @pos: the current position (%NULL to initiate traversal)
75  * @root: sched whose descendants to walk
76  *
77  * To be used by scx_for_each_descendant_pre(). Find the next descendant to
78  * visit for pre-order traversal of @root's descendants. @root is included in
79  * the iteration and the first node to be visited.
80  */
81 struct scx_sched *scx_next_descendant_pre(struct scx_sched *pos, struct scx_sched *root)
82 {
83 	struct scx_sched *next;
84 
85 	lockdep_assert(lockdep_is_held(&scx_enable_mutex) ||
86 		       lockdep_is_held(&scx_sched_lock) ||
87 		       rcu_read_lock_any_held());
88 
89 	/* if first iteration, visit @root */
90 	if (!pos)
91 		return root;
92 
93 	/* visit the first child if exists */
94 	next = list_first_or_null_rcu(&pos->children, struct scx_sched, sibling);
95 	if (next)
96 		return next;
97 
98 	/* no child, visit my or the closest ancestor's next sibling */
99 	return scx_skip_subtree_pre(pos, root);
100 }
101 
102 /**
103  * scx_cid_sched_id_from - Resolve what @from sees when @sch runs on a cid
104  * @sch: sched whose task runs there, %NULL for none
105  * @from: sched asking
106  *
107  * Return %SCX_CID_SCHED_NONE when @sch is %NULL or outside @from's subtree,
108  * %SCX_CID_SCHED_SELF for @from itself, or else the cgroup id of the direct
109  * child of @from on the way down to @sch.
110  */
111 static u64 scx_cid_sched_id_from(struct scx_sched *sch, struct scx_sched *from)
112 {
113 	if (!sch || !scx_is_descendant(sch, from))
114 		return SCX_CID_SCHED_NONE;
115 	if (sch == from)
116 		return SCX_CID_SCHED_SELF;
117 	return sch->ancestors[from->level + 1]->ops.sub_cgroup_id;
118 }
119 
120 /* notify @from of what it now sees running on @rq's cid */
121 static void scx_cid_notify_sched_updated(struct rq *rq, struct scx_sched *sch,
122 					 struct scx_sched *from)
123 {
124 	if (SCX_HAS_OP(from, sub_cid_sched_updated))
125 		SCX_CALL_OP(from, sub_cid_sched_updated, rq, __scx_cpu_to_cid(cpu_of(rq)),
126 			    scx_cid_sched_id_from(sch, from));
127 }
128 
129 /**
130  * scx_cid_sched_update - Update rq->scx.sched and notify the scheds affected
131  * @rq: rq whose running session opens or closes
132  * @sch: sched starting a session, %NULL to close the open one
133  *
134  * Every sched whose scx_cid_sched_id_from() value changes is notified of the
135  * new one. Above the deepest common ancestor of the two scheds, both map to the
136  * same child, so the walk stops there. With root R, children A and B, and A's
137  * child A1, a switch from an A1 task to a B task reports:
138  *
139  *         R        R:  A -> B
140  *        / \
141  *       A   B      A:  A1 -> NONE      B: NONE -> SELF
142  *       |
143  *       A1         A1: SELF -> NONE
144  *
145  * When the task on one side is not an ext task, there is no common ancestor and
146  * only the other side is walked.
147  */
148 void scx_cid_sched_update(struct rq *rq, struct scx_sched *sch)
149 {
150 	struct scx_sched *prev = rq->scx.sched;
151 	s32 level, common = -1;
152 
153 	lockdep_assert_rq_held(rq);
154 
155 	if (!static_branch_unlikely(&__scx_ops_cid_sched_updated_enabled) || prev == sch)
156 		return;
157 
158 	rq->scx.sched = sch;
159 
160 	if (prev && sch) {
161 		for (level = min(prev->level, sch->level); level >= 0; level--)
162 			if (prev->ancestors[level] == sch->ancestors[level])
163 				break;
164 		common = level;
165 		scx_cid_notify_sched_updated(rq, sch, prev->ancestors[common]);
166 	}
167 	if (prev)
168 		for (level = common + 1; level <= prev->level; level++)
169 			scx_cid_notify_sched_updated(rq, sch, prev->ancestors[level]);
170 	if (sch)
171 		for (level = common + 1; level <= sch->level; level++)
172 			scx_cid_notify_sched_updated(rq, sch, sch->ancestors[level]);
173 }
174 
175 /**
176  * scx_ops_cid_sched_updated_enable - Maintain rq->scx.sched if @sch has the op
177  * @sch: sched being enabled, its has_op filled in
178  *
179  * rq->scx.sched is maintained only while a loaded sched implements
180  * ops.sub_cid_sched_updated(), so that everyone else pays one static branch per
181  * session open or close. The first such sched turns the key on and then
182  * initializes every rq from the task running there, in that order so that no
183  * session change in between goes unrecorded. While the key is off every
184  * rq->scx.sched is NULL, see scx_ops_cid_sched_updated_disable().
185  */
186 void scx_ops_cid_sched_updated_enable(struct scx_sched *sch)
187 {
188 	s32 cpu;
189 
190 	lockdep_assert_held(&scx_enable_mutex);
191 
192 	if (!SCX_HAS_OP(sch, sub_cid_sched_updated) || scx_nr_ops_cid_sched_updated++)
193 		return;
194 
195 	static_branch_enable(&__scx_ops_cid_sched_updated_enabled);
196 
197 	for_each_possible_cpu(cpu) {
198 		struct rq *rq = cpu_rq(cpu);
199 		struct task_struct *p;
200 
201 		guard(rq_lock_irqsave)(rq);
202 		p = rq->donor;
203 		if (p->sched_class == &ext_sched_class &&
204 		    (p->scx.flags & SCX_TASK_RUN_TRACKED))
205 			rq->scx.sched = scx_task_sched(p);
206 	}
207 }
208 
209 /**
210  * scx_ops_cid_sched_updated_disable - Stop maintaining rq->scx.sched for @sch
211  * @sch: sched being disabled, its tasks all gone
212  *
213  * Close the session on every rq that still points at @sch, before ops.exit(),
214  * so that no sched is notified of @sch once it is gone. The last sched with the
215  * op turns the key off first and clears every rq, so while the key is off every
216  * rq->scx.sched is NULL. A sched whose enable failed before its has_op fill was
217  * never counted, so has_op gates the decrement.
218  */
219 void scx_ops_cid_sched_updated_disable(struct scx_sched *sch)
220 {
221 	bool last;
222 	s32 cpu;
223 
224 	lockdep_assert_held(&scx_enable_mutex);
225 
226 	last = SCX_HAS_OP(sch, sub_cid_sched_updated) && !--scx_nr_ops_cid_sched_updated;
227 	if (last)
228 		static_branch_disable(&__scx_ops_cid_sched_updated_enabled);
229 
230 	/*
231 	 * Re-homing restarts a running task's session under its new sched. A
232 	 * task that blocked while its cpu's dispatch had the rq lock dropped is
233 	 * put and set next again without a restart, so rq->scx.sched keeps @sch
234 	 * until the pick completes:
235 	 *
236 	 *   cpu 0, __schedule()                 cpu 1, scx_sub_disable(@sch)
237 	 *   T of @sch blocks, stops running
238 	 *   dispatch drops the rq lock
239 	 *                                       re-home T, nothing to restart
240 	 *                                       this sweep
241 	 *   pick N, N's session opens
242 	 *
243 	 * Closing the session here reports NONE to @sch and its ancestors now
244 	 * and lets the pick report N's sched from NONE instead of from @sch.
245 	 */
246 	for_each_possible_cpu(cpu) {
247 		struct rq *rq = cpu_rq(cpu);
248 
249 		guard(rq_lock_irqsave)(rq);
250 		if (rq->scx.sched == sch)
251 			scx_cid_sched_update(rq, NULL);
252 		if (last)
253 			rq->scx.sched = NULL;
254 	}
255 }
256 
257 static struct scx_sched *scx_find_sub_sched(u64 cgroup_id)
258 {
259 	return rhashtable_lookup(&scx_sched_hash, &cgroup_id,
260 				 scx_sched_hash_params);
261 }
262 
263 void scx_set_task_sched(struct task_struct *p, struct scx_sched *sch)
264 {
265 	rcu_assign_pointer(p->scx.sched, sch);
266 }
267 
268 struct cgroup *sch_cgroup(struct scx_sched *sch)
269 {
270 	return sch->cgrp;
271 }
272 
273 /* for each descendant of @cgrp including self, set ->scx_sched to @sch */
274 void set_cgroup_sched(struct cgroup *cgrp, struct scx_sched *sch)
275 {
276 	struct cgroup *pos;
277 	struct cgroup_subsys_state *css;
278 
279 	cgroup_for_each_live_descendant_pre(pos, css, cgrp)
280 		rcu_assign_pointer(pos->scx_sched, sch);
281 }
282 
283 static void free_pshard(struct scx_pshard *pshard)
284 {
285 	struct scx_caps_updated *cu;
286 
287 	if (!pshard)
288 		return;
289 	cu = &pshard->caps_updated;
290 	if (cu->cmask_arena_out)
291 		scx_arena_free(pshard->sch, cu->cmask_arena_out,
292 			       struct_size_t(struct scx_cmask, bits,
293 					     SCX_CMASK_NR_WORDS(pshard->nr_cids)));
294 	kfree(pshard);
295 }
296 
297 void scx_free_pshards(struct scx_sched *sch)
298 {
299 	s32 si;
300 
301 	if (!sch->pshard)
302 		return;
303 	for (si = 0; si < sch->nr_pshards; si++)
304 		free_pshard(sch->pshard[si]);
305 	kfree(sch->pshard);
306 }
307 
308 static struct scx_pshard *alloc_pshard(struct scx_sched *sch, s32 shard_idx, s32 node)
309 {
310 	const struct scx_cid_shard *shard =
311 		&rcu_dereference_protected(scx_cid_shard_ranges,
312 					   lockdep_is_held(&scx_enable_mutex))[shard_idx];
313 	size_t cmask_size = struct_size_t(struct scx_cmask, bits,
314 					  SCX_CMASK_NR_WORDS(shard->nr_cids));
315 	struct scx_pshard *pshard;
316 	struct scx_caps_updated *cu;
317 	s32 i;
318 
319 	pshard = kzalloc_node(sizeof(*pshard), GFP_KERNEL, node);
320 	if (!pshard)
321 		return NULL;
322 
323 	raw_spin_lock_init(&pshard->lock);
324 	pshard->sch = sch;
325 	pshard->base = shard->base_cid;
326 	pshard->nr_cids = shard->nr_cids;
327 
328 	for (i = 0; i < __SCX_NR_CAPS; i++)
329 		scx_cmask_init(&pshard->caps[i].cmask, shard->base_cid, shard->nr_cids);
330 
331 	cu = &pshard->caps_updated;
332 	raw_spin_lock_init(&cu->lock);
333 	INIT_LIST_HEAD(&cu->node_in_flight);
334 	__scx_cmask_init(&cu->cmask, shard->base_cid, shard->nr_cids, SCX_CID_SHARD_MAX_CPUS);
335 
336 	cu->cmask_arena_out = scx_arena_alloc(sch, cmask_size);
337 	if (!cu->cmask_arena_out) {
338 		free_pshard(pshard);
339 		return NULL;
340 	}
341 
342 	scx_cmask_init(cu->cmask_arena_out, shard->base_cid, shard->nr_cids);
343 
344 	return pshard;
345 }
346 
347 s32 scx_alloc_pshards(struct scx_sched *sch)
348 {
349 	struct scx_pshard **pshard;
350 	s32 *shard_node;
351 	s32 si;
352 
353 	if (!sch->is_cid_type || !sch->arena_pool)
354 		return 0;
355 
356 	shard_node = rcu_dereference_protected(scx_shard_node,
357 					       lockdep_is_held(&scx_enable_mutex));
358 
359 	pshard = kzalloc_objs(pshard[0], scx_nr_cid_shards);
360 	if (!pshard)
361 		return -ENOMEM;
362 
363 	for (si = 0; si < scx_nr_cid_shards; si++) {
364 		pshard[si] = alloc_pshard(sch, si, shard_node[si]);
365 		if (!pshard[si]) {
366 			while (--si >= 0)
367 				free_pshard(pshard[si]);
368 			kfree(pshard);
369 			return -ENOMEM;
370 		}
371 	}
372 
373 	sch->nr_pshards = scx_nr_cid_shards;
374 	/*
375 	 * Publish only after every entry is built so a reader observing
376 	 * @sch->pshard never sees a partially-filled array or unpublished cid
377 	 * tables. Pair the store with a barrier and an acquire load on the
378 	 * read side.
379 	 */
380 	smp_wmb();
381 	WRITE_ONCE(sch->pshard, pshard);
382 	return 0;
383 }
384 
385 /*
386  * Seed the root's caps fully. Root owns all cids on all caps at enable time.
387  * Children acquire caps via scx_bpf_sub_grant().
388  */
389 void scx_init_root_caps(struct scx_sched *sch)
390 {
391 	s32 si, i;
392 
393 	for (si = 0; si < sch->nr_pshards; si++) {
394 		struct scx_pshard *ps = sch->pshard[si];
395 
396 		for (i = 0; i < __SCX_NR_CAPS; i++)
397 			scx_cmask_fill(&ps->caps[i].cmask);
398 	}
399 }
400 
401 /* unserved remainder of @rq's rescuee's admitted slice, 0 once fully served */
402 static s64 scx_rescue_slice_remaining(struct rq *rq)
403 {
404 	s64 served = rq->scx.rescue.curr->se.sum_exec_runtime - rq->scx.rescue.exec_snap;
405 
406 	return max(rq->scx.rescue.slice - served, 0);
407 }
408 
409 /*
410  * Decay @pcpu's rescue usage average in place, halving per the knob-derived
411  * halflife, see scx_rescue_set_knobs(). The timestamp advances only by whole
412  * halflives.
413  */
414 static u64 scx_rescue_decay_avg(struct scx_sched_pcpu *pcpu)
415 {
416 	unsigned long halflife = scx_rescue_decay_halflife;
417 	u64 n = div_u64(get_jiffies_64() - pcpu->rescue_avg_at, halflife);
418 
419 	if (n) {
420 		pcpu->rescue_avg = n < 64 ? pcpu->rescue_avg >> n : 0;
421 		pcpu->rescue_avg_at += n * halflife;
422 	}
423 	return pcpu->rescue_avg;
424 }
425 
426 /**
427  * scx_rescue_charge - Charge the rescuee's runtime
428  * @rq: rq the rescuee is running on
429  * @delta_exec: runtime being charged
430  *
431  * Also ends the rescue once the admitted slice has been served in full. Ending
432  * on served time rather than slice exhaustion bounds both the rescue and the
433  * charging when a scheduler extends the rescuee's slice.
434  */
435 void scx_rescue_charge(struct rq *rq, s64 delta_exec)
436 {
437 	struct scx_sched_pcpu *pcpu;
438 
439 	lockdep_assert_rq_held(rq);
440 
441 	/*
442 	 * A rescue slice is bounded by one quantum and tick-driven expiry can
443 	 * overshoot by up to a tick. Clamp to avoid wild over-charges on VMs.
444 	 */
445 	delta_exec = min_t(s64, delta_exec, scx_rescue_quantum_ns + TICK_NSEC);
446 
447 	rq->scx.rescue.budget -= delta_exec;
448 
449 	/* per-cpu usage average feeds the overload victim pick */
450 	pcpu = per_cpu_ptr(scx_task_sched(rq->scx.rescue.curr)->pcpu,
451 			   cpu_of(rq));
452 	pcpu->rescue_avg = scx_rescue_decay_avg(pcpu) + delta_exec;
453 
454 	if (!scx_rescue_slice_remaining(rq))
455 		scx_task_slice_ended(rq, rq->scx.rescue.curr);
456 }
457 
458 /**
459  * scx_rescue_end - End the rescue execution on @rq
460  * @rq: rq of interest
461  *
462  * When no rescuee is left pending, the session is over and the balance above
463  * one quantum dies with it - it would otherwise become a banked license to
464  * preempt the cid owner long after the starvation ended. While waiters remain,
465  * the accrued deficit belongs to the queue and carries into the next rescue.
466  */
467 void scx_rescue_end(struct rq *rq)
468 {
469 	lockdep_assert_rq_held(rq);
470 
471 	rq->scx.rescue.curr = NULL;
472 	if (list_empty(&rq->scx.rescue.dsq.list))
473 		rq->scx.rescue.budget = min(rq->scx.rescue.budget, scx_rescue_quantum_ns);
474 }
475 
476 /**
477  * scx_rescue_keep - Keep the rescue going for a preempted-out rescuee
478  * @rq: rq @p is running on
479  * @p: task under rescue whose slice is exhausted
480  *
481  * Called from put_prev_task_scx() to decide what an exhausted slice means for
482  * the rescuee. scx_rescue_charge() ends the rescue the moment the admitted
483  * slice is fully served, so arriving here with the rescue still open means @p
484  * was preempted. Restore the unserved remainder and return %true - @p stays the
485  * rescuee and the caller reinserts it at the tail of the local DSQ, behind
486  * whatever preempted the rescuee.
487  *
488  * Return %false to end the rescue instead - the slice is already fully served,
489  * @p is leaving the rq or bypass is dismantling rescues.
490  */
491 bool scx_rescue_keep(struct rq *rq, struct task_struct *p)
492 {
493 	s64 remaining = scx_rescue_slice_remaining(rq);
494 
495 	lockdep_assert_rq_held(rq);
496 
497 	if (!remaining || !(p->scx.flags & SCX_TASK_QUEUED) ||
498 	    scx_bypassing(scx_task_sched(p), cpu_of(rq)))
499 		return false;
500 
501 	scx_set_task_slice(p, remaining);
502 	return true;
503 }
504 
505 /**
506  * scx_rescue_accrue - Accrue budget at the configured fraction of elapsed time
507  * @rq: rq of interest
508  *
509  * A session spans from the first arrival until no rescuee is left, pending or
510  * admitted. While one is active the cap is three quanta and the balance drives
511  * escalation, see scx_rescue_timerfn(). Outside a session the cap is one
512  * quantum, so an idle gap funds the next arrival's admission but never an
513  * escalation.
514  */
515 static void scx_rescue_accrue(struct rq *rq)
516 {
517 	bool in_session = rq->scx.rescue.curr || !list_empty(&rq->scx.rescue.dsq.list);
518 	s64 cap = in_session ? 3 * scx_rescue_quantum_ns : scx_rescue_quantum_ns;
519 	s64 delta;
520 	u64 now;
521 
522 	lockdep_assert_rq_held(rq);
523 
524 	/* not every path here holds an updated rq clock, use __scx_bpf_now() */
525 	now = __scx_bpf_now(rq);
526 	delta = now - rq->scx.rescue.clock;
527 	rq->scx.rescue.clock = now;
528 
529 	/*
530 	 * Avoid multiplication overflows by taking a shortcut when the gap is
531 	 * large enough to fill the budget.
532 	 */
533 	if (delta >= scx_rescue_sat_delta_ns)
534 		rq->scx.rescue.budget = cap;
535 	else
536 		rq->scx.rescue.budget =
537 			min(cap, rq->scx.rescue.budget +
538 			    ((delta * scx_rescue_bw_1024) >> SCHED_CAPACITY_SHIFT));
539 }
540 
541 /*
542  * The slice for the next admission - the quantum divided across the stranded
543  * tasks so that a crowded queue round-robins on shorter slices.
544  */
545 static s64 scx_rescue_next_slice(struct rq *rq)
546 {
547 	s64 min_slice = max_t(s64, SCX_RESCUE_MIN_SLICE_US * NSEC_PER_USEC, TICK_NSEC);
548 	u32 depth = rq->scx.rescue.dsq.nr ?: 1;
549 
550 	return clamp(div_s64(scx_rescue_quantum_ns, depth), min_slice, scx_rescue_quantum_ns);
551 }
552 
553 static void scx_rescue_timer_arm(struct rq *rq)
554 {
555 	struct timer_list *timer = &rq->scx.rescue.timer;
556 	s64 delay = scx_rescue_quantum_ns / 4;	/* should be granular enough */
557 
558 	if (timer_pending(timer))
559 		return;
560 
561 	/*
562 	 * While the head waiter can't be admitted because the bucket is short
563 	 * of a full quantum, stretch to the full funding delay.
564 	 */
565 	if (!rq->scx.rescue.curr && rq->scx.rescue.budget < scx_rescue_quantum_ns) {
566 		s64 deficit = scx_rescue_quantum_ns - rq->scx.rescue.budget;
567 
568 		delay = max(delay,
569 			    div_s64(deficit << SCHED_CAPACITY_SHIFT, scx_rescue_bw_1024));
570 	}
571 
572 	/* +1 rounds up so the beat is due by the time the timer fires */
573 	timer->expires = jiffies + nsecs_to_jiffies(delay) + 1;
574 	add_timer_on(timer, cpu_of(rq));
575 }
576 
577 /**
578  * scx_rescue_admit - Start rescuing @p on @rq
579  * @rq: rq @p is being admitted on
580  * @p: task being admitted, off any DSQ
581  * @slice: CPU time to grant
582  *
583  * The schedulers keep their normal control over @p and may preempt or reslice
584  * it. @slice is measured on served CPU time against the snapshot taken here, so
585  * neither shortens the rescue, see scx_rescue_charge() and scx_rescue_keep().
586  * Prolonged denial escalates into protected execution, see
587  * scx_rescue_timerfn().
588  */
589 static void scx_rescue_admit(struct rq *rq, struct task_struct *p, s64 slice)
590 {
591 	lockdep_assert_rq_held(rq);
592 	WARN_ON_ONCE(rq->scx.rescue.curr);
593 
594 	rq->scx.rescue.curr = p;
595 	rq->scx.rescue.slice = slice;
596 	rq->scx.rescue.exec_snap = p->se.sum_exec_runtime;
597 	scx_set_task_slice(p, slice);
598 	scx_rescue_timer_arm(rq);
599 }
600 
601 /**
602  * scx_rescue_try_admit - Try to admit a freshly stranded task
603  * @rq: rq @p is being inserted on
604  * @p: stranded task being diverted to rescue
605  *
606  * One rescue at a time and earlier arrivals go first. Admission needs a full
607  * quantum of budget, spent as the rescue runs. Return %true if @p was admitted
608  * and should be inserted at the tail of @rq's local DSQ, %false if it has to
609  * park on the rescue DSQ, with the timer armed to admit it later.
610  */
611 static bool scx_rescue_try_admit(struct rq *rq, struct task_struct *p)
612 {
613 	scx_rescue_accrue(rq);
614 
615 	if (!rq->scx.rescue.curr && list_empty(&rq->scx.rescue.dsq.list) &&
616 	    rq->scx.rescue.budget >= scx_rescue_quantum_ns) {
617 		scx_rescue_admit(rq, p, scx_rescue_quantum_ns);
618 		return true;
619 	}
620 
621 	scx_rescue_timer_arm(rq);
622 	return false;
623 }
624 
625 /**
626  * scx_rescue_check_overload - Eject the top rescue consumer on a stuck rescue
627  * @rq: rq whose rescue timer fired
628  *
629  * If the oldest waiter on @rq's rescue DSQ has been queued for too long, rescue
630  * demand on this cpu persistently exceeds the configured bandwidth. Eject the
631  * sub with the highest recent rescue consumption instead of letting the
632  * scheduler stall path blame the waiter's owner, who may just be crowded out.
633  */
634 static void scx_rescue_check_overload(struct rq *rq)
635 {
636 	struct scx_sched *victim = NULL, *pos;
637 	struct task_struct *p;
638 	int cpu = cpu_of(rq);
639 	u64 max_avg = 0;
640 	u32 dur_ms;
641 
642 	lockdep_assert_rq_held(rq);
643 
644 	p = list_first_entry_or_null(&rq->scx.rescue.dsq.list, struct task_struct,
645 				     scx.dsq_list.node);
646 	if (!p)
647 		return;
648 
649 	/* has the head waiter been queued for longer than the threshold? */
650 	if (time_before(jiffies, p->scx.rescue_at + scx_rescue_overload_after))
651 		return;
652 
653 	/*
654 	 * Grace period after the last ejection on this cpu - the freed
655 	 * bandwidth gets one threshold's worth of time to drain the backlog
656 	 * before another sub is judged.
657 	 */
658 	if (time_before64(get_jiffies_64(), rq->scx.rescue.kill_at +
659 			  scx_rescue_overload_after))
660 		return;
661 
662 	list_for_each_entry_rcu(pos, &scx_sched_all, all) {
663 		u64 avg = scx_rescue_decay_avg(per_cpu_ptr(pos->pcpu, cpu));
664 
665 		/* skip an already-exiting sub, else the ejection is wasted */
666 		if (pos->level && avg > max_avg &&
667 		    atomic_read(&pos->exit_kind) == SCX_EXIT_NONE) {
668 			max_avg = avg;
669 			victim = pos;
670 		}
671 	}
672 	if (!victim)
673 		return;
674 
675 	rq->scx.rescue.kill_at = get_jiffies_64();
676 	dur_ms = jiffies_to_msecs(jiffies - p->scx.rescue_at);
677 	__scx_exit(victim, SCX_EXIT_ERROR_RESCUE, 0, cpu,
678 		   "used too much rescue CPU time (%llums) while %s[%d] waited %u.%03us to be rescued",
679 		   div_u64(max_avg, NSEC_PER_MSEC), p->comm, p->pid, dur_ms / 1000,
680 		   dur_ms % 1000);
681 }
682 
683 /**
684  * scx_rescue_timerfn - Drive and pace rescue execution
685  * @timer: rq->scx.rescue.timer
686  *
687  * Runs every quarter quantum while a rescuee exists, pending or admitted, see
688  * scx_rescue_timer_arm(). The head waiter is admitted once the bucket holds a
689  * full quantum and granted its slice, see scx_rescue_next_slice(). A session
690  * whose budget accumulates over two quanta with the admitted rescuee still
691  * waiting escalates - the rescuee's remaining slice turns into protected
692  * execution and it preempts the current task. An overloaded rescue queue ejects
693  * the top consumer, see scx_rescue_check_overload().
694  */
695 static void scx_rescue_timerfn(struct timer_list *timer)
696 {
697 	struct rq *rq = timer_container_of(rq, timer, scx.rescue.timer);
698 	struct task_struct *p;
699 
700 	guard(rq_lock_irqsave)(rq);
701 
702 	p = rq->scx.rescue.curr;
703 	if (!p && list_empty(&rq->scx.rescue.dsq.list))
704 		return;
705 
706 	scx_rescue_accrue(rq);
707 	scx_rescue_check_overload(rq);
708 
709 	if (!p) {
710 		s64 slice = scx_rescue_next_slice(rq);
711 
712 		/* no rescue in progress */
713 		if (rq->scx.rescue.budget < scx_rescue_quantum_ns)
714 			goto out_arm;
715 
716 		/* there's enough budget to start rescuing the next one */
717 		p = list_first_entry(&rq->scx.rescue.dsq.list, struct task_struct,
718 				     scx.dsq_list.node);
719 		scx_task_unlink_from_dsq(p, &rq->scx.rescue.dsq);
720 		scx_rescue_admit(rq, p, slice);
721 		scx_move_local_task_to_local_dsq(scx_task_sched(p), p,
722 						 SCX_ENQ_IGNORE_CAPS, rq);
723 		if (sched_class_above(&ext_sched_class, rq->donor->sched_class))
724 			resched_curr(rq);
725 	} else if (p->scx.dsq && rq->scx.rescue.budget > 2 * scx_rescue_quantum_ns) {
726 		/*
727 		 * The rescuee waited for the CPU for too long. Escalate - grant
728 		 * the unserved remainder, protect it from the schedulers and
729 		 * preempt the current task. The slice is set before the
730 		 * protection. Repeat beats only repeat the head move - the
731 		 * slice write is refused on a protected task.
732 		 */
733 		scx_set_task_slice(p, scx_rescue_slice_remaining(rq));
734 		p->scx.flags |= SCX_TASK_PROTECTED;
735 		scx_task_unlink_from_dsq(p, &rq->scx.local_dsq);
736 		scx_move_local_task_to_local_dsq(scx_task_sched(p), p,
737 					SCX_ENQ_HEAD | SCX_ENQ_PREEMPT | SCX_ENQ_IGNORE_CAPS,
738 					rq);
739 	}
740 out_arm:
741 	scx_rescue_timer_arm(rq);
742 }
743 
744 /* flush out tasks waiting for rescue before a CPU goes down */
745 void scx_rescue_flush(struct rq *rq)
746 {
747 	struct task_struct *p, *n;
748 
749 	lockdep_assert_rq_held(rq);
750 
751 	/* end the current rescue */
752 	if (rq->scx.rescue.curr)
753 		scx_task_slice_ended(rq, rq->scx.rescue.curr);
754 
755 	/* and flush out all pending ones */
756 	list_for_each_entry_safe(p, n, &rq->scx.rescue.dsq.list, scx.dsq_list.node) {
757 		scx_task_unlink_from_dsq(p, &rq->scx.rescue.dsq);
758 		scx_move_local_task_to_local_dsq(scx_task_sched(p), p,
759 						 SCX_ENQ_IGNORE_CAPS, rq);
760 	}
761 
762 	timer_delete(&rq->scx.rescue.timer);
763 }
764 
765 void scx_rescue_dump(struct seq_buf *s, struct rq *rq)
766 {
767 	struct task_struct *p = rq->scx.rescue.curr;
768 
769 	scx_dump_line(s, "          rescue=%u budget=%lldus rescuing=%s[%d]",
770 		      rq->scx.rescue.dsq.nr,
771 		      div_s64(rq->scx.rescue.budget, NSEC_PER_USEC),
772 		      p ? p->comm : "none", p ? p->pid : -1);
773 }
774 
775 /*
776  * A scheduler whose stall watchdog is shorter than the overload threshold gets
777  * stall-killed over its parked waiters before the overload check can eject the
778  * actual top consumer. The root's knobs set the threshold, warn on any
779  * scheduler that doesn't fit it.
780  */
781 static void scx_rescue_check_timeout(struct scx_sched *sch)
782 {
783 	if (!scx_rescue_bw_1024 || sch->watchdog_timeout > scx_rescue_overload_after)
784 		return;
785 
786 	pr_warn("sched_ext: %s: watchdog timeout %ums <= rescue overload threshold %ums\n",
787 		sch->ops.name, jiffies_to_msecs(sch->watchdog_timeout),
788 		jiffies_to_msecs(scx_rescue_overload_after));
789 }
790 
791 /* latch the rescue parameters on root scheduler enable */
792 void scx_rescue_set_knobs(struct scx_sched *sch)
793 {
794 	s32 bw_ppt = sch->ops.rescue_bandwidth_ppt ?: SCX_RESCUE_DFL_BW_PPT;
795 	s64 quantum_us = sch->ops.rescue_quantum_us ?: SCX_RESCUE_DFL_QUANTUM_US;
796 	s64 period_ns;
797 
798 	if (sch->ops.rescue_bandwidth_ppt == SCX_RESCUE_DISABLE) {
799 		scx_rescue_bw_1024 = 0;
800 		return;
801 	}
802 
803 	scx_rescue_bw_1024 = bw_ppt * SCHED_CAPACITY_SCALE / 1000;
804 	scx_rescue_quantum_ns = max(quantum_us * NSEC_PER_USEC, TICK_NSEC);
805 	scx_rescue_sat_delta_ns =
806 		div_s64((4 * scx_rescue_quantum_ns + TICK_NSEC) << SCHED_CAPACITY_SHIFT,
807 			scx_rescue_bw_1024);
808 
809 	/*
810 	 * The overload threshold and the decay halflife scale with the funding
811 	 * period - the time the bucket takes to fund one full quantum.
812 	 */
813 	period_ns = div_s64(scx_rescue_quantum_ns << SCHED_CAPACITY_SHIFT, scx_rescue_bw_1024);
814 	scx_rescue_overload_after =
815 		clamp(nsecs_to_jiffies(SCX_RESCUE_OVERLOAD_MULT * period_ns),
816 		      msecs_to_jiffies(SCX_RESCUE_MIN_OVERLOAD_MS),
817 		      msecs_to_jiffies(SCX_RESCUE_MAX_OVERLOAD_MS));
818 	scx_rescue_decay_halflife = scx_rescue_overload_after / 4;
819 
820 	/* a single in-budget wait must not cross the overload trigger */
821 	if (nsecs_to_jiffies(period_ns) > scx_rescue_overload_after / 2)
822 		pr_warn("sched_ext: %s: rescue funding period %lldms > overload threshold %ums / 2\n",
823 			sch->ops.name, div_s64(period_ns, NSEC_PER_MSEC),
824 			jiffies_to_msecs(scx_rescue_overload_after));
825 
826 	scx_rescue_check_timeout(sch);
827 }
828 
829 void scx_rescue_init(struct rq *rq)
830 {
831 	BUG_ON(scx_init_dsq(&rq->scx.rescue.dsq, SCX_DSQ_RESCUE, NULL));
832 	timer_setup(&rq->scx.rescue.timer, scx_rescue_timerfn, TIMER_PINNED);
833 	rq->scx.rescue.kill_at = get_jiffies_64();
834 }
835 
836 /**
837  * __scx_resolve_local_dsq - Pick the local, rescue or reject DSQ for an insert
838  * @sch: enqueuing sub-sched
839  * @rq: rq whose local DSQ @p targets
840  * @p: task being inserted
841  * @enq_flags: in/out, unhonored flags are cleared
842  *
843  * Return @rq's local DSQ if @sch holds the required caps on @rq's cid.
844  * Otherwise, return @rq's rescue DSQ if the insert carries %SCX_ENQ_RESCUE and
845  * rescue is enabled, or @rq's reject DSQ after recording the reenq reason on
846  * @p.
847  *
848  * %SCX_ENQ_IMMED, %SCX_ENQ_PREEMPT, %SCX_ENQ_PREEMPT_LAZY and %SCX_ENQ_HEAD are
849  * cleared when diverting to rescue or reject. %SCX_ENQ_PREEMPT and
850  * %SCX_ENQ_PREEMPT_LAZY are also cleared on a fallback migration-disabled
851  * admission.
852  *
853  * Bypass doesn't need special-casing as a bypassing sched's tasks are enqueued
854  * to and run by its nearest non-bypassing ancestor. If root is bypassing, it
855  * always holds all caps.
856  */
857 struct scx_dispatch_q *__scx_resolve_local_dsq(struct scx_sched *sch, struct rq *rq,
858 					       struct task_struct *p, u64 *enq_flags)
859 {
860 	s32 cid = __scx_cpu_to_cid(cpu_of(rq));
861 	struct scx_sched *asch = rq->scx.remote_activate_sch ?: sch;
862 	u64 needed = scx_caps_for_enq(*enq_flags);
863 	u64 missing;
864 
865 	/*
866 	 * On a remote activation the scheduling sched (@asch) differs from
867 	 * @p's owner (@sch). Check caps against the scheduling sched.
868 	 */
869 	if (*enq_flags & (SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY))
870 		needed |= scx_caps_for_preempt(asch, rq, *enq_flags);
871 	missing = scx_missing_caps(asch, cpu_of(rq), needed);
872 
873 	/* requirements met */
874 	if (likely(!missing))
875 		return &rq->scx.local_dsq;
876 
877 	/*
878 	 * The task must run on this CPU regardless of caps: the rq is draining
879 	 * offline (BPF scheduler bypassed), the task is migration-disabled, or a
880 	 * migration is pending. Admit despite the missing caps and count it.
881 	 * Refuse preemptions.
882 	 */
883 	if (unlikely(!scx_rq_online(rq) || is_migration_disabled(p) ||
884 		     p->migration_pending)) {
885 		__scx_add_event(sch, SCX_EV_SUB_FORCED_ADMIT, 1);
886 		*enq_flags &= ~(SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY);
887 		return &rq->scx.local_dsq;
888 	}
889 
890 	/*
891 	 * Diverting to rescue or reject, neither of which honors IMMED, PREEMPT
892 	 * or HEAD - a diversion has no priority and IMMED is not allowed on
893 	 * non-local DSQs. Strip the enq and task flags along with the slice.
894 	 */
895 	scx_divert_strip_flags(p, enq_flags);
896 
897 	/* the enqueuer opted for rescue instead of rejection and reenqueue */
898 	if ((*enq_flags & SCX_ENQ_RESCUE) && likely(scx_rescue_bw_1024)) {
899 		__scx_add_event(sch, SCX_EV_SUB_RESCUE, 1);
900 		if (scx_rescue_try_admit(rq, p))
901 			return &rq->scx.local_dsq;
902 
903 		/* queueing, the overload trigger measures the wait from here */
904 		p->scx.rescue_at = jiffies;
905 		return &rq->scx.rescue.dsq;
906 	}
907 
908 	p->scx.reenq_reason_caps = missing;
909 	p->scx.reenq_reason_cid = cid;
910 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK);
911 	p->scx.flags |= SCX_TASK_REENQ_CAP;
912 
913 	return &rq->scx.reject_dsq;
914 }
915 
916 /* @p lost the caps needed to stay on @rq's local DSQ? Record reason if so. */
917 bool scx_task_reenq_on_cap_revoke(struct rq *rq, struct task_struct *p)
918 {
919 	s32 cpu = cpu_of(rq);
920 	u64 missing;
921 
922 	/* migration-disabled tasks and the rescuee are admitted capless */
923 	if (is_migration_disabled(p) || p == scx_rescuee(rq))
924 		return false;
925 
926 	/* check caps against the sched running a bypassed task */
927 	missing = scx_missing_caps(scx_exec_sched(scx_task_sched(p), cpu), cpu,
928 				   scx_caps_for_task(p));
929 	if (likely(!missing))
930 		return false;
931 
932 	p->scx.reenq_reason_caps = missing;
933 	p->scx.reenq_reason_cid = __scx_cpu_to_cid(cpu);
934 	return true;
935 }
936 
937 /* record a caps change, see struct scx_caps_updated */
938 static void caps_updated_record(struct scx_pshard *ps, const struct scx_cmask *cids, u64 caps,
939 				struct list_head *to_deliver)
940 {
941 	struct scx_caps_updated *cu = &ps->caps_updated;
942 
943 	guard(raw_spinlock)(&cu->lock);
944 	scx_cmask_or(&cu->cmask, cids);
945 	cu->caps |= caps;
946 	if (list_empty(&cu->node_in_flight))
947 		list_add_tail(&cu->node_in_flight, to_deliver);
948 }
949 
950 /* deliver queued caps_updated callbacks, see struct scx_caps_updated */
951 static void caps_updated_deliver(struct list_head *to_deliver)
952 {
953 	struct scx_caps_updated *cu, *tmp;
954 
955 	list_for_each_entry_safe(cu, tmp, to_deliver, node_in_flight) {
956 		struct scx_pshard *ps = container_of(cu, struct scx_pshard, caps_updated);
957 		struct scx_sched *sch = ps->sch;
958 
959 		while (true) {
960 			u64 caps = 0;
961 
962 			/*
963 			 * During enable, has_op is set after ops.sub_attach(),
964 			 * so !has_op means the op is absent or the sched isn't
965 			 * live yet - e.g. caps grant from ops.sub_attach().
966 			 * Either way don't consume - leave for
967 			 * scx_sub_seed_caps() to deliver once live.
968 			 */
969 			scoped_guard (raw_spinlock, &cu->lock) {
970 				if (cu->caps && SCX_HAS_OP(sch, sub_caps_updated) &&
971 				    likely(!READ_ONCE(sch->aborting))) {
972 					struct scx_cmask_ref ref;
973 
974 					caps = cu->caps;
975 					scx_cmask_ref_init_kern(sch, cu->cmask_arena_out,
976 								ps->base, ps->nr_cids, &ref);
977 					scx_cmask_ref_copy(&ref, &cu->cmask);
978 					scx_cmask_clear(&cu->cmask);
979 					cu->caps = 0;
980 				} else {
981 					list_del_init(&cu->node_in_flight);
982 				}
983 			}
984 			if (!caps)
985 				break;
986 
987 			/* caps != 0 only when deliverable (has_op, above) */
988 			SCX_CALL_OP(sch, sub_caps_updated, NULL, cu->cmask_arena_out, caps);
989 		}
990 	}
991 }
992 
993 /*
994  * Deliver caps owed to @sch that couldn't be delivered earlier (e.g. a grant
995  * taken during its sub_attach(), before has_op was set). Called once @sch is
996  * enabled.
997  */
998 static void scx_sub_seed_caps(struct scx_sched *sch)
999 {
1000 	LIST_HEAD(to_deliver);
1001 	s32 si;
1002 
1003 	guard(irqsave)();
1004 
1005 	for (si = 0; si < sch->nr_pshards; si++) {
1006 		struct scx_pshard *ps = sch->pshard[si];
1007 		struct scx_caps_updated *cu = &ps->caps_updated;
1008 
1009 		scoped_guard (raw_spinlock, &cu->lock) {
1010 			if (cu->caps && list_empty(&cu->node_in_flight))
1011 				list_add_tail(&cu->node_in_flight, &to_deliver);
1012 		}
1013 	}
1014 	caps_updated_deliver(&to_deliver);
1015 }
1016 
1017 static u64 calc_effective_caps(struct scx_pshard *ps, s32 cid)
1018 {
1019 	u64 ecaps = 0;
1020 	u32 cap_bit;
1021 
1022 	for (cap_bit = 0; cap_bit < __SCX_NR_CAPS; cap_bit++)
1023 		if (scx_cmask_test(cid, &ps->caps[cap_bit].cmask))
1024 			ecaps |= BIT_U64(cap_bit) | scx_caps_implied(BIT_U64(cap_bit));
1025 	return ecaps;
1026 }
1027 
1028 /**
1029  * queue_sync_ecaps - Queue ecaps update for a (sch, cid) pair
1030  * @sch: sched to update
1031  * @cid: cid to update
1032  *
1033  * Queue an ecaps update for @sch's @cid and kick the cpu so that it syncs in
1034  * dispatch_one().
1035  */
1036 static void queue_sync_ecaps(struct scx_sched *sch, s32 cid)
1037 {
1038 	s32 cpu = __scx_cid_to_cpu(cid);
1039 	struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
1040 
1041 	/*
1042 	 * Pairs with smp_mb() in __scx_process_sync_ecaps(). Either the check
1043 	 * below sees the node off the list and queues it, or the in-flight sync
1044 	 * sees the caps[] update made before this call.
1045 	 */
1046 	smp_mb();
1047 
1048 	/* @cid's pshard->lock excludes concurrent queueing attempts */
1049 	if (llist_on_list(&pcpu->ecaps_to_sync_node))
1050 		return;
1051 	if (llist_add(&pcpu->ecaps_to_sync_node, &cpu_rq(cpu)->scx.ecaps_to_sync))
1052 		scx_kick_cpu(sch->ancestors[0], cpu, 0);
1053 }
1054 
1055 /* discard @rq's queued ecaps syncs */
1056 static void discard_queued_syncs(struct rq *rq)
1057 {
1058 	struct llist_node *pos, *tmp;
1059 
1060 	lockdep_assert_rq_held(rq);
1061 
1062 	llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync))
1063 		init_llist_node(pos);
1064 }
1065 
1066 /**
1067  * __scx_process_sync_ecaps - Sync this cpu's ecaps to pshard->caps[]
1068  * @rq: the cid's cpu rq
1069  * @prev: @rq's previous task from the in-progress dispatch
1070  *
1071  * pshard->caps[] is the target configuration. pcpu->ecaps is the effective
1072  * transposed copy owned by the cid's cpu and written only here under @rq's
1073  * lock.
1074  *
1075  * A sched that newly gains baseline access here is owed an update_idle() so it
1076  * learns the cid's idle state. Such a gain arms the per-rq
1077  * %SCX_RQ_SUB_IDLE_RENOTIFY gate so the next idle pick delivers it.
1078  */
1079 void __scx_process_sync_ecaps(struct rq *rq, struct task_struct *prev)
1080 {
1081 	s32 cpu = cpu_of(rq);
1082 	s32 cid, shard;
1083 	struct llist_node *batch, *pos, *tmp;
1084 	u64 lost_all = 0;
1085 
1086 	if (likely(llist_empty(&rq->scx.ecaps_to_sync)))
1087 		return;
1088 
1089 	/*
1090 	 * ecaps are zeroed while the cpu is inactive and must stay zero.
1091 	 * Discard queued syncs instead of processing them - the
1092 	 * scx_online_ecaps() reseed re-syncs every sched on activation.
1093 	 * cpu_active() clears before the offline zeroing and sets before the
1094 	 * reseed is queued, so this test can neither miss a racing sync nor
1095 	 * eat the reseed.
1096 	 */
1097 	if (unlikely(!cpu_active(cpu))) {
1098 		discard_queued_syncs(rq);
1099 		return;
1100 	}
1101 
1102 	/* @cid is valid here: the cpu is active with queued syncs */
1103 	cid = __scx_cpu_to_cid(cpu);
1104 	shard = rcu_dereference_all(scx_cid_to_shard)[cid];
1105 
1106 	batch = llist_del_all(&rq->scx.ecaps_to_sync);
1107 	llist_for_each_safe(pos, tmp, batch) {
1108 		struct scx_sched_pcpu *pcpu =
1109 			container_of(pos, struct scx_sched_pcpu, ecaps_to_sync_node);
1110 		struct scx_pshard *ps = pcpu->sch->pshard[shard];
1111 		u64 old, ecaps, lost, gained;
1112 
1113 		init_llist_node(pos);
1114 
1115 		/* pairs with smp_mb() in queue_sync_ecaps(), see there */
1116 		smp_mb();
1117 
1118 		old = READ_ONCE(pcpu->ecaps);
1119 		ecaps = calc_effective_caps(ps, cid);
1120 		WRITE_ONCE(pcpu->ecaps, ecaps);
1121 
1122 		lost = old & ~ecaps;
1123 		gained = ecaps & ~old;
1124 		lost_all |= lost;
1125 
1126 		/*
1127 		 * Tell the sched and its parent that the sched's effective caps
1128 		 * on this cid changed. The invocations are equivalent to the
1129 		 * dispatch path and may drop and re-acquire the rq lock
1130 		 * temporarily while the rest of @batch is held privately, see
1131 		 * scx_discard_ecaps_to_sync(). The dispatch kfuncs resolve
1132 		 * their context on the executing cpu, which under core
1133 		 * scheduling can differ from @rq's cpu, so the context is set
1134 		 * up there. The rq recorded in it keeps the dispatches
1135 		 * targeting @rq.
1136 		 *
1137 		 * Bypass propagates down the hierarchy, so a sched that isn't
1138 		 * bypassing has no bypassing parent. The child's bypass state
1139 		 * gates both deliveries. Both report the same before value, so
1140 		 * one reported_ecaps covers them.
1141 		 */
1142 		if (ecaps != pcpu->reported_ecaps && !scx_bypassing(pcpu->sch, cpu)) {
1143 			struct scx_sched *parent = scx_parent(pcpu->sch);
1144 			struct scx_dsp_ctx *dspc;
1145 
1146 			/* stash @prev so nested dispatches can access it */
1147 			rq->scx.sub_dispatch_prev = prev;
1148 			if (SCX_HAS_OP(pcpu->sch, sub_ecaps_updated)) {
1149 				dspc = &this_cpu_ptr(pcpu->sch->pcpu)->dsp_ctx;
1150 				dspc->rq = rq;
1151 				SCX_CALL_OP(pcpu->sch, sub_ecaps_updated, rq,
1152 					    scx_cpu_arg(cpu), pcpu->reported_ecaps, ecaps);
1153 				scx_flush_dispatch_buf(pcpu->sch, rq);
1154 			}
1155 			if (SCX_HAS_OP(parent, sub_child_ecaps_updated)) {
1156 				dspc = &this_cpu_ptr(parent->pcpu)->dsp_ctx;
1157 				dspc->rq = rq;
1158 				SCX_CALL_OP(parent, sub_child_ecaps_updated, rq,
1159 					    pcpu->sch->ops.sub_cgroup_id, scx_cpu_arg(cpu),
1160 					    pcpu->reported_ecaps, ecaps);
1161 				scx_flush_dispatch_buf(parent, rq);
1162 			}
1163 			rq->scx.sub_dispatch_prev = NULL;
1164 			pcpu->reported_ecaps = ecaps;
1165 		}
1166 
1167 		/*
1168 		 * Gaining baseline access owes an update_idle() so the sched
1169 		 * learns the cpu's idle state. Arm the per-rq gate so the next
1170 		 * idle pick flushes it. Losing access drops any pending notify.
1171 		 */
1172 		if (gained & SCX_CAP_BASE) {
1173 			pcpu->idle_renotify = true;
1174 			rq->scx.flags |= SCX_RQ_SUB_IDLE_RENOTIFY;
1175 		} else if (lost & SCX_CAP_BASE) {
1176 			pcpu->idle_renotify = false;
1177 		}
1178 	}
1179 
1180 	/*
1181 	 * Losing a cap can strand already-queued tasks. Schedule a reenq scan
1182 	 * to move the now-capless ones off the local DSQ. The scan tests
1183 	 * against the effective caps and thus must come after the ecaps sync.
1184 	 */
1185 	if (lost_all & SCX_CAPS_REENQ_ON_LOSS)
1186 		scx_schedule_reenq_local(rq, SCX_REENQ_CAP_REVOKE);
1187 }
1188 
1189 /**
1190  * scx_unbypass_replay_ecaps - Replay a bypass-suppressed ecaps notification
1191  * @rq: rq of the cpu leaving bypass
1192  * @sch: scheduler that just left bypass on @rq's cpu
1193  *
1194  * scx_process_sync_ecaps() consumes syncs while bypassing without delivering
1195  * ops.sub_ecaps_updated(), leaving reported_ecaps stale. Nothing re-queues a
1196  * sync when bypass lifts, so without a replay a cid that never changes again
1197  * would never be notified. The attach-time initial grants are the acute case
1198  * as they are consumed during the enable bypass window. Re-queue a sync for
1199  * any undelivered delta so the next dispatch delivers it.
1200  */
1201 void scx_unbypass_replay_ecaps(struct rq *rq, struct scx_sched *sch)
1202 {
1203 	s32 cpu = cpu_of(rq);
1204 	struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
1205 	struct scx_pshard *ps;
1206 	s32 cid;
1207 
1208 	lockdep_assert_rq_held(rq);
1209 
1210 	/* root holds every cap and never uses ecaps */
1211 	if (!sch->level)
1212 		return;
1213 
1214 	if (READ_ONCE(pcpu->ecaps) == pcpu->reported_ecaps)
1215 		return;
1216 
1217 	cid = __scx_cpu_to_cid(cpu);
1218 	ps = sch->pshard[rcu_dereference_all(scx_cid_to_shard)[cid]];
1219 
1220 	guard(raw_spinlock)(&ps->lock);
1221 	queue_sync_ecaps(sch, cid);
1222 }
1223 
1224 /*
1225  * A cpu came back. Re-seed each sub-sched's ecaps on the cpu's cid. The sync
1226  * recomputes effective caps from the pshard and fires ops.sub_ecaps_updated()
1227  * only on a real change since offline.
1228  */
1229 void scx_online_ecaps(struct rq *rq)
1230 {
1231 	struct scx_sched *root, *pos;
1232 	s32 cid, shard;
1233 
1234 	/*
1235 	 * Only a live hierarchy can have ecaps to reseed. This also keeps the
1236 	 * table reads below away from an enable that failed before publishing
1237 	 * the tables. A concurrent disable can't retire them, see
1238 	 * handle_hotplug().
1239 	 */
1240 	if (!scx_enabled())
1241 		return;
1242 
1243 	guard(rq_lock_irqsave)(rq);
1244 
1245 	root = scx_root_protected();
1246 	cid = __scx_cpu_to_cid(cpu_of(rq));
1247 	shard = rcu_dereference_all(scx_cid_to_shard)[cid];
1248 
1249 	scx_for_each_descendant_pre(pos, root) {
1250 		struct scx_pshard *ps;
1251 
1252 		/* root holds every cap and never uses ecaps */
1253 		if (!pos->level)
1254 			continue;
1255 
1256 		ps = pos->pshard[shard];
1257 		guard(raw_spinlock)(&ps->lock);
1258 		queue_sync_ecaps(pos, cid);
1259 	}
1260 }
1261 
1262 /*
1263  * A cpu is going down. Zero each sub-sched's in-effect ecaps so cap checks
1264  * treat the cpu as capless while offline. Pending and late-queued syncs are
1265  * discarded at consumption by scx_process_sync_ecaps() while the cpu is
1266  * inactive. Leave reported_ecaps. Ownership is unchanged, so the
1267  * scx_online_ecaps() reseed reports only a genuine delta. No callback fires
1268  * here.
1269  */
1270 void scx_offline_ecaps(struct rq *rq)
1271 {
1272 	s32 cpu = cpu_of(rq);
1273 	struct scx_sched *root, *pos;
1274 
1275 	guard(rq_lock_irqsave)(rq);
1276 
1277 	root = scx_root_protected();
1278 
1279 	scx_for_each_descendant_pre(pos, root) {
1280 		/* root holds every cap and never uses ecaps */
1281 		if (!pos->level)
1282 			continue;
1283 
1284 		WRITE_ONCE(per_cpu_ptr(pos->pcpu, cpu)->ecaps, 0);
1285 	}
1286 }
1287 
1288 /*
1289  * Clear every cap @sch holds. The pshard caps go first as they are the source a
1290  * pending sync recomputes ecaps from. ecaps are then zeroed directly for the
1291  * cap checks.
1292  */
1293 static void clear_all_caps(struct scx_sched *sch)
1294 {
1295 	s32 si, cpu;
1296 	u32 cap_bit;
1297 
1298 	/* enable may have failed before scx_alloc_pshards() */
1299 	if (!sch->pshard)
1300 		return;
1301 
1302 	for (si = 0; si < sch->nr_pshards; si++) {
1303 		struct scx_pshard *ps = sch->pshard[si];
1304 
1305 		guard(raw_spinlock_irqsave)(&ps->lock);
1306 		for (cap_bit = 0; cap_bit < __SCX_NR_CAPS; cap_bit++)
1307 			scx_cmask_clear(&ps->caps[cap_bit].cmask);
1308 	}
1309 
1310 	for_each_possible_cpu(cpu) {
1311 		guard(rq_lock_irqsave)(cpu_rq(cpu));
1312 		WRITE_ONCE(per_cpu_ptr(sch->pcpu, cpu)->ecaps, 0);
1313 	}
1314 }
1315 
1316 /*
1317  * @pcpu's sched was unhashed before the grace period, so nothing re-queues its
1318  * sync node. Remove the node from @rq's pending list so the pcpu can be freed.
1319  */
1320 void scx_discard_ecaps_to_sync(s32 cpu, struct scx_sched_pcpu *pcpu)
1321 {
1322 	struct rq *rq = cpu_rq(cpu);
1323 	struct llist_node *head = NULL, *tail = NULL;
1324 	struct llist_node *pos, *tmp;
1325 
1326 	/*
1327 	 * llist can't unlink a single node. Take all queued nodes, drop @pcpu's
1328 	 * and resplice the rest. Nodes in the taken batch read as on-list
1329 	 * throughout, so queue_sync_ecaps() stays correct.
1330 	 */
1331 	if (llist_on_list(&pcpu->ecaps_to_sync_node)) {
1332 		scoped_guard (rq_lock_irqsave, rq) {
1333 			llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) {
1334 				if (pos == &pcpu->ecaps_to_sync_node) {
1335 					init_llist_node(pos);
1336 				} else {
1337 					pos->next = head;
1338 					head = pos;
1339 					if (!tail)
1340 						tail = pos;
1341 				}
1342 			}
1343 			if (head)
1344 				llist_add_batch(head, tail, &rq->scx.ecaps_to_sync);
1345 		}
1346 	}
1347 
1348 	/*
1349 	 * An in-flight scx_process_sync_ecaps() batch may still hold the node
1350 	 * privately across dispatch-induced rq unlocks, reading as on-list.
1351 	 *
1352 	 * Because a bypassing sched gets no op call, init_llist_node() and all
1353 	 * @pcpu accesses share one contiguous lock hold, off-list under the rq
1354 	 * lock means @pcpu won't be accessed again.
1355 	 */
1356 	while (true) {
1357 		scoped_guard (rq_lock_irqsave, rq) {
1358 			if (!llist_on_list(&pcpu->ecaps_to_sync_node))
1359 				return;
1360 		}
1361 		cpu_relax();
1362 	}
1363 }
1364 
1365 /**
1366  * scx_discard_stale_ecaps_syncs - Discard ecaps syncs from earlier schedulers
1367  *
1368  * To be called during root enable before the scheduler goes live. An earlier
1369  * root's sub-sched may not have gone through its RCU free path yet (e.g. a
1370  * still-open link fd defers it) and can leave queued ecaps syncs behind.
1371  * Processing them would decode the dead sched's pshards with the current cid
1372  * layout. Discard them instead. The backing scx_sched_pcpu's are still
1373  * allocated as the free path removes ecaps_to_sync_node before freeing.
1374  */
1375 void scx_discard_stale_ecaps_syncs(void)
1376 {
1377 	s32 cpu;
1378 
1379 	for_each_possible_cpu(cpu) {
1380 		struct rq *rq = cpu_rq(cpu);
1381 
1382 		guard(rq_lock_irqsave)(rq);
1383 		discard_queued_syncs(rq);
1384 	}
1385 }
1386 
1387 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq);
1388 
1389 void drain_descendants(struct scx_sched *sch)
1390 {
1391 	/*
1392 	 * Child scheds that finished the critical part of disabling will take
1393 	 * themselves off @sch->children. Wait for it to drain. As propagation
1394 	 * is recursive, empty @sch->children means that all proper descendant
1395 	 * scheds reached unlinking stage.
1396 	 */
1397 	wait_event(scx_unlink_waitq, list_empty(&sch->children));
1398 }
1399 
1400 /**
1401  * scx_rehome_task - Move a task to a sched it has been initialized for
1402  * @to: sched taking over @p, @p's init on it already complete
1403  * @p: task to re-home
1404  *
1405  * Exit @p from its current sched and switch it over to @to, overriding the
1406  * state to %SCX_TASK_READY to account for the already completed init. A task
1407  * on a non-ext class, possible under an %SCX_OPS_SWITCH_PARTIAL root, stays
1408  * %READY and is enabled by switching_to_scx() if it switches over.
1409  */
1410 static void scx_rehome_task(struct scx_sched *to, struct task_struct *p)
1411 {
1412 	lockdep_assert_held(&p->pi_lock);
1413 	lockdep_assert_rq_held(task_rq(p));
1414 
1415 	scx_prepare_task_sched_change(p);
1416 	scoped_guard (sched_change, p,
1417 		      DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK) {
1418 		scx_disable_and_exit_task(scx_task_sched(p), p);
1419 		scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
1420 		scx_set_task_state(p, SCX_TASK_INIT);
1421 		scx_set_task_sched(p, to);
1422 		scx_set_task_state(p, SCX_TASK_READY);
1423 		if (p->sched_class == &ext_sched_class)
1424 			scx_enable_task(to, p);
1425 	}
1426 }
1427 
1428 /**
1429  * scx_punt_task - Hand a task to a failed sched without initialization
1430  * @to: failed and bypassed sched taking custody of @p
1431  * @p: task to punt
1432  *
1433  * Take @p off its current sched and put it on @to at %SCX_TASK_NONE. @to is
1434  * dying and its teardown will re-home @p properly.
1435  *
1436  * Used when @to must take over @p but failed to initialize it. Bypass keeps
1437  * scheduling decisions away from @to but @p can still trigger its task ops,
1438  * which may confuse the BPF side. @to is dying anyway. The exit paths skip
1439  * %NONE tasks (see __scx_disable_and_exit_task() and switched_from_scx()).
1440  */
1441 static void scx_punt_task(struct scx_sched *to, struct task_struct *p)
1442 {
1443 	lockdep_assert_held(&p->pi_lock);
1444 	lockdep_assert_rq_held(task_rq(p));
1445 	WARN_ON_ONCE(!READ_ONCE(to->bypass_depth));
1446 
1447 	scx_prepare_task_sched_change(p);
1448 	scoped_guard (sched_change, p,
1449 		      DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK) {
1450 		scx_disable_and_exit_task(scx_task_sched(p), p);
1451 		scx_set_task_sched(p, to);
1452 	}
1453 }
1454 
1455 static void scx_fail_parent(struct scx_sched *sch,
1456 			    struct task_struct *failed, s32 fail_code)
1457 {
1458 	struct scx_sched *parent = scx_parent(sch);
1459 	struct scx_task_iter sti;
1460 	struct task_struct *p;
1461 
1462 	scx_error(parent, "ops.init_task() failed (%d) for %s[%d] while disabling a sub-scheduler",
1463 		  fail_code, failed->comm, failed->pid);
1464 
1465 	/*
1466 	 * Once $parent is bypassed, tasks can be punted into it. This may
1467 	 * cause downstream failures on the BPF side but $parent is dying
1468 	 * anyway.
1469 	 */
1470 	scx_bypass(parent, true);
1471 
1472 	scx_task_iter_start(&sti, sch->cgrp);
1473 	while ((p = scx_task_iter_next_locked(&sti))) {
1474 		if (scx_task_on_sched(parent, p))
1475 			continue;
1476 
1477 		scx_punt_task(parent, p);
1478 	}
1479 	scx_task_iter_stop(&sti);
1480 }
1481 
1482 #ifdef CONFIG_EXT_GROUP_SCHED
1483 /**
1484  * scx_cgroup_claim_subtree - Claim the subtree's cgroups for an enabling sub
1485  * @sch: sub-scheduler being enabled
1486  *
1487  * Called while enabling @sch, after the subtree's cgrp->scx_sched's are pointed
1488  * at @sch and before any task is claimed. This mirrors root enable's
1489  * cgroups-before-tasks order. The ops.init_task() args are task_group-granular
1490  * and can still reference a cgroup outside the handed-over set when the cpu
1491  * controller is coarser than the sub topology or mounted on cgroup1.
1492  *
1493  * First init each of the parent sched's subtree cgroups on @sch, and only then
1494  * exit them from the parent, so that a failed init can be unwound with the
1495  * parent untouched. The both-inited transient is invisible outside
1496  * scx_cgroup_lock(). %SCX_TG_SUB_INIT tracks the first pass's progress.
1497  * %SCX_TG_INITED stays set throughout, except for a task_group whose
1498  * ops.cgroup_init() failed on the parent (see scx_cgroup_return_subtree()):
1499  * there is nothing to exit from the parent and %SCX_TG_INITED is set back with
1500  * the transfer.
1501  *
1502  * Dying but not yet offlined task_groups are included: a removed cgroup keeps
1503  * hosting scheduling events until its dying tasks finish their final context
1504  * switches, so it still needs to be inited on a sched, and its offline-time
1505  * ops.cgroup_exit() follows the last of those events.
1506  *
1507  * Return 0 on success, -errno on failure. On failure, @sch has been
1508  * scx_error()'d and is left with no cgroups.
1509  */
1510 static s32 scx_cgroup_claim_subtree(struct scx_sched *sch)
1511 {
1512 	struct cgroup *sub_cgrp = sch_cgroup(sch);
1513 	struct cgroup_subsys_state *ecss = cgroup_e_css(sub_cgrp, &cpu_cgrp_subsys);
1514 	struct scx_sched *parent = scx_parent(sch);
1515 	struct cgroup_subsys_state *css;
1516 	int ret;
1517 
1518 	css_for_each_descendant_pre(css, ecss) {
1519 		struct task_group *tg = css_tg(css);
1520 		struct scx_cgroup_init_args args = {
1521 			.weight = tg->scx.weight,
1522 			.bw_period_us = tg->scx.bw_period_us,
1523 			.bw_quota_us = tg->scx.bw_quota_us,
1524 			.bw_burst_us = tg->scx.bw_burst_us,
1525 			.sched_idle = tg->scx.sched_idle,
1526 		};
1527 
1528 		if (tg->scx.sched != parent ||
1529 		    !cgroup_is_descendant(css->cgroup, sub_cgrp))
1530 			continue;
1531 
1532 		if (SCX_HAS_OP(sch, cgroup_init)) {
1533 			ret = SCX_CALL_OP_RET(sch, cgroup_init, NULL, css->cgroup, &args);
1534 			if (ret) {
1535 				scx_error(sch, "ops.cgroup_init() failed (%d)", ret);
1536 				goto err;
1537 			}
1538 		}
1539 		tg->scx.flags |= SCX_TG_SUB_INIT;
1540 	}
1541 
1542 	css_for_each_descendant_post(css, ecss) {
1543 		struct task_group *tg = css_tg(css);
1544 
1545 		/*
1546 		 * SUB_INIT is pass 1's progress mark: pass 2 and the err path
1547 		 * must visit exactly the tgs pass 1 inited.
1548 		 */
1549 		if (!(tg->scx.flags & SCX_TG_SUB_INIT))
1550 			continue;
1551 
1552 		/* skip the exit if the parent's ops.cgroup_init() failed */
1553 		if ((tg->scx.flags & SCX_TG_INITED) && SCX_HAS_OP(parent, cgroup_exit))
1554 			SCX_CALL_OP(parent, cgroup_exit, NULL, css->cgroup);
1555 		tg->scx.sched = sch;
1556 		tg->scx.flags |= SCX_TG_INITED;
1557 		tg->scx.flags &= ~SCX_TG_SUB_INIT;
1558 	}
1559 
1560 	return 0;
1561 
1562 err:
1563 	css_for_each_descendant_post(css, ecss) {
1564 		struct task_group *tg = css_tg(css);
1565 
1566 		if (!(tg->scx.flags & SCX_TG_SUB_INIT))
1567 			continue;
1568 
1569 		if (SCX_HAS_OP(sch, cgroup_exit))
1570 			SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup);
1571 		tg->scx.flags &= ~SCX_TG_SUB_INIT;
1572 	}
1573 	return ret;
1574 }
1575 
1576 /**
1577  * scx_cgroup_return_subtree - Return the subtree's cgroups to the parent sched
1578  * @sch: sub-scheduler being disabled
1579  *
1580  * Called while disabling @sch, after the subtree's cgrp->scx_sched's are reset
1581  * to the parent sched and before tasks are re-homed, mirroring root disable's
1582  * cgroups-before-tasks teardown order. The reverse of
1583  * scx_cgroup_claim_subtree(): exit @sch's cgroups from @sch, then init them on
1584  * the parent with the current tg->scx.* values, resyncing settings that changed
1585  * while @sch had them.
1586  *
1587  * When an init on the parent fails, the parent is failed - the same policy as
1588  * task re-homing. The remaining task_groups are punted: they move to the parent
1589  * anyway with %SCX_TG_INITED cleared, as ops.cgroup_init() failed or never ran
1590  * for them. A punted task_group gets no cgroup ops. The dying parent's own
1591  * disable moves it one sched up, initing it there. Root ends the chain: root
1592  * teardown drops cgroup ops entirely and the next enable's bulk init re-inits
1593  * every online task_group.
1594  *
1595  * The task re-home that follows still delivers ops.init_task() to the dying
1596  * parent, including for tasks in punted cgroups it never inited - tolerated
1597  * like the downstream failures of task punting (see scx_punt_task()).
1598  */
1599 static void scx_cgroup_return_subtree(struct scx_sched *sch)
1600 {
1601 	struct cgroup *sub_cgrp = sch_cgroup(sch);
1602 	struct cgroup_subsys_state *ecss = cgroup_e_css(sub_cgrp, &cpu_cgrp_subsys);
1603 	struct scx_sched *parent = scx_parent(sch);
1604 	struct cgroup_subsys_state *css;
1605 	bool parent_failed = false;
1606 	int ret;
1607 
1608 	css_for_each_descendant_post(css, ecss) {
1609 		struct task_group *tg = css_tg(css);
1610 
1611 		if (tg->scx.sched != sch ||
1612 		    !cgroup_is_descendant(css->cgroup, sub_cgrp))
1613 			continue;
1614 
1615 		/* skip the exit if @sch's ops.cgroup_init() failed for the tg */
1616 		if ((tg->scx.flags & SCX_TG_INITED) && SCX_HAS_OP(sch, cgroup_exit))
1617 			SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup);
1618 		tg->scx.sched = parent;
1619 		tg->scx.flags |= SCX_TG_SUB_INIT;
1620 	}
1621 
1622 	css_for_each_descendant_pre(css, ecss) {
1623 		struct task_group *tg = css_tg(css);
1624 		struct scx_cgroup_init_args args = {
1625 			.weight = tg->scx.weight,
1626 			.bw_period_us = tg->scx.bw_period_us,
1627 			.bw_quota_us = tg->scx.bw_quota_us,
1628 			.bw_burst_us = tg->scx.bw_burst_us,
1629 			.sched_idle = tg->scx.sched_idle,
1630 		};
1631 
1632 		/* the first pass must have transferred everything */
1633 		WARN_ON_ONCE(tg->scx.sched == sch);
1634 
1635 		/*
1636 		 * SUB_INIT distinguishes the tgs pass 1 moved. The sched test
1637 		 * can't: a tg punted to the parent by an earlier failure would
1638 		 * also match.
1639 		 */
1640 		if (!(tg->scx.flags & SCX_TG_SUB_INIT))
1641 			continue;
1642 		tg->scx.flags &= ~(SCX_TG_SUB_INIT | SCX_TG_INITED);
1643 
1644 		/*
1645 		 * A re-init on $parent failed. The task_groups from here on are
1646 		 * punted: they stay on the dying $parent with INITED clear and
1647 		 * move onward when it disables.
1648 		 */
1649 		if (parent_failed)
1650 			continue;
1651 
1652 		if (SCX_HAS_OP(parent, cgroup_init)) {
1653 			ret = SCX_CALL_OP_RET(parent, cgroup_init, NULL, css->cgroup, &args);
1654 			if (ret) {
1655 				scx_error(parent, "ops.cgroup_init() failed (%d) while disabling a sub-scheduler",
1656 					  ret);
1657 				parent_failed = true;
1658 				continue;
1659 			}
1660 		}
1661 		tg->scx.flags |= SCX_TG_INITED;
1662 	}
1663 }
1664 #else
1665 static inline s32 scx_cgroup_claim_subtree(struct scx_sched *sch) { return 0; }
1666 static inline void scx_cgroup_return_subtree(struct scx_sched *sch) {}
1667 #endif
1668 
1669 void scx_sub_disable(struct scx_sched *sch)
1670 {
1671 	struct scx_sched *parent = scx_parent(sch);
1672 	struct scx_task_iter sti;
1673 	struct task_struct *p;
1674 	int ret;
1675 
1676 	/*
1677 	 * Guarantee forward progress and wait for descendants to be disabled.
1678 	 * To limit disruptions, $parent is not bypassed. Tasks are fully
1679 	 * prepped and then inserted back into $parent.
1680 	 */
1681 	scx_bypass(sch, true);
1682 	drain_descendants(sch);
1683 
1684 	/*
1685 	 * Here, every runnable task is guaranteed to make forward progress and
1686 	 * we can safely use blocking synchronization constructs. Actually
1687 	 * disable ops.
1688 	 */
1689 	mutex_lock(&scx_enable_mutex);
1690 	percpu_down_write(&scx_fork_rwsem);
1691 	scx_cgroup_lock();
1692 
1693 	/*
1694 	 * An enable that failed before scx_link_sched() succeeded never owned a
1695 	 * cgroup or task and won't be waited on by an ancestor's
1696 	 * drain_descendants(). Nothing to reparent and walking the tasks can
1697 	 * misbehave as the task ownership invariant (either owned by self or
1698 	 * parent) does not hold. ->sibling can't identify this case - an undone
1699 	 * link leaves it non-empty.
1700 	 */
1701 	if (!sch->linked)
1702 		goto dump;
1703 
1704 	set_cgroup_sched(sch_cgroup(sch), parent);
1705 
1706 	/*
1707 	 * Return the subtree's cgroups before re-homing tasks so that any
1708 	 * ops.init_task() on $parent only sees cgroups it has initialized.
1709 	 */
1710 	scx_cgroup_return_subtree(sch);
1711 
1712 	scx_task_iter_start(&sti, sch->cgrp);
1713 	while ((p = scx_task_iter_next_locked(&sti))) {
1714 		struct rq *rq;
1715 		struct rq_flags rf;
1716 
1717 		/* filter out duplicate visits */
1718 		if (scx_task_on_sched(parent, p))
1719 			continue;
1720 
1721 		/*
1722 		 * By the time control reaches here, all linked descendant
1723 		 * schedulers should have been disabled.
1724 		 */
1725 		WARN_ON_ONCE(!scx_task_on_sched(sch, p));
1726 
1727 		/*
1728 		 * @p is pinned by the iter: css_task_iter_next() takes a
1729 		 * reference and holds it until the next iter_next() call, so
1730 		 * @p->usage is guaranteed > 0.
1731 		 */
1732 		get_task_struct(p);
1733 
1734 		scx_task_iter_unlock(&sti);
1735 
1736 		/*
1737 		 * $p is READY or ENABLED on @sch. Initialize for $parent,
1738 		 * disable and exit from @sch, and then switch over to $parent.
1739 		 *
1740 		 * If a task fails to initialize for $parent, the only available
1741 		 * action is disabling $parent too. While this allows disabling
1742 		 * of a child sched to cause the parent scheduler to fail, the
1743 		 * failure can only originate from ops.init_task() of the
1744 		 * parent. A child can't directly affect the parent through its
1745 		 * own failures.
1746 		 */
1747 		ret = __scx_init_task(parent, p, NULL, false);
1748 		if (ret) {
1749 			scx_fail_parent(sch, p, ret);
1750 			put_task_struct(p);
1751 			break;
1752 		}
1753 
1754 		rq = task_rq_lock(p, &rf);
1755 
1756 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
1757 			/*
1758 			 * sched_ext_dead() raced us between __scx_init_task()
1759 			 * and this rq lock and ran exit_task() on @sch (the
1760 			 * sched @p was on at that point), not on $parent.
1761 			 * $parent's just-completed init is owed an exit_task()
1762 			 * and we issue it here.
1763 			 */
1764 			scx_sub_init_cancel_task(parent, p);
1765 			task_rq_unlock(rq, p, &rf);
1766 			put_task_struct(p);
1767 			continue;
1768 		}
1769 
1770 		scx_rehome_task(parent, p);
1771 
1772 		task_rq_unlock(rq, p, &rf);
1773 		put_task_struct(p);
1774 	}
1775 	scx_task_iter_stop(&sti);
1776 
1777 dump:
1778 	scx_disable_dump(sch);
1779 
1780 	scx_cgroup_unlock();
1781 	percpu_up_write(&scx_fork_rwsem);
1782 
1783 	scx_ops_cid_sched_updated_disable(sch);
1784 
1785 	/*
1786 	 * All tasks are moved off of @sch but there may still be on-going
1787 	 * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use
1788 	 * the expedited version as ancestors may be waiting in bypass mode.
1789 	 * Also, tell the parent that there is no need to keep running bypass
1790 	 * DSQs for us.
1791 	 */
1792 	synchronize_rcu_expedited();
1793 	scx_disable_bypass_dsp(sch);
1794 
1795 	scx_unlink_sched(sch);
1796 
1797 	/*
1798 	 * The parent restores what it delegated in ops.sub_detach(). @sch must
1799 	 * hold no caps by then.
1800 	 */
1801 	clear_all_caps(sch);
1802 
1803 	mutex_unlock(&scx_enable_mutex);
1804 
1805 	/*
1806 	 * @sch is now unlinked from the parent's children list. Notify and call
1807 	 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called
1808 	 * after unlinking and releasing all locks. See scx_claim_exit().
1809 	 */
1810 	wake_up_all(&scx_unlink_waitq);
1811 
1812 	if (parent->ops.sub_detach && sch->sub_attached) {
1813 		struct scx_sub_detach_args sub_detach_args = {
1814 			.ops = &sch->ops,
1815 			.cgroup_path = sch->cgrp_path,
1816 		};
1817 		SCX_CALL_OP(parent, sub_detach, NULL,
1818 			    &sub_detach_args);
1819 	}
1820 
1821 	scx_log_sched_disable(sch);
1822 
1823 	if (sch->ops.exit)
1824 		SCX_CALL_OP(sch, exit, NULL, sch->exit_info);
1825 
1826 	/*
1827 	 * @sch's non-ops programs such as timers and tracers can fire after
1828 	 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from
1829 	 * resolving to @sch and drain in-flight resolvers.
1830 	 */
1831 	WRITE_ONCE(sch->dead, true);
1832 	synchronize_rcu();
1833 
1834 	if (sch->sub_kset)
1835 		kobject_del(&sch->sub_kset->kobj);
1836 	/* not added if enable failed before scx_sched_sysfs_add() */
1837 	if (sch->kobj.state_in_sysfs)
1838 		kobject_del(&sch->kobj);
1839 }
1840 
1841 /* verify that a scheduler can be attached to @cgrp and return the parent */
1842 static struct scx_sched *find_parent_sched(struct cgroup *cgrp)
1843 {
1844 	struct scx_sched *parent = scx_cgroup_sched(cgrp);
1845 	struct scx_sched *pos;
1846 
1847 	lockdep_assert_held(&scx_sched_lock);
1848 
1849 	/* can't attach twice to the same cgroup */
1850 	if (parent->cgrp == cgrp)
1851 		return ERR_PTR(-EBUSY);
1852 
1853 	/* does $parent allow sub-scheds? */
1854 	if (!parent->ops.sub_attach)
1855 		return ERR_PTR(-EOPNOTSUPP);
1856 
1857 	/* can't insert between $parent and its exiting children */
1858 	list_for_each_entry(pos, &parent->children, sibling)
1859 		if (cgroup_is_descendant(pos->cgrp, cgrp))
1860 			return ERR_PTR(-EBUSY);
1861 
1862 	return parent;
1863 }
1864 
1865 static bool assert_task_ready_or_enabled(struct task_struct *p)
1866 {
1867 	u32 state = scx_get_task_state(p);
1868 
1869 	switch (state) {
1870 	case SCX_TASK_READY:
1871 	case SCX_TASK_ENABLED:
1872 		return true;
1873 	default:
1874 		WARN_ONCE(true, "sched_ext: Invalid task state %d for %s[%d] during enabling sub sched",
1875 			  state, p->comm, p->pid);
1876 		return false;
1877 	}
1878 }
1879 
1880 void scx_sub_enable_workfn(struct kthread_work *work)
1881 {
1882 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
1883 	struct sched_ext_ops *ops = cmd->ops;
1884 	struct cgroup *cgrp;
1885 	struct scx_sched *parent, *sch;
1886 	struct scx_task_iter sti;
1887 	struct task_struct *p;
1888 	s32 i, ret;
1889 
1890 	mutex_lock(&scx_enable_mutex);
1891 
1892 	if (!scx_enabled()) {
1893 		ret = -ENODEV;
1894 		goto out_unlock;
1895 	}
1896 
1897 	/* See scx_root_enable_workfn() for the @ops->priv check. */
1898 	if (rcu_access_pointer(ops->priv)) {
1899 		ret = -EBUSY;
1900 		goto out_unlock;
1901 	}
1902 
1903 	cgrp = cgroup_get_from_id(ops->sub_cgroup_id);
1904 	if (IS_ERR(cgrp)) {
1905 		ret = PTR_ERR(cgrp);
1906 		goto out_unlock;
1907 	}
1908 
1909 	raw_spin_lock_irq(&scx_sched_lock);
1910 	parent = find_parent_sched(cgrp);
1911 	if (IS_ERR(parent)) {
1912 		raw_spin_unlock_irq(&scx_sched_lock);
1913 		ret = PTR_ERR(parent);
1914 		goto out_put_cgrp;
1915 	}
1916 	kobject_get(&parent->kobj);
1917 	raw_spin_unlock_irq(&scx_sched_lock);
1918 
1919 	/*
1920 	 * Flip the hot-path gates before ops->priv is published - the sub's
1921 	 * programs can e.g. kick cpus from that point on. The matching dec is
1922 	 * at the end of scx_sched_free_rcu_work().
1923 	 */
1924 	static_branch_inc(&__scx_has_subs);
1925 
1926 	/* scx_alloc_and_add_sched() consumes @cgrp whether it succeeds or not */
1927 	sch = scx_alloc_and_add_sched(cmd, cgrp, parent);
1928 	kobject_put(&parent->kobj);
1929 	if (IS_ERR(sch)) {
1930 		static_branch_dec(&__scx_has_subs);
1931 		ret = PTR_ERR(sch);
1932 		goto out_unlock;
1933 	}
1934 
1935 	/*
1936 	 * Validate before scx_link_sched() publishes @sch, so an invalid sub
1937 	 * never becomes visible with an unallocated pshard.
1938 	 */
1939 	ret = scx_validate_ops(sch, ops);
1940 	if (ret)
1941 		goto err_disable;
1942 
1943 	scx_rescue_check_timeout(sch);
1944 
1945 	/*
1946 	 * Allocate pshard[] before scx_link_sched() publishes @sch into the
1947 	 * parent's RCU children list. A concurrent revoke walking the tree
1948 	 * would otherwise dereference sch->pshard[si] while it's still NULL.
1949 	 * Unlike the root path, the cid shard layout is stable at this point.
1950 	 *
1951 	 * scx_alloc_pshards() skips allocation when @sch's arena pool isn't
1952 	 * initialized, so scx_arena_pool_init() must run first.
1953 	 */
1954 	ret = scx_arena_pool_init(sch);
1955 	if (ret)
1956 		goto err_disable;
1957 
1958 	ret = scx_alloc_pshards(sch);
1959 	if (ret)
1960 		goto err_disable;
1961 
1962 	/*
1963 	 * Bypass before @sch is linked and grants can reach it. The parent's
1964 	 * delivery advances reported_ecaps, so a sync consumed before @sch's
1965 	 * ops are registered would reach the parent and never be replayed to
1966 	 * @sch. While bypassed, the syncs are consumed without a delivery and
1967 	 * replayed to both at unbypass.
1968 	 */
1969 	scx_bypass(sch, true);
1970 
1971 	ret = scx_link_sched(sch);
1972 	if (ret)
1973 		goto err_disable;
1974 
1975 	ret = scx_sched_sysfs_add(sch);
1976 	if (ret)
1977 		goto err_disable;
1978 
1979 	if (sch->level >= SCX_SUB_MAX_DEPTH) {
1980 		scx_error(sch, "max nesting depth %d violated",
1981 			  SCX_SUB_MAX_DEPTH);
1982 		ret = -EINVAL;
1983 		goto err_disable;
1984 	}
1985 
1986 	scoped_guard(cpus_read_lock) {
1987 		ret = scx_alloc_kern_arena_objs(sch);
1988 		if (ret)
1989 			goto err_disable;
1990 	}
1991 
1992 	if (sch->ops.init) {
1993 		ret = SCX_CALL_OP_RET(sch, init, NULL);
1994 		if (ret) {
1995 			ret = scx_ops_sanitize_err(sch, "init", ret);
1996 			scx_error(sch, "ops.init() failed (%d)", ret);
1997 			goto err_disable;
1998 		}
1999 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
2000 	}
2001 
2002 	struct scx_sub_attach_args sub_attach_args = {
2003 		.ops = &sch->ops,
2004 		.cgroup_path = sch->cgrp_path,
2005 	};
2006 
2007 	ret = SCX_CALL_OP_RET(parent, sub_attach, NULL,
2008 			      &sub_attach_args);
2009 	if (ret) {
2010 		ret = scx_ops_sanitize_err(sch, "sub_attach", ret);
2011 		scx_error(sch, "parent rejected (%d)", ret);
2012 		goto err_disable;
2013 	}
2014 	sch->sub_attached = true;
2015 
2016 	for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++)
2017 		if (((void (**)(void))ops)[i])
2018 			set_bit(i, sch->has_op);
2019 
2020 	scx_ops_cid_sched_updated_enable(sch);
2021 
2022 	percpu_down_write(&scx_fork_rwsem);
2023 	scx_cgroup_lock();
2024 
2025 	/*
2026 	 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see
2027 	 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down.
2028 	 */
2029 	set_cgroup_sched(sch_cgroup(sch), sch);
2030 	if (!(cgrp->self.flags & CSS_ONLINE)) {
2031 		scx_error(sch, "cgroup is not online");
2032 		ret = -ENODEV;
2033 		goto err_unlock_and_disable;
2034 	}
2035 
2036 	/*
2037 	 * Take over the subtree's cgroups before any task is claimed,
2038 	 * mirroring root enable's cgroups-before-tasks order.
2039 	 */
2040 	ret = scx_cgroup_claim_subtree(sch);
2041 	if (ret)
2042 		goto err_unlock_and_disable;
2043 
2044 	/*
2045 	 * Initialize tasks for the new child $sch without exiting them for
2046 	 * $parent so that the tasks can always be reverted back to $parent
2047 	 * sched on child init failure.
2048 	 */
2049 	WARN_ON_ONCE(scx_enabling_sub_sched);
2050 	scx_enabling_sub_sched = sch;
2051 
2052 	scx_task_iter_start(&sti, sch->cgrp);
2053 	while ((p = scx_task_iter_next_locked(&sti))) {
2054 		struct rq *rq;
2055 		struct rq_flags rf;
2056 
2057 		/*
2058 		 * Task iteration may visit the same task twice when racing
2059 		 * against exiting. Use %SCX_TASK_SUB_INIT to mark tasks which
2060 		 * finished __scx_init_task() and skip if set.
2061 		 *
2062 		 * A task may exit and get freed between __scx_init_task()
2063 		 * completion and scx_enable_task(). In such cases,
2064 		 * scx_disable_and_exit_task() must exit the task for both the
2065 		 * parent and child scheds.
2066 		 */
2067 		if (p->scx.flags & SCX_TASK_SUB_INIT)
2068 			continue;
2069 
2070 		/* @p is pinned by the iter; see scx_sub_disable() */
2071 		get_task_struct(p);
2072 
2073 		if (!assert_task_ready_or_enabled(p)) {
2074 			ret = -EINVAL;
2075 			goto abort;
2076 		}
2077 
2078 		scx_task_iter_unlock(&sti);
2079 
2080 		/*
2081 		 * As $p is still on $parent, it can't be transitioned to INIT.
2082 		 * Let's worry about task state later. Use __scx_init_task().
2083 		 */
2084 		ret = __scx_init_task(sch, p, NULL, false);
2085 		if (ret)
2086 			goto abort;
2087 
2088 		rq = task_rq_lock(p, &rf);
2089 
2090 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
2091 			/*
2092 			 * sched_ext_dead() raced us between __scx_init_task()
2093 			 * and this rq lock and ran exit_task() on $parent (the
2094 			 * sched @p was on at that point), not on @sch. @sch's
2095 			 * just-completed init is owed an exit_task() and we
2096 			 * issue it here.
2097 			 */
2098 			scx_sub_init_cancel_task(sch, p);
2099 			task_rq_unlock(rq, p, &rf);
2100 			put_task_struct(p);
2101 			continue;
2102 		}
2103 
2104 		p->scx.flags |= SCX_TASK_SUB_INIT;
2105 		task_rq_unlock(rq, p, &rf);
2106 
2107 		put_task_struct(p);
2108 	}
2109 	scx_task_iter_stop(&sti);
2110 
2111 	/*
2112 	 * All tasks are prepped. Disable/exit tasks for $parent and enable for
2113 	 * the new @sch.
2114 	 */
2115 	scx_task_iter_start(&sti, sch->cgrp);
2116 	while ((p = scx_task_iter_next_locked(&sti))) {
2117 		/*
2118 		 * Use clearing of %SCX_TASK_SUB_INIT to detect and skip
2119 		 * duplicate iterations.
2120 		 */
2121 		if (!(p->scx.flags & SCX_TASK_SUB_INIT))
2122 			continue;
2123 
2124 		scx_prepare_task_sched_change(p);
2125 		scoped_guard (sched_change, p,
2126 			      DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK) {
2127 			/*
2128 			 * $p must be either READY or ENABLED. If ENABLED,
2129 			 * __scx_disabled_and_exit_task() first disables and
2130 			 * makes it READY. However, after exiting $p, it will
2131 			 * leave $p as READY.
2132 			 */
2133 			assert_task_ready_or_enabled(p);
2134 			__scx_disable_and_exit_task(parent, p);
2135 
2136 			/*
2137 			 * $p is now only initialized for @sch and READY, which
2138 			 * is what we want. Assign it to @sch and, if it's on
2139 			 * the ext class, enable. A non-ext task, possible under
2140 			 * an %SCX_OPS_SWITCH_PARTIAL root, stays READY and is
2141 			 * enabled by switching_to_scx() if it switches over.
2142 			 */
2143 			scx_set_task_sched(p, sch);
2144 			if (p->sched_class == &ext_sched_class)
2145 				scx_enable_task(sch, p);
2146 
2147 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
2148 		}
2149 	}
2150 	scx_task_iter_stop(&sti);
2151 
2152 	scx_enabling_sub_sched = NULL;
2153 
2154 	scx_cgroup_unlock();
2155 	percpu_up_write(&scx_fork_rwsem);
2156 
2157 	scx_bypass(sch, false);
2158 
2159 	/* @sch is enabled; deliver any caps owed since its sub_attach() */
2160 	scx_sub_seed_caps(sch);
2161 
2162 	pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name);
2163 	kobject_uevent(&sch->kobj, KOBJ_ADD);
2164 	ret = 0;
2165 	goto out_unlock;
2166 
2167 out_put_cgrp:
2168 	cgroup_put(cgrp);
2169 out_unlock:
2170 	mutex_unlock(&scx_enable_mutex);
2171 	cmd->ret = ret;
2172 	return;
2173 
2174 abort:
2175 	put_task_struct(p);
2176 	scx_task_iter_stop(&sti);
2177 
2178 	/*
2179 	 * Undo __scx_init_task() for tasks we marked. scx_enable_task() never
2180 	 * ran for @sch on them, so calling scx_disable_task() here would invoke
2181 	 * ops.disable() without a matching ops.enable(). scx_enabling_sub_sched
2182 	 * must stay set until SUB_INIT is cleared from every marked task -
2183 	 * scx_disable_and_exit_task() reads it when a task exits concurrently.
2184 	 */
2185 	scx_task_iter_start(&sti, sch->cgrp);
2186 	while ((p = scx_task_iter_next_locked(&sti))) {
2187 		if (p->scx.flags & SCX_TASK_SUB_INIT) {
2188 			scx_sub_init_cancel_task(sch, p);
2189 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
2190 		}
2191 	}
2192 	scx_task_iter_stop(&sti);
2193 	scx_enabling_sub_sched = NULL;
2194 err_unlock_and_disable:
2195 	/* we'll soon enter disable path, keep bypass on */
2196 	scx_cgroup_unlock();
2197 	percpu_up_write(&scx_fork_rwsem);
2198 err_disable:
2199 	mutex_unlock(&scx_enable_mutex);
2200 	/*
2201 	 * Some enable failures only return an errno (e.g. -ENOMEM from an
2202 	 * allocation) without calling scx_error(). Record it so
2203 	 * scx_flush_disable_work() runs the disable and ops.exit() fires.
2204 	 */
2205 	scx_error(sch, "scx_sub_enable() failed (%d)", ret);
2206 	scx_flush_disable_work(sch);
2207 	cmd->ret = 0;
2208 }
2209 
2210 /**
2211  * scx_cgroup_task_migrating - Prepare a task for a cgroup migration
2212  * @ctx: migration being prepared
2213  *
2214  * A task's sched must match its cgroup's owner, so a migration that crosses a
2215  * sched boundary re-homes the task once committed. Run the fallible part here,
2216  * before the migration commits: initialize the task for the destination sched.
2217  * A rejection fails the cgroup.procs write.
2218  */
2219 static s32 scx_cgroup_task_migrating(struct cgroup_task_migrate_ctx *ctx)
2220 {
2221 	struct task_struct *p = ctx->task;
2222 	struct scx_sched *to;
2223 	int ret;
2224 
2225 	/*
2226 	 * Cleared under scx_cgroup_lock() before root disable starts tearing
2227 	 * down tasks. As cgroup_mutex is held, a set flag guarantees that the
2228 	 * teardown loop is not running concurrently.
2229 	 */
2230 	if (!scx_cgroup_enabled)
2231 		return NOTIFY_OK;
2232 
2233 	to = scx_cgroup_sched(ctx->dst_dcgrp);
2234 	if (scx_task_on_sched(to, p))
2235 		return NOTIFY_OK;
2236 
2237 	ret = __scx_init_task(to, p, ctx->dst_dcgrp, false);
2238 	if (ret)
2239 		return notifier_from_errno(ret);
2240 
2241 	return NOTIFY_OK;
2242 }
2243 
2244 /**
2245  * scx_cgroup_task_migrated - Re-home a task that changed cgroups
2246  * @ctx: committed migration
2247  *
2248  * Move the task to its new cgroup's sched, which scx_cgroup_task_migrating()
2249  * already initialized it for. Can't fail.
2250  *
2251  * This is safe against all phases of the destination sched's destruction. A
2252  * disable resets cgroup ownership to the parent and re-homes tasks in one
2253  * scx_cgroup_lock() section. If that section already ran, the destination would
2254  * be the parent. Otherwise, the re-home loop is still ahead and guaranteed to
2255  * visit the task, now in the destination cgroup.
2256  */
2257 static void scx_cgroup_task_migrated(struct cgroup_task_migrate_ctx *ctx)
2258 {
2259 	struct task_struct *p = ctx->task;
2260 	struct scx_sched *to;
2261 	struct rq *rq;
2262 	struct rq_flags rf;
2263 
2264 	if (!scx_cgroup_enabled)
2265 		return;
2266 
2267 	to = scx_cgroup_sched(ctx->dst_dcgrp);
2268 	if (scx_task_on_sched(to, p))
2269 		return;
2270 
2271 	rq = task_rq_lock(p, &rf);
2272 	scx_rehome_task(to, p);
2273 	task_rq_unlock(rq, p, &rf);
2274 }
2275 
2276 /**
2277  * scx_cgroup_task_migrate_canceled - Undo migration preparation
2278  * @ctx: canceled migration
2279  *
2280  * The migration failed after scx_cgroup_task_migrating() initialized the task
2281  * for the destination sched. The task stays on its current sched in the source
2282  * cgroup. Undo the destination's init.
2283  */
2284 static void scx_cgroup_task_migrate_canceled(struct cgroup_task_migrate_ctx *ctx)
2285 {
2286 	struct task_struct *p = ctx->task;
2287 	struct scx_sched *to;
2288 	struct rq *rq;
2289 	struct rq_flags rf;
2290 
2291 	if (!scx_cgroup_enabled)
2292 		return;
2293 
2294 	to = scx_cgroup_sched(ctx->dst_dcgrp);
2295 	if (scx_task_on_sched(to, p))
2296 		return;
2297 
2298 	rq = task_rq_lock(p, &rf);
2299 	scx_sub_init_cancel_task(to, p);
2300 	task_rq_unlock(rq, p, &rf);
2301 }
2302 
2303 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb,
2304 				      unsigned long action, void *data)
2305 {
2306 	struct cgroup *cgrp = data;
2307 	struct cgroup *parent = cgroup_parent(cgrp);
2308 	struct scx_sched *sch;
2309 
2310 	if (!cgroup_on_dfl(cgrp))
2311 		return NOTIFY_OK;
2312 
2313 	switch (action) {
2314 	case CGROUP_LIFETIME_ONLINE:
2315 		/* inherit ->scx_sched from $parent */
2316 		if (parent)
2317 			rcu_assign_pointer(cgrp->scx_sched, scx_cgroup_sched(parent));
2318 		break;
2319 	case CGROUP_LIFETIME_OFFLINE:
2320 		/* if there is a sched attached, shoot it down */
2321 		sch = scx_cgroup_sched(cgrp);
2322 		if (sch && sch->cgrp == cgrp)
2323 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
2324 				 SCX_ECODE_RSN_CGROUP_OFFLINE,
2325 				 "cgroup %llu going offline", cgroup_id(cgrp));
2326 		break;
2327 	}
2328 
2329 	return NOTIFY_OK;
2330 }
2331 
2332 static struct notifier_block scx_cgroup_lifetime_nb = {
2333 	.notifier_call = scx_cgroup_lifetime_notify,
2334 };
2335 
2336 static s32 scx_cgroup_task_notify(struct notifier_block *nb,
2337 				  unsigned long action, void *data)
2338 {
2339 	struct cgroup_task_migrate_ctx *ctx = data;
2340 
2341 	switch (action) {
2342 	case CGROUP_TASK_MIGRATING:
2343 		return scx_cgroup_task_migrating(ctx);
2344 	case CGROUP_TASK_MIGRATED:
2345 		scx_cgroup_task_migrated(ctx);
2346 		break;
2347 	case CGROUP_TASK_MIGRATE_CANCELED:
2348 		scx_cgroup_task_migrate_canceled(ctx);
2349 		break;
2350 	}
2351 
2352 	return NOTIFY_OK;
2353 }
2354 
2355 static struct notifier_block scx_cgroup_task_nb = {
2356 	.notifier_call = scx_cgroup_task_notify,
2357 };
2358 
2359 static s32 __init scx_cgroup_notifier_init(void)
2360 {
2361 	s32 ret;
2362 
2363 	ret = blocking_notifier_chain_register(&cgroup_lifetime_notifier,
2364 					       &scx_cgroup_lifetime_nb);
2365 	if (ret)
2366 		return ret;
2367 
2368 	return blocking_notifier_chain_register(&cgroup_task_notifier,
2369 						&scx_cgroup_task_nb);
2370 }
2371 core_initcall(scx_cgroup_notifier_init);
2372 
2373 static void scx_pstack_recursion(struct bpf_prog *prog, const char *op)
2374 {
2375 	struct scx_sched *sch;
2376 
2377 	guard(rcu)();
2378 	sch = scx_prog_sched(prog->aux);
2379 	if (unlikely(!sch))
2380 		return;
2381 
2382 	scx_error(sch, "%s recursion detected", op);
2383 }
2384 
2385 void scx_pstack_recursion_on_dispatch(struct bpf_prog *prog)
2386 {
2387 	scx_pstack_recursion(prog, "dispatch");
2388 }
2389 
2390 void scx_pstack_recursion_on_caps_updated(struct bpf_prog *prog)
2391 {
2392 	scx_pstack_recursion(prog, "sub_caps_updated");
2393 }
2394 
2395 __bpf_kfunc_start_defs();
2396 
2397 /**
2398  * scx_bpf_sub_dispatch - Trigger dispatching on a child scheduler
2399  * @cgroup_id: cgroup ID of the child scheduler to dispatch
2400  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
2401  *
2402  * Allows a parent scheduler to trigger dispatching on one of its direct
2403  * child schedulers. The child scheduler runs its dispatch operation to
2404  * move tasks from dispatch queues to the local runqueue.
2405  *
2406  * Returns: true on success, false if cgroup_id is invalid, not a direct
2407  * child, or caller lacks dispatch permission.
2408  */
2409 __bpf_kfunc bool scx_bpf_sub_dispatch(u64 cgroup_id, const struct bpf_prog_aux *aux)
2410 {
2411 	struct rq *rq = scx_locked_rq();
2412 	struct scx_sched *parent, *child;
2413 
2414 	guard(rcu)();
2415 	parent = scx_prog_sched(aux);
2416 	if (unlikely(!parent))
2417 		return false;
2418 
2419 	child = scx_find_sub_sched(cgroup_id);
2420 
2421 	if (unlikely(!child))
2422 		return false;
2423 
2424 	if (unlikely(scx_parent(child) != parent)) {
2425 		scx_error(parent, "trying to dispatch a distant sub-sched on cgroup %llu",
2426 			  cgroup_id);
2427 		return false;
2428 	}
2429 
2430 	/*
2431 	 * Skip a child that does not effectively hold the base cap on this cpu:
2432 	 * its inserts would only be rejected. ecaps are synced at the top of
2433 	 * dispatch_one() before dispatch, so this reflects the in-effect state.
2434 	 */
2435 	if (scx_missing_caps(child, cpu_of(rq), SCX_CAP_BASE))
2436 		return false;
2437 
2438 	return scx_dispatch_sched(child, rq, rq->scx.sub_dispatch_prev, true) !=
2439 		SCX_DSP_NONE;
2440 }
2441 
2442 /* Validate common inputs. On success, *parent_out and *child_out are set. */
2443 static s32 sub_cap_preamble(u64 cgroup_id, u64 caps, const struct bpf_prog_aux *aux,
2444 			    struct scx_sched **parent_out, struct scx_sched **child_out)
2445 {
2446 	struct scx_sched *parent, *child;
2447 
2448 	parent = scx_prog_sched(aux);
2449 	if (unlikely(!parent))
2450 		return -ENODEV;
2451 
2452 	if (!scx_kf_allowed_ctx(parent))
2453 		return -EDEADLK;
2454 
2455 	if (!scx_is_cid_type()) {
2456 		scx_error(parent, "sub-cap kfuncs require a cid-form scheduler");
2457 		return -EOPNOTSUPP;
2458 	}
2459 
2460 	child = scx_find_sub_sched(cgroup_id);
2461 	if (unlikely(!child))
2462 		return -ENODEV;
2463 
2464 	if (unlikely(scx_parent(child) != parent)) {
2465 		scx_error(parent, "%s: sub-%llu is not a direct child",
2466 			  parent->cgrp_path, cgroup_id);
2467 		return -EINVAL;
2468 	}
2469 
2470 	if (unlikely(caps & ~__SCX_CAP_ALL)) {
2471 		scx_error(parent, "invalid caps 0x%llx", caps);
2472 		return -EINVAL;
2473 	}
2474 
2475 	*parent_out = parent;
2476 	*child_out = child;
2477 	return 0;
2478 }
2479 
2480 /**
2481  * scx_bpf_sub_grant - Grant @caps on a cmask's cids to a direct child
2482  * @cgroup_id: cgroup id of the direct child sub-sched
2483  * @caps: bitmask of SCX_CAP_* to grant
2484  * @cmask__arena: cid cmask to grant @caps on
2485  * @denied_out__arena__nullable: optional cmask accumulating refused cids
2486  * @aux: implicit BPF argument
2487  *
2488  * A cid in @cmask__arena is granted to the child only if the parent holds every
2489  * requested cap on it. Refused cids are OR'd into the denied mask when
2490  * provided. Refusals outside the denied mask's range are not recorded.
2491  *
2492  * All-or-nothing keeps the caller-visible result binary per cid, so the denied
2493  * mask is one mask to interpret rather than a per-cap matrix.
2494  *
2495  * Return 0 on full success, -EPERM if any cid was refused, -ENODEV if the child
2496  * is gone or being disabled, or a negative errno on other failures.
2497  */
2498 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps,
2499 				  const struct scx_cmask *cmask__arena,
2500 				  struct scx_cmask *denied_out__arena__nullable,
2501 				  const struct bpf_prog_aux *aux)
2502 {
2503 	struct scx_cmask_ref ref, denied_ref;
2504 	struct scx_sched *parent, *child;
2505 	bool any_denied = false;
2506 	LIST_HEAD(to_deliver);
2507 	s32 si, ret;
2508 
2509 	guard(irqsave)();
2510 
2511 	ret = sub_cap_preamble(cgroup_id, caps, aux, &parent, &child);
2512 	if (ret)
2513 		return ret;
2514 
2515 	ret = scx_cmask_ref_init(parent, cmask__arena, &ref);
2516 	if (ret) {
2517 		scx_error(parent, "invalid cmask (%d)", ret);
2518 		return ret;
2519 	}
2520 
2521 	if (denied_out__arena__nullable) {
2522 		ret = scx_cmask_ref_init(parent, denied_out__arena__nullable, &denied_ref);
2523 		if (ret) {
2524 			scx_error(parent, "invalid denied_out (%d)", ret);
2525 			return ret;
2526 		}
2527 	}
2528 
2529 	/* apply the grant one shard at a time */
2530 	for (si = ref.shard_first; si < ref.shard_end; si++) {
2531 		SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS);
2532 		struct scx_pshard *pps = parent->pshard[si];
2533 		struct scx_pshard *cps = child->pshard[si];
2534 		u64 granted_caps = 0;
2535 		u32 cap_bit;
2536 
2537 		scx_cmask_ref_shard(&ref, si, slice);
2538 		if (scx_cmask_empty(slice))
2539 			continue;
2540 
2541 		SCX_CMASK_DEFINE_SHARD(granted_cids, slice->base, slice->nr_cids);
2542 		SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids);
2543 		SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids);
2544 
2545 		scx_cmask_copy(granted_cids, slice);
2546 
2547 		scoped_guard (raw_spinlock, &pps->lock) {
2548 			guard(raw_spinlock_nested)(&cps->lock);
2549 
2550 			/* the child is being disabled, see clear_all_caps() */
2551 			if (unlikely(READ_ONCE(child->aborting))) {
2552 				ret = -ENODEV;
2553 				goto out;
2554 			}
2555 
2556 			/*
2557 			 * Narrow granted_cids to cids the parent holds every
2558 			 * requested cap on. All-or-nothing per cid.
2559 			 */
2560 			scx_for_each_cap_bit(cap_bit, caps)
2561 				scx_cmask_and(granted_cids, &pps->caps[cap_bit].cmask);
2562 
2563 			/*
2564 			 * For each requested cap, fold the newly-set cids into
2565 			 * the child and accumulate the delta.
2566 			 */
2567 			scx_for_each_cap_bit(cap_bit, caps) {
2568 				struct scx_cmask *ccm = &cps->caps[cap_bit].cmask;
2569 
2570 				scx_cmask_copy(delta, granted_cids);
2571 				scx_cmask_andnot(delta, ccm);
2572 				if (scx_cmask_empty(delta))
2573 					continue;
2574 
2575 				scx_cmask_or(ccm, delta);
2576 				scx_cmask_or(changed_cids, delta);
2577 				granted_caps |= BIT_U64(cap_bit);
2578 			}
2579 
2580 			if (granted_caps) {
2581 				s32 cid;
2582 
2583 				caps_updated_record(cps, changed_cids, granted_caps,
2584 						    &to_deliver);
2585 				/*
2586 				 * The sync arms an update_idle() re-notify if
2587 				 * the cid gains baseline access, so the holder
2588 				 * learns of an already-idle cid.
2589 				 */
2590 				scx_cmask_for_each_cid(cid, changed_cids)
2591 					queue_sync_ecaps(child, cid);
2592 			}
2593 		}
2594 
2595 		/* record cids that didn't make it into the denied mask */
2596 		if (!scx_cmask_subset(slice, granted_cids)) {
2597 			any_denied = true;
2598 			if (denied_out__arena__nullable) {
2599 				SCX_CMASK_DEFINE_SHARD(denied, slice->base, slice->nr_cids);
2600 
2601 				scx_cmask_copy(denied, slice);
2602 				scx_cmask_andnot(denied, granted_cids);
2603 				scx_cmask_ref_or(&denied_ref, denied);
2604 			}
2605 		}
2606 	}
2607 
2608 	ret = any_denied ? -EPERM : 0;
2609 out:
2610 	caps_updated_deliver(&to_deliver);
2611 	return ret;
2612 }
2613 
2614 /**
2615  * scx_bpf_sub_revoke - Revoke @caps on a cmask's cids from a direct child
2616  * @cgroup_id: cgroup id of the direct child sub-sched
2617  * @caps: bitmask of SCX_CAP_* to revoke
2618  * @cmask__arena: cid cmask to revoke @caps on
2619  * @aux: implicit BPF argument
2620  *
2621  * Clear @caps bits on @cmask__arena from the child named by @cgroup_id and all
2622  * its descendants. The origin parent's pshard lock is held across the subtree
2623  * walk so a concurrent grant from the origin parent observes the revoked state.
2624  */
2625 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps,
2626 				    const struct scx_cmask *cmask__arena,
2627 				    const struct bpf_prog_aux *aux)
2628 {
2629 	struct scx_cmask_ref ref;
2630 	struct scx_sched *parent, *child, *pos;
2631 	LIST_HEAD(to_deliver);
2632 	s32 si, ret;
2633 
2634 	guard(irqsave)();
2635 
2636 	if (sub_cap_preamble(cgroup_id, caps, aux, &parent, &child))
2637 		return;
2638 
2639 	ret = scx_cmask_ref_init(parent, cmask__arena, &ref);
2640 	if (ret) {
2641 		scx_error(parent, "invalid cmask (%d)", ret);
2642 		return;
2643 	}
2644 
2645 	/* per-shard, walk child's subtree and clear @caps */
2646 	for (si = ref.shard_first; si < ref.shard_end; si++) {
2647 		SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS);
2648 
2649 		scx_cmask_ref_shard(&ref, si, slice);
2650 		if (scx_cmask_empty(slice))
2651 			continue;
2652 
2653 		/*
2654 		 * Pre-order with subtree skip: a descendant that cleared
2655 		 * nothing means no descendant of it can hold @caps on these
2656 		 * cids either.
2657 		 */
2658 		guard(raw_spinlock)(&parent->pshard[si]->lock);
2659 		pos = scx_next_descendant_pre(NULL, child);
2660 		while (pos) {
2661 			struct scx_pshard *ps = pos->pshard[si];
2662 			SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids);
2663 			SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids);
2664 			u64 revoked_caps = 0;
2665 			u32 cap_bit;
2666 
2667 			scoped_guard (raw_spinlock_nested, &ps->lock) {
2668 				/*
2669 				 * For each cap, clear lost cids and accumulate
2670 				 * the per-cap diff for notification.
2671 				 */
2672 				scx_for_each_cap_bit(cap_bit, caps) {
2673 					struct scx_cmask *cm = &ps->caps[cap_bit].cmask;
2674 
2675 					scx_cmask_copy(delta, cm);
2676 					scx_cmask_and(delta, slice);
2677 					if (scx_cmask_empty(delta))
2678 						continue;
2679 
2680 					scx_cmask_andnot(cm, delta);
2681 					scx_cmask_or(changed_cids, delta);
2682 					revoked_caps |= BIT_U64(cap_bit);
2683 				}
2684 
2685 				if (revoked_caps) {
2686 					s32 cid;
2687 
2688 					caps_updated_record(ps, changed_cids, revoked_caps,
2689 							    &to_deliver);
2690 					scx_cmask_for_each_cid(cid, changed_cids)
2691 						queue_sync_ecaps(pos, cid);
2692 				}
2693 			}
2694 
2695 			if (revoked_caps)
2696 				pos = scx_next_descendant_pre(pos, child);
2697 			else
2698 				pos = scx_skip_subtree_pre(pos, child);
2699 		}
2700 	}
2701 
2702 	caps_updated_deliver(&to_deliver);
2703 }
2704 
2705 /**
2706  * scx_bpf_sub_caps - Read self's or a direct child's cap cmasks
2707  * @cgroup_id: 0 for self, or a direct child's cgroup id
2708  * @caps: one or more SCX_CAP_* bits
2709  * @out__arena: cmask to receive the union of @caps within its range
2710  * @aux: implicit BPF argument
2711  *
2712  * Read the cap cmasks granted on each cid for self (@cgroup_id 0) or a direct
2713  * child - the literal granted set. A sched can read only itself or a direct
2714  * child.
2715  *
2716  * Return 0, -ENODEV if @cgroup_id names no direct child, or -EINVAL on bad
2717  * inputs.
2718  */
2719 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__arena,
2720 				 const struct bpf_prog_aux *aux)
2721 {
2722 	struct scx_cmask_ref ref;
2723 	struct scx_sched *sch, *target;
2724 	struct scx_pshard **pshard;
2725 	s32 si, ret;
2726 
2727 	guard(irqsave)();
2728 
2729 	sch = scx_prog_sched(aux);
2730 	if (unlikely(!sch))
2731 		return -ENODEV;
2732 
2733 	if (!scx_is_cid_type()) {
2734 		scx_error(sch, "sub-cap kfuncs require a cid-form scheduler");
2735 		return -EOPNOTSUPP;
2736 	}
2737 
2738 	if (unlikely(caps & ~__SCX_CAP_ALL)) {
2739 		scx_error(sch, "invalid caps 0x%llx", caps);
2740 		return -EINVAL;
2741 	}
2742 
2743 	/* @cgroup_id 0 reads self, otherwise a direct child */
2744 	if (cgroup_id) {
2745 		target = scx_find_sub_sched(cgroup_id);
2746 		if (unlikely(!target))
2747 			return -ENODEV;
2748 		if (unlikely(scx_parent(target) != sch)) {
2749 			scx_error(sch, "%s: sub-%llu is not a direct child",
2750 				  sch->cgrp_path, cgroup_id);
2751 			return -EINVAL;
2752 		}
2753 	} else {
2754 		target = sch;
2755 	}
2756 
2757 	/*
2758 	 * The target's caps storage may not be set up yet (e.g. a self-read
2759 	 * during ops.init_cids()). Pairs with the publish in
2760 	 * scx_alloc_pshards(): a non-NULL pshard has every element set and the
2761 	 * acquire also orders the cid table reads below against it.
2762 	 */
2763 	pshard = smp_load_acquire(&target->pshard);
2764 	if (unlikely(!pshard)) {
2765 		scx_error(sch, "scx_bpf_sub_caps() called before caps storage is initialized");
2766 		return -ENODEV;
2767 	}
2768 
2769 	ret = scx_cmask_ref_init(sch, out__arena, &ref);
2770 	if (ret) {
2771 		scx_error(sch, "invalid out (%d)", ret);
2772 		return ret;
2773 	}
2774 
2775 	for (si = ref.shard_first; si < ref.shard_end; si++) {
2776 		const struct scx_cid_shard *shard =
2777 			&rcu_dereference_all(scx_cid_shard_ranges)[si];
2778 		SCX_CMASK_DEFINE_SHARD(local_out, shard->base_cid, shard->nr_cids);
2779 		u32 cap_bit;
2780 
2781 		scx_for_each_cap_bit(cap_bit, caps)
2782 			scx_cmask_or(local_out, &pshard[si]->caps[cap_bit].cmask);
2783 		scx_cmask_ref_copy(&ref, local_out);
2784 	}
2785 	return 0;
2786 }
2787 
2788 /**
2789  * scx_bpf_sub_kill_bstr - Kill a direct child sub-scheduler
2790  * @cgroup_id: cgroup id of the direct child to kill
2791  * @fmt: reason message format string
2792  * @data: format string parameters packaged using ___bpf_fill() macro
2793  * @data__sz: @data len, must end in '__sz' for the verifier
2794  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
2795  *
2796  * Evict a direct child sub-scheduler, disabling it with the supplied reason.
2797  * The child and its subtree are torn down asynchronously through the usual
2798  * disable path.
2799  *
2800  * Unlike scx_bpf_exit(), no exit code is taken: the child is a separate
2801  * scheduler with its own exit-code semantics, so a code chosen by the parent
2802  * would have no defined meaning. The reason string carries the intent.
2803  *
2804  * Return 0 on success or -ENODEV if @cgroup_id names no sub-scheduler, which
2805  * can race with the child detaching on its own and so is not a scheduler error.
2806  * Naming a sched that exists but is not a direct child aborts the parent.
2807  */
2808 __printf(2, 0)
2809 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt,
2810 				      unsigned long long *data, u32 data__sz,
2811 				      const struct bpf_prog_aux *aux)
2812 {
2813 	struct scx_sched *parent, *child;
2814 
2815 	guard(rcu)();
2816 
2817 	parent = scx_prog_sched(aux);
2818 	if (unlikely(!parent))
2819 		return -ENODEV;
2820 
2821 	if (!scx_is_cid_type()) {
2822 		scx_error(parent, "sub-cap kfuncs require a cid-form scheduler");
2823 		return -EOPNOTSUPP;
2824 	}
2825 
2826 	child = scx_find_sub_sched(cgroup_id);
2827 	if (unlikely(!child))
2828 		return -ENODEV;
2829 
2830 	if (unlikely(scx_parent(child) != parent)) {
2831 		scx_error(parent, "%s: sub-%llu is not a direct child",
2832 			  parent->cgrp_path, cgroup_id);
2833 		return -EINVAL;
2834 	}
2835 
2836 	scx_exit_bstr(child, SCX_EXIT_PARENT_KILL, 0, parent, fmt, data, data__sz);
2837 	return 0;
2838 }
2839 
2840 __bpf_kfunc_end_defs();
2841 
2842 #else	/* !CONFIG_EXT_SUB_SCHED */
2843 
2844 __bpf_kfunc_start_defs();
2845 
2846 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps,
2847 				  const struct scx_cmask *cmask__arena,
2848 				  struct scx_cmask *denied_out__arena__nullable,
2849 				  const struct bpf_prog_aux *aux)
2850 {
2851 	return -EOPNOTSUPP;
2852 }
2853 
2854 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps,
2855 				    const struct scx_cmask *cmask__arena,
2856 				    const struct bpf_prog_aux *aux)
2857 {
2858 }
2859 
2860 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__arena,
2861 				 const struct bpf_prog_aux *aux)
2862 {
2863 	return -EOPNOTSUPP;
2864 }
2865 
2866 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt,
2867 				      unsigned long long *data, u32 data__sz,
2868 				      const struct bpf_prog_aux *aux)
2869 {
2870 	return -EOPNOTSUPP;
2871 }
2872 
2873 __bpf_kfunc_end_defs();
2874 
2875 #endif	/* CONFIG_EXT_SUB_SCHED */
2876