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