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