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