xref: /linux/kernel/sched/ext/sub.c (revision f883dbb64ca53f75d9006d1e73180c9d9ecfc9a2)
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. The reenqueue is bounded per task in
323  * scx_do_enqueue_task(), which ejects the owning sub past SCX_REENQ_MAX_REPEAT.
324  * Rejection can't happen for root.
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(sch->ancestors[0], 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 *root, *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 	root = scx_root_protected();
656 	cid = __scx_cpu_to_cid(cpu_of(rq));
657 	shard = rcu_dereference_all(scx_cid_to_shard)[cid];
658 
659 	scx_for_each_descendant_pre(pos, root) {
660 		struct scx_pshard *ps;
661 
662 		/* root holds every cap and never uses ecaps */
663 		if (!pos->level)
664 			continue;
665 
666 		ps = pos->pshard[shard];
667 		guard(raw_spinlock)(&ps->lock);
668 		queue_sync_ecaps(pos, cid);
669 	}
670 }
671 
672 /*
673  * A cpu is going down. Zero each sub-sched's in-effect ecaps so cap checks
674  * treat the cpu as capless while offline. Pending and late-queued syncs are
675  * discarded at consumption by scx_process_sync_ecaps() while the cpu is
676  * inactive. Leave reported_ecaps. Ownership is unchanged, so the
677  * scx_online_ecaps() reseed reports only a genuine delta. No callback fires
678  * here.
679  */
680 void scx_offline_ecaps(struct rq *rq)
681 {
682 	s32 cpu = cpu_of(rq);
683 	struct scx_sched *root, *pos;
684 
685 	guard(rq_lock_irqsave)(rq);
686 
687 	root = scx_root_protected();
688 
689 	scx_for_each_descendant_pre(pos, root) {
690 		/* root holds every cap and never uses ecaps */
691 		if (!pos->level)
692 			continue;
693 
694 		WRITE_ONCE(per_cpu_ptr(pos->pcpu, cpu)->ecaps, 0);
695 	}
696 }
697 
698 /*
699  * @pcpu's sched was unhashed before the grace period, so nothing re-queues its
700  * sync node. Remove the node from @rq's pending list so the pcpu can be freed.
701  */
702 void scx_discard_ecaps_to_sync(s32 cpu, struct scx_sched_pcpu *pcpu)
703 {
704 	struct rq *rq = cpu_rq(cpu);
705 	struct llist_node *head = NULL, *tail = NULL;
706 	struct llist_node *pos, *tmp;
707 
708 	/*
709 	 * llist can't unlink a single node. Take all queued nodes, drop @pcpu's
710 	 * and resplice the rest. Nodes in the taken batch read as on-list
711 	 * throughout, so queue_sync_ecaps() stays correct.
712 	 */
713 	if (llist_on_list(&pcpu->ecaps_to_sync_node)) {
714 		scoped_guard (rq_lock_irqsave, rq) {
715 			llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) {
716 				if (pos == &pcpu->ecaps_to_sync_node) {
717 					init_llist_node(pos);
718 				} else {
719 					pos->next = head;
720 					head = pos;
721 					if (!tail)
722 						tail = pos;
723 				}
724 			}
725 			if (head)
726 				llist_add_batch(head, tail, &rq->scx.ecaps_to_sync);
727 		}
728 	}
729 
730 	/*
731 	 * An in-flight scx_process_sync_ecaps() batch may still hold the node
732 	 * privately across dispatch-induced rq unlocks, reading as on-list.
733 	 *
734 	 * Because a bypassing sched gets no op call, init_llist_node() and all
735 	 * @pcpu accesses share one contiguous lock hold, off-list under the rq
736 	 * lock means @pcpu won't be accessed again.
737 	 */
738 	while (true) {
739 		scoped_guard (rq_lock_irqsave, rq) {
740 			if (!llist_on_list(&pcpu->ecaps_to_sync_node))
741 				return;
742 		}
743 		cpu_relax();
744 	}
745 }
746 
747 /**
748  * scx_discard_stale_ecaps_syncs - Discard ecaps syncs from earlier schedulers
749  *
750  * To be called during root enable before the scheduler goes live. An earlier
751  * root's sub-sched may not have gone through its RCU free path yet (e.g. a
752  * still-open link fd defers it) and can leave queued ecaps syncs behind.
753  * Processing them would decode the dead sched's pshards with the current cid
754  * layout. Discard them instead. The backing scx_sched_pcpu's are still
755  * allocated as the free path removes ecaps_to_sync_node before freeing.
756  */
757 void scx_discard_stale_ecaps_syncs(void)
758 {
759 	s32 cpu;
760 
761 	for_each_possible_cpu(cpu) {
762 		struct rq *rq = cpu_rq(cpu);
763 
764 		guard(rq_lock_irqsave)(rq);
765 		discard_queued_syncs(rq);
766 	}
767 }
768 
769 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq);
770 
771 void drain_descendants(struct scx_sched *sch)
772 {
773 	/*
774 	 * Child scheds that finished the critical part of disabling will take
775 	 * themselves off @sch->children. Wait for it to drain. As propagation
776 	 * is recursive, empty @sch->children means that all proper descendant
777 	 * scheds reached unlinking stage.
778 	 */
779 	wait_event(scx_unlink_waitq, list_empty(&sch->children));
780 }
781 
782 /**
783  * scx_rehome_task - Move a task to a sched it has been initialized for
784  * @to: sched taking over @p, @p's init on it already complete
785  * @p: task to re-home
786  *
787  * Exit @p from its current sched and switch it over to @to, overriding the
788  * state to %SCX_TASK_READY to account for the already completed init. A task
789  * on a non-ext class, possible under an %SCX_OPS_SWITCH_PARTIAL root, stays
790  * %READY and is enabled by switching_to_scx() if it switches over.
791  */
792 static void scx_rehome_task(struct scx_sched *to, struct task_struct *p)
793 {
794 	lockdep_assert_held(&p->pi_lock);
795 	lockdep_assert_rq_held(task_rq(p));
796 
797 	scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
798 		scx_disable_and_exit_task(scx_task_sched(p), p);
799 		scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
800 		scx_set_task_state(p, SCX_TASK_INIT);
801 		scx_set_task_sched(p, to);
802 		scx_set_task_state(p, SCX_TASK_READY);
803 		if (p->sched_class == &ext_sched_class)
804 			scx_enable_task(to, p);
805 	}
806 }
807 
808 /**
809  * scx_punt_task - Hand a task to a failed sched without initialization
810  * @to: failed and bypassed sched taking custody of @p
811  * @p: task to punt
812  *
813  * Take @p off its current sched and put it on @to at %SCX_TASK_NONE. @to is
814  * dying and its teardown will re-home @p properly.
815  *
816  * Used when @to must take over @p but failed to initialize it. Bypass keeps
817  * scheduling decisions away from @to but @p can still trigger its task ops,
818  * which may confuse the BPF side. @to is dying anyway. The exit paths skip
819  * %NONE tasks (see __scx_disable_and_exit_task() and switched_from_scx()).
820  */
821 static void scx_punt_task(struct scx_sched *to, struct task_struct *p)
822 {
823 	lockdep_assert_held(&p->pi_lock);
824 	lockdep_assert_rq_held(task_rq(p));
825 	WARN_ON_ONCE(!READ_ONCE(to->bypass_depth));
826 
827 	scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
828 		scx_disable_and_exit_task(scx_task_sched(p), p);
829 		scx_set_task_sched(p, to);
830 	}
831 }
832 
833 static void scx_fail_parent(struct scx_sched *sch,
834 			    struct task_struct *failed, s32 fail_code)
835 {
836 	struct scx_sched *parent = scx_parent(sch);
837 	struct scx_task_iter sti;
838 	struct task_struct *p;
839 
840 	scx_error(parent, "ops.init_task() failed (%d) for %s[%d] while disabling a sub-scheduler",
841 		  fail_code, failed->comm, failed->pid);
842 
843 	/*
844 	 * Once $parent is bypassed, tasks can be punted into it. This may
845 	 * cause downstream failures on the BPF side but $parent is dying
846 	 * anyway.
847 	 */
848 	scx_bypass(parent, true);
849 
850 	scx_task_iter_start(&sti, sch->cgrp);
851 	while ((p = scx_task_iter_next_locked(&sti))) {
852 		if (scx_task_on_sched(parent, p))
853 			continue;
854 
855 		scx_punt_task(parent, p);
856 	}
857 	scx_task_iter_stop(&sti);
858 }
859 
860 #ifdef CONFIG_EXT_GROUP_SCHED
861 /**
862  * scx_cgroup_claim_subtree - Claim the subtree's cgroups for an enabling sub
863  * @sch: sub-scheduler being enabled
864  *
865  * Called while enabling @sch, after the subtree's cgrp->scx_sched's are pointed
866  * at @sch and before any task is claimed. This mirrors root enable's
867  * cgroups-before-tasks order. The ops.init_task() args are task_group-granular
868  * and can still reference a cgroup outside the handed-over set when the cpu
869  * controller is coarser than the sub topology or mounted on cgroup1.
870  *
871  * First init each of the parent sched's subtree cgroups on @sch, and only then
872  * exit them from the parent, so that a failed init can be unwound with the
873  * parent untouched. The both-inited transient is invisible outside
874  * scx_cgroup_lock(). %SCX_TG_SUB_INIT tracks the first pass's progress.
875  * %SCX_TG_INITED stays set throughout, except for a task_group whose
876  * ops.cgroup_init() failed on the parent (see scx_cgroup_return_subtree()):
877  * there is nothing to exit from the parent and %SCX_TG_INITED is set back with
878  * the transfer.
879  *
880  * Dying but not yet offlined task_groups are included: a removed cgroup keeps
881  * hosting scheduling events until its dying tasks finish their final context
882  * switches, so it still needs to be inited on a sched, and its offline-time
883  * ops.cgroup_exit() follows the last of those events.
884  *
885  * Return 0 on success, -errno on failure. On failure, @sch has been
886  * scx_error()'d and is left with no cgroups.
887  */
888 static s32 scx_cgroup_claim_subtree(struct scx_sched *sch)
889 {
890 	struct cgroup *sub_cgrp = sch_cgroup(sch);
891 	struct cgroup_subsys_state *ecss = cgroup_e_css(sub_cgrp, &cpu_cgrp_subsys);
892 	struct scx_sched *parent = scx_parent(sch);
893 	struct cgroup_subsys_state *css;
894 	int ret;
895 
896 	css_for_each_descendant_pre(css, ecss) {
897 		struct task_group *tg = css_tg(css);
898 		struct scx_cgroup_init_args args = {
899 			.weight = tg->scx.weight,
900 			.bw_period_us = tg->scx.bw_period_us,
901 			.bw_quota_us = tg->scx.bw_quota_us,
902 			.bw_burst_us = tg->scx.bw_burst_us,
903 		};
904 
905 		if (tg->scx.sched != parent ||
906 		    !cgroup_is_descendant(css->cgroup, sub_cgrp))
907 			continue;
908 
909 		if (SCX_HAS_OP(sch, cgroup_init)) {
910 			ret = SCX_CALL_OP_RET(sch, cgroup_init, NULL, css->cgroup, &args);
911 			if (ret) {
912 				scx_error(sch, "ops.cgroup_init() failed (%d)", ret);
913 				goto err;
914 			}
915 		}
916 		tg->scx.flags |= SCX_TG_SUB_INIT;
917 	}
918 
919 	css_for_each_descendant_post(css, ecss) {
920 		struct task_group *tg = css_tg(css);
921 
922 		/*
923 		 * SUB_INIT is pass 1's progress mark: pass 2 and the err path
924 		 * must visit exactly the tgs pass 1 inited.
925 		 */
926 		if (!(tg->scx.flags & SCX_TG_SUB_INIT))
927 			continue;
928 
929 		/* skip the exit if the parent's ops.cgroup_init() failed */
930 		if ((tg->scx.flags & SCX_TG_INITED) && SCX_HAS_OP(parent, cgroup_exit))
931 			SCX_CALL_OP(parent, cgroup_exit, NULL, css->cgroup);
932 		tg->scx.sched = sch;
933 		tg->scx.flags |= SCX_TG_INITED;
934 		tg->scx.flags &= ~SCX_TG_SUB_INIT;
935 	}
936 
937 	return 0;
938 
939 err:
940 	css_for_each_descendant_post(css, ecss) {
941 		struct task_group *tg = css_tg(css);
942 
943 		if (!(tg->scx.flags & SCX_TG_SUB_INIT))
944 			continue;
945 
946 		if (SCX_HAS_OP(sch, cgroup_exit))
947 			SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup);
948 		tg->scx.flags &= ~SCX_TG_SUB_INIT;
949 	}
950 	return ret;
951 }
952 
953 /**
954  * scx_cgroup_return_subtree - Return the subtree's cgroups to the parent sched
955  * @sch: sub-scheduler being disabled
956  *
957  * Called while disabling @sch, after the subtree's cgrp->scx_sched's are reset
958  * to the parent sched and before tasks are re-homed, mirroring root disable's
959  * cgroups-before-tasks teardown order. The reverse of
960  * scx_cgroup_claim_subtree(): exit @sch's cgroups from @sch, then init them on
961  * the parent with the current tg->scx.* values, resyncing settings that changed
962  * while @sch had them.
963  *
964  * When an init on the parent fails, the parent is failed - the same policy as
965  * task re-homing. The remaining task_groups are punted: they move to the parent
966  * anyway with %SCX_TG_INITED cleared, as ops.cgroup_init() failed or never ran
967  * for them. A punted task_group gets no cgroup ops. The dying parent's own
968  * disable moves it one sched up, initing it there. Root ends the chain: root
969  * teardown drops cgroup ops entirely and the next enable's bulk init re-inits
970  * every online task_group.
971  *
972  * The task re-home that follows still delivers ops.init_task() to the dying
973  * parent, including for tasks in punted cgroups it never inited - tolerated
974  * like the downstream failures of task punting (see scx_punt_task()).
975  */
976 static void scx_cgroup_return_subtree(struct scx_sched *sch)
977 {
978 	struct cgroup *sub_cgrp = sch_cgroup(sch);
979 	struct cgroup_subsys_state *ecss = cgroup_e_css(sub_cgrp, &cpu_cgrp_subsys);
980 	struct scx_sched *parent = scx_parent(sch);
981 	struct cgroup_subsys_state *css;
982 	bool parent_failed = false;
983 	int ret;
984 
985 	css_for_each_descendant_post(css, ecss) {
986 		struct task_group *tg = css_tg(css);
987 
988 		if (tg->scx.sched != sch ||
989 		    !cgroup_is_descendant(css->cgroup, sub_cgrp))
990 			continue;
991 
992 		/* skip the exit if @sch's ops.cgroup_init() failed for the tg */
993 		if ((tg->scx.flags & SCX_TG_INITED) && SCX_HAS_OP(sch, cgroup_exit))
994 			SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup);
995 		tg->scx.sched = parent;
996 		tg->scx.flags |= SCX_TG_SUB_INIT;
997 	}
998 
999 	css_for_each_descendant_pre(css, ecss) {
1000 		struct task_group *tg = css_tg(css);
1001 		struct scx_cgroup_init_args args = {
1002 			.weight = tg->scx.weight,
1003 			.bw_period_us = tg->scx.bw_period_us,
1004 			.bw_quota_us = tg->scx.bw_quota_us,
1005 			.bw_burst_us = tg->scx.bw_burst_us,
1006 		};
1007 
1008 		/* the first pass must have transferred everything */
1009 		WARN_ON_ONCE(tg->scx.sched == sch);
1010 
1011 		/*
1012 		 * SUB_INIT distinguishes the tgs pass 1 moved. The sched test
1013 		 * can't: a tg punted to the parent by an earlier failure would
1014 		 * also match.
1015 		 */
1016 		if (!(tg->scx.flags & SCX_TG_SUB_INIT))
1017 			continue;
1018 		tg->scx.flags &= ~(SCX_TG_SUB_INIT | SCX_TG_INITED);
1019 
1020 		/*
1021 		 * A re-init on $parent failed. The task_groups from here on are
1022 		 * punted: they stay on the dying $parent with INITED clear and
1023 		 * move onward when it disables.
1024 		 */
1025 		if (parent_failed)
1026 			continue;
1027 
1028 		if (SCX_HAS_OP(parent, cgroup_init)) {
1029 			ret = SCX_CALL_OP_RET(parent, cgroup_init, NULL, css->cgroup, &args);
1030 			if (ret) {
1031 				scx_error(parent, "ops.cgroup_init() failed (%d) while disabling a sub-scheduler",
1032 					  ret);
1033 				parent_failed = true;
1034 				continue;
1035 			}
1036 		}
1037 		tg->scx.flags |= SCX_TG_INITED;
1038 	}
1039 }
1040 #else
1041 static inline s32 scx_cgroup_claim_subtree(struct scx_sched *sch) { return 0; }
1042 static inline void scx_cgroup_return_subtree(struct scx_sched *sch) {}
1043 #endif
1044 
1045 void scx_sub_disable(struct scx_sched *sch)
1046 {
1047 	struct scx_sched *parent = scx_parent(sch);
1048 	struct scx_task_iter sti;
1049 	struct task_struct *p;
1050 	int ret;
1051 
1052 	/*
1053 	 * Guarantee forward progress and wait for descendants to be disabled.
1054 	 * To limit disruptions, $parent is not bypassed. Tasks are fully
1055 	 * prepped and then inserted back into $parent.
1056 	 */
1057 	scx_bypass(sch, true);
1058 	drain_descendants(sch);
1059 
1060 	/*
1061 	 * Here, every runnable task is guaranteed to make forward progress and
1062 	 * we can safely use blocking synchronization constructs. Actually
1063 	 * disable ops.
1064 	 */
1065 	mutex_lock(&scx_enable_mutex);
1066 	percpu_down_write(&scx_fork_rwsem);
1067 	scx_cgroup_lock();
1068 
1069 	/*
1070 	 * An enable that failed before scx_link_sched() succeeded never owned a
1071 	 * cgroup or task and won't be waited on by an ancestor's
1072 	 * drain_descendants(). Nothing to reparent and walking the tasks can
1073 	 * misbehave as the task ownership invariant (either owned by self or
1074 	 * parent) does not hold. ->sibling can't identify this case - an undone
1075 	 * link leaves it non-empty.
1076 	 */
1077 	if (!sch->linked)
1078 		goto dump;
1079 
1080 	set_cgroup_sched(sch_cgroup(sch), parent);
1081 
1082 	/*
1083 	 * Return the subtree's cgroups before re-homing tasks so that any
1084 	 * ops.init_task() on $parent only sees cgroups it has initialized.
1085 	 */
1086 	scx_cgroup_return_subtree(sch);
1087 
1088 	scx_task_iter_start(&sti, sch->cgrp);
1089 	while ((p = scx_task_iter_next_locked(&sti))) {
1090 		struct rq *rq;
1091 		struct rq_flags rf;
1092 
1093 		/* filter out duplicate visits */
1094 		if (scx_task_on_sched(parent, p))
1095 			continue;
1096 
1097 		/*
1098 		 * By the time control reaches here, all linked descendant
1099 		 * schedulers should have been disabled.
1100 		 */
1101 		WARN_ON_ONCE(!scx_task_on_sched(sch, p));
1102 
1103 		/*
1104 		 * @p is pinned by the iter: css_task_iter_next() takes a
1105 		 * reference and holds it until the next iter_next() call, so
1106 		 * @p->usage is guaranteed > 0.
1107 		 */
1108 		get_task_struct(p);
1109 
1110 		scx_task_iter_unlock(&sti);
1111 
1112 		/*
1113 		 * $p is READY or ENABLED on @sch. Initialize for $parent,
1114 		 * disable and exit from @sch, and then switch over to $parent.
1115 		 *
1116 		 * If a task fails to initialize for $parent, the only available
1117 		 * action is disabling $parent too. While this allows disabling
1118 		 * of a child sched to cause the parent scheduler to fail, the
1119 		 * failure can only originate from ops.init_task() of the
1120 		 * parent. A child can't directly affect the parent through its
1121 		 * own failures.
1122 		 */
1123 		ret = __scx_init_task(parent, p, NULL, false);
1124 		if (ret) {
1125 			scx_fail_parent(sch, p, ret);
1126 			put_task_struct(p);
1127 			break;
1128 		}
1129 
1130 		rq = task_rq_lock(p, &rf);
1131 
1132 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
1133 			/*
1134 			 * sched_ext_dead() raced us between __scx_init_task()
1135 			 * and this rq lock and ran exit_task() on @sch (the
1136 			 * sched @p was on at that point), not on $parent.
1137 			 * $parent's just-completed init is owed an exit_task()
1138 			 * and we issue it here.
1139 			 */
1140 			scx_sub_init_cancel_task(parent, p);
1141 			task_rq_unlock(rq, p, &rf);
1142 			put_task_struct(p);
1143 			continue;
1144 		}
1145 
1146 		scx_rehome_task(parent, p);
1147 
1148 		task_rq_unlock(rq, p, &rf);
1149 		put_task_struct(p);
1150 	}
1151 	scx_task_iter_stop(&sti);
1152 
1153 dump:
1154 	scx_disable_dump(sch);
1155 
1156 	scx_cgroup_unlock();
1157 	percpu_up_write(&scx_fork_rwsem);
1158 
1159 	/*
1160 	 * All tasks are moved off of @sch but there may still be on-going
1161 	 * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use
1162 	 * the expedited version as ancestors may be waiting in bypass mode.
1163 	 * Also, tell the parent that there is no need to keep running bypass
1164 	 * DSQs for us.
1165 	 */
1166 	synchronize_rcu_expedited();
1167 	scx_disable_bypass_dsp(sch);
1168 
1169 	scx_unlink_sched(sch);
1170 
1171 	mutex_unlock(&scx_enable_mutex);
1172 
1173 	/*
1174 	 * @sch is now unlinked from the parent's children list. Notify and call
1175 	 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called
1176 	 * after unlinking and releasing all locks. See scx_claim_exit().
1177 	 */
1178 	wake_up_all(&scx_unlink_waitq);
1179 
1180 	if (parent->ops.sub_detach && sch->sub_attached) {
1181 		struct scx_sub_detach_args sub_detach_args = {
1182 			.ops = &sch->ops,
1183 			.cgroup_path = sch->cgrp_path,
1184 		};
1185 		SCX_CALL_OP(parent, sub_detach, NULL,
1186 			    &sub_detach_args);
1187 	}
1188 
1189 	scx_log_sched_disable(sch);
1190 
1191 	if (sch->ops.exit)
1192 		SCX_CALL_OP(sch, exit, NULL, sch->exit_info);
1193 
1194 	/*
1195 	 * @sch's non-ops programs such as timers and tracers can fire after
1196 	 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from
1197 	 * resolving to @sch and drain in-flight resolvers.
1198 	 */
1199 	WRITE_ONCE(sch->dead, true);
1200 	synchronize_rcu();
1201 
1202 	if (sch->sub_kset)
1203 		kobject_del(&sch->sub_kset->kobj);
1204 	/* not added if enable failed before scx_sched_sysfs_add() */
1205 	if (sch->kobj.state_in_sysfs)
1206 		kobject_del(&sch->kobj);
1207 }
1208 
1209 /* verify that a scheduler can be attached to @cgrp and return the parent */
1210 static struct scx_sched *find_parent_sched(struct cgroup *cgrp)
1211 {
1212 	struct scx_sched *parent = scx_cgroup_sched(cgrp);
1213 	struct scx_sched *pos;
1214 
1215 	lockdep_assert_held(&scx_sched_lock);
1216 
1217 	/* can't attach twice to the same cgroup */
1218 	if (parent->cgrp == cgrp)
1219 		return ERR_PTR(-EBUSY);
1220 
1221 	/* does $parent allow sub-scheds? */
1222 	if (!parent->ops.sub_attach)
1223 		return ERR_PTR(-EOPNOTSUPP);
1224 
1225 	/* can't insert between $parent and its exiting children */
1226 	list_for_each_entry(pos, &parent->children, sibling)
1227 		if (cgroup_is_descendant(pos->cgrp, cgrp))
1228 			return ERR_PTR(-EBUSY);
1229 
1230 	return parent;
1231 }
1232 
1233 static bool assert_task_ready_or_enabled(struct task_struct *p)
1234 {
1235 	u32 state = scx_get_task_state(p);
1236 
1237 	switch (state) {
1238 	case SCX_TASK_READY:
1239 	case SCX_TASK_ENABLED:
1240 		return true;
1241 	default:
1242 		WARN_ONCE(true, "sched_ext: Invalid task state %d for %s[%d] during enabling sub sched",
1243 			  state, p->comm, p->pid);
1244 		return false;
1245 	}
1246 }
1247 
1248 void scx_sub_enable_workfn(struct kthread_work *work)
1249 {
1250 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
1251 	struct sched_ext_ops *ops = cmd->ops;
1252 	struct cgroup *cgrp;
1253 	struct scx_sched *parent, *sch;
1254 	struct scx_task_iter sti;
1255 	struct task_struct *p;
1256 	s32 i, ret;
1257 
1258 	mutex_lock(&scx_enable_mutex);
1259 
1260 	if (!scx_enabled()) {
1261 		ret = -ENODEV;
1262 		goto out_unlock;
1263 	}
1264 
1265 	/* See scx_root_enable_workfn() for the @ops->priv check. */
1266 	if (rcu_access_pointer(ops->priv)) {
1267 		ret = -EBUSY;
1268 		goto out_unlock;
1269 	}
1270 
1271 	cgrp = cgroup_get_from_id(ops->sub_cgroup_id);
1272 	if (IS_ERR(cgrp)) {
1273 		ret = PTR_ERR(cgrp);
1274 		goto out_unlock;
1275 	}
1276 
1277 	raw_spin_lock_irq(&scx_sched_lock);
1278 	parent = find_parent_sched(cgrp);
1279 	if (IS_ERR(parent)) {
1280 		raw_spin_unlock_irq(&scx_sched_lock);
1281 		ret = PTR_ERR(parent);
1282 		goto out_put_cgrp;
1283 	}
1284 	kobject_get(&parent->kobj);
1285 	raw_spin_unlock_irq(&scx_sched_lock);
1286 
1287 	/*
1288 	 * Flip the hot-path gates before ops->priv is published - the sub's
1289 	 * programs can e.g. kick cpus from that point on. The matching dec is
1290 	 * at the end of scx_sched_free_rcu_work().
1291 	 */
1292 	static_branch_inc(&__scx_has_subs);
1293 
1294 	/* scx_alloc_and_add_sched() consumes @cgrp whether it succeeds or not */
1295 	sch = scx_alloc_and_add_sched(cmd, cgrp, parent);
1296 	kobject_put(&parent->kobj);
1297 	if (IS_ERR(sch)) {
1298 		static_branch_dec(&__scx_has_subs);
1299 		ret = PTR_ERR(sch);
1300 		goto out_unlock;
1301 	}
1302 
1303 	/*
1304 	 * Validate before scx_link_sched() publishes @sch, so an invalid sub
1305 	 * never becomes visible with an unallocated pshard.
1306 	 */
1307 	ret = scx_validate_ops(sch, ops);
1308 	if (ret)
1309 		goto err_disable;
1310 
1311 	/*
1312 	 * Allocate pshard[] before scx_link_sched() publishes @sch into the
1313 	 * parent's RCU children list. A concurrent revoke walking the tree
1314 	 * would otherwise dereference sch->pshard[si] while it's still NULL.
1315 	 * Unlike the root path, the cid shard layout is stable at this point.
1316 	 *
1317 	 * scx_alloc_pshards() skips allocation when @sch's arena pool isn't
1318 	 * initialized, so scx_arena_pool_init() must run first.
1319 	 */
1320 	ret = scx_arena_pool_init(sch);
1321 	if (ret)
1322 		goto err_disable;
1323 
1324 	ret = scx_alloc_pshards(sch);
1325 	if (ret)
1326 		goto err_disable;
1327 
1328 	ret = scx_link_sched(sch);
1329 	if (ret)
1330 		goto err_disable;
1331 
1332 	ret = scx_sched_sysfs_add(sch);
1333 	if (ret)
1334 		goto err_disable;
1335 
1336 	if (sch->level >= SCX_SUB_MAX_DEPTH) {
1337 		scx_error(sch, "max nesting depth %d violated",
1338 			  SCX_SUB_MAX_DEPTH);
1339 		ret = -EINVAL;
1340 		goto err_disable;
1341 	}
1342 
1343 	if (sch->ops.init) {
1344 		ret = SCX_CALL_OP_RET(sch, init, NULL);
1345 		if (ret) {
1346 			ret = scx_ops_sanitize_err(sch, "init", ret);
1347 			scx_error(sch, "ops.init() failed (%d)", ret);
1348 			goto err_disable;
1349 		}
1350 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
1351 	}
1352 
1353 	ret = scx_set_cmask_scratch_alloc(sch);
1354 	if (ret)
1355 		goto err_disable;
1356 
1357 	struct scx_sub_attach_args sub_attach_args = {
1358 		.ops = &sch->ops,
1359 		.cgroup_path = sch->cgrp_path,
1360 	};
1361 
1362 	ret = SCX_CALL_OP_RET(parent, sub_attach, NULL,
1363 			      &sub_attach_args);
1364 	if (ret) {
1365 		ret = scx_ops_sanitize_err(sch, "sub_attach", ret);
1366 		scx_error(sch, "parent rejected (%d)", ret);
1367 		goto err_disable;
1368 	}
1369 	sch->sub_attached = true;
1370 
1371 	scx_bypass(sch, true);
1372 
1373 	for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++)
1374 		if (((void (**)(void))ops)[i])
1375 			set_bit(i, sch->has_op);
1376 
1377 	percpu_down_write(&scx_fork_rwsem);
1378 	scx_cgroup_lock();
1379 
1380 	/*
1381 	 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see
1382 	 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down.
1383 	 */
1384 	set_cgroup_sched(sch_cgroup(sch), sch);
1385 	if (!(cgrp->self.flags & CSS_ONLINE)) {
1386 		scx_error(sch, "cgroup is not online");
1387 		ret = -ENODEV;
1388 		goto err_unlock_and_disable;
1389 	}
1390 
1391 	/*
1392 	 * Take over the subtree's cgroups before any task is claimed,
1393 	 * mirroring root enable's cgroups-before-tasks order.
1394 	 */
1395 	ret = scx_cgroup_claim_subtree(sch);
1396 	if (ret)
1397 		goto err_unlock_and_disable;
1398 
1399 	/*
1400 	 * Initialize tasks for the new child $sch without exiting them for
1401 	 * $parent so that the tasks can always be reverted back to $parent
1402 	 * sched on child init failure.
1403 	 */
1404 	WARN_ON_ONCE(scx_enabling_sub_sched);
1405 	scx_enabling_sub_sched = sch;
1406 
1407 	scx_task_iter_start(&sti, sch->cgrp);
1408 	while ((p = scx_task_iter_next_locked(&sti))) {
1409 		struct rq *rq;
1410 		struct rq_flags rf;
1411 
1412 		/*
1413 		 * Task iteration may visit the same task twice when racing
1414 		 * against exiting. Use %SCX_TASK_SUB_INIT to mark tasks which
1415 		 * finished __scx_init_task() and skip if set.
1416 		 *
1417 		 * A task may exit and get freed between __scx_init_task()
1418 		 * completion and scx_enable_task(). In such cases,
1419 		 * scx_disable_and_exit_task() must exit the task for both the
1420 		 * parent and child scheds.
1421 		 */
1422 		if (p->scx.flags & SCX_TASK_SUB_INIT)
1423 			continue;
1424 
1425 		/* @p is pinned by the iter; see scx_sub_disable() */
1426 		get_task_struct(p);
1427 
1428 		if (!assert_task_ready_or_enabled(p)) {
1429 			ret = -EINVAL;
1430 			goto abort;
1431 		}
1432 
1433 		scx_task_iter_unlock(&sti);
1434 
1435 		/*
1436 		 * As $p is still on $parent, it can't be transitioned to INIT.
1437 		 * Let's worry about task state later. Use __scx_init_task().
1438 		 */
1439 		ret = __scx_init_task(sch, p, NULL, false);
1440 		if (ret)
1441 			goto abort;
1442 
1443 		rq = task_rq_lock(p, &rf);
1444 
1445 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
1446 			/*
1447 			 * sched_ext_dead() raced us between __scx_init_task()
1448 			 * and this rq lock and ran exit_task() on $parent (the
1449 			 * sched @p was on at that point), not on @sch. @sch's
1450 			 * just-completed init is owed an exit_task() and we
1451 			 * issue it here.
1452 			 */
1453 			scx_sub_init_cancel_task(sch, p);
1454 			task_rq_unlock(rq, p, &rf);
1455 			put_task_struct(p);
1456 			continue;
1457 		}
1458 
1459 		p->scx.flags |= SCX_TASK_SUB_INIT;
1460 		task_rq_unlock(rq, p, &rf);
1461 
1462 		put_task_struct(p);
1463 	}
1464 	scx_task_iter_stop(&sti);
1465 
1466 	/*
1467 	 * All tasks are prepped. Disable/exit tasks for $parent and enable for
1468 	 * the new @sch.
1469 	 */
1470 	scx_task_iter_start(&sti, sch->cgrp);
1471 	while ((p = scx_task_iter_next_locked(&sti))) {
1472 		/*
1473 		 * Use clearing of %SCX_TASK_SUB_INIT to detect and skip
1474 		 * duplicate iterations.
1475 		 */
1476 		if (!(p->scx.flags & SCX_TASK_SUB_INIT))
1477 			continue;
1478 
1479 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
1480 			/*
1481 			 * $p must be either READY or ENABLED. If ENABLED,
1482 			 * __scx_disabled_and_exit_task() first disables and
1483 			 * makes it READY. However, after exiting $p, it will
1484 			 * leave $p as READY.
1485 			 */
1486 			assert_task_ready_or_enabled(p);
1487 			__scx_disable_and_exit_task(parent, p);
1488 
1489 			/*
1490 			 * $p is now only initialized for @sch and READY, which
1491 			 * is what we want. Assign it to @sch and, if it's on
1492 			 * the ext class, enable. A non-ext task, possible under
1493 			 * an %SCX_OPS_SWITCH_PARTIAL root, stays READY and is
1494 			 * enabled by switching_to_scx() if it switches over.
1495 			 */
1496 			scx_set_task_sched(p, sch);
1497 			if (p->sched_class == &ext_sched_class)
1498 				scx_enable_task(sch, p);
1499 
1500 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
1501 		}
1502 	}
1503 	scx_task_iter_stop(&sti);
1504 
1505 	scx_enabling_sub_sched = NULL;
1506 
1507 	scx_cgroup_unlock();
1508 	percpu_up_write(&scx_fork_rwsem);
1509 
1510 	scx_bypass(sch, false);
1511 
1512 	/* @sch is enabled; deliver any caps owed since its sub_attach() */
1513 	scx_sub_seed_caps(sch);
1514 
1515 	pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name);
1516 	kobject_uevent(&sch->kobj, KOBJ_ADD);
1517 	ret = 0;
1518 	goto out_unlock;
1519 
1520 out_put_cgrp:
1521 	cgroup_put(cgrp);
1522 out_unlock:
1523 	mutex_unlock(&scx_enable_mutex);
1524 	cmd->ret = ret;
1525 	return;
1526 
1527 abort:
1528 	put_task_struct(p);
1529 	scx_task_iter_stop(&sti);
1530 
1531 	/*
1532 	 * Undo __scx_init_task() for tasks we marked. scx_enable_task() never
1533 	 * ran for @sch on them, so calling scx_disable_task() here would invoke
1534 	 * ops.disable() without a matching ops.enable(). scx_enabling_sub_sched
1535 	 * must stay set until SUB_INIT is cleared from every marked task -
1536 	 * scx_disable_and_exit_task() reads it when a task exits concurrently.
1537 	 */
1538 	scx_task_iter_start(&sti, sch->cgrp);
1539 	while ((p = scx_task_iter_next_locked(&sti))) {
1540 		if (p->scx.flags & SCX_TASK_SUB_INIT) {
1541 			scx_sub_init_cancel_task(sch, p);
1542 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
1543 		}
1544 	}
1545 	scx_task_iter_stop(&sti);
1546 	scx_enabling_sub_sched = NULL;
1547 err_unlock_and_disable:
1548 	/* we'll soon enter disable path, keep bypass on */
1549 	scx_cgroup_unlock();
1550 	percpu_up_write(&scx_fork_rwsem);
1551 err_disable:
1552 	mutex_unlock(&scx_enable_mutex);
1553 	/*
1554 	 * Some enable failures only return an errno (e.g. -ENOMEM from an
1555 	 * allocation) without calling scx_error(). Record it so
1556 	 * scx_flush_disable_work() runs the disable and ops.exit() fires.
1557 	 */
1558 	scx_error(sch, "scx_sub_enable() failed (%d)", ret);
1559 	scx_flush_disable_work(sch);
1560 	cmd->ret = 0;
1561 }
1562 
1563 /**
1564  * scx_cgroup_task_migrating - Prepare a task for a cgroup migration
1565  * @ctx: migration being prepared
1566  *
1567  * A task's sched must match its cgroup's owner, so a migration that crosses a
1568  * sched boundary re-homes the task once committed. Run the fallible part here,
1569  * before the migration commits: initialize the task for the destination sched.
1570  * A rejection fails the cgroup.procs write.
1571  */
1572 static s32 scx_cgroup_task_migrating(struct cgroup_task_migrate_ctx *ctx)
1573 {
1574 	struct task_struct *p = ctx->task;
1575 	struct scx_sched *to;
1576 	int ret;
1577 
1578 	/*
1579 	 * Cleared under scx_cgroup_lock() before root disable starts tearing
1580 	 * down tasks. As cgroup_mutex is held, a set flag guarantees that the
1581 	 * teardown loop is not running concurrently.
1582 	 */
1583 	if (!scx_cgroup_enabled)
1584 		return NOTIFY_OK;
1585 
1586 	to = scx_cgroup_sched(ctx->dst_dcgrp);
1587 	if (scx_task_on_sched(to, p))
1588 		return NOTIFY_OK;
1589 
1590 	ret = __scx_init_task(to, p, ctx->dst_dcgrp, false);
1591 	if (ret)
1592 		return notifier_from_errno(ret);
1593 
1594 	return NOTIFY_OK;
1595 }
1596 
1597 /**
1598  * scx_cgroup_task_migrated - Re-home a task that changed cgroups
1599  * @ctx: committed migration
1600  *
1601  * Move the task to its new cgroup's sched, which scx_cgroup_task_migrating()
1602  * already initialized it for. Can't fail.
1603  *
1604  * This is safe against all phases of the destination sched's destruction. A
1605  * disable resets cgroup ownership to the parent and re-homes tasks in one
1606  * scx_cgroup_lock() section. If that section already ran, the destination would
1607  * be the parent. Otherwise, the re-home loop is still ahead and guaranteed to
1608  * visit the task, now in the destination cgroup.
1609  */
1610 static void scx_cgroup_task_migrated(struct cgroup_task_migrate_ctx *ctx)
1611 {
1612 	struct task_struct *p = ctx->task;
1613 	struct scx_sched *to;
1614 	struct rq *rq;
1615 	struct rq_flags rf;
1616 
1617 	if (!scx_cgroup_enabled)
1618 		return;
1619 
1620 	to = scx_cgroup_sched(ctx->dst_dcgrp);
1621 	if (scx_task_on_sched(to, p))
1622 		return;
1623 
1624 	rq = task_rq_lock(p, &rf);
1625 	scx_rehome_task(to, p);
1626 	task_rq_unlock(rq, p, &rf);
1627 }
1628 
1629 /**
1630  * scx_cgroup_task_migrate_canceled - Undo migration preparation
1631  * @ctx: canceled migration
1632  *
1633  * The migration failed after scx_cgroup_task_migrating() initialized the task
1634  * for the destination sched. The task stays on its current sched in the source
1635  * cgroup. Undo the destination's init.
1636  */
1637 static void scx_cgroup_task_migrate_canceled(struct cgroup_task_migrate_ctx *ctx)
1638 {
1639 	struct task_struct *p = ctx->task;
1640 	struct scx_sched *to;
1641 	struct rq *rq;
1642 	struct rq_flags rf;
1643 
1644 	if (!scx_cgroup_enabled)
1645 		return;
1646 
1647 	to = scx_cgroup_sched(ctx->dst_dcgrp);
1648 	if (scx_task_on_sched(to, p))
1649 		return;
1650 
1651 	rq = task_rq_lock(p, &rf);
1652 	scx_sub_init_cancel_task(to, p);
1653 	task_rq_unlock(rq, p, &rf);
1654 }
1655 
1656 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb,
1657 				      unsigned long action, void *data)
1658 {
1659 	struct cgroup *cgrp = data;
1660 	struct cgroup *parent = cgroup_parent(cgrp);
1661 	struct scx_sched *sch;
1662 
1663 	if (!cgroup_on_dfl(cgrp))
1664 		return NOTIFY_OK;
1665 
1666 	switch (action) {
1667 	case CGROUP_LIFETIME_ONLINE:
1668 		/* inherit ->scx_sched from $parent */
1669 		if (parent)
1670 			rcu_assign_pointer(cgrp->scx_sched, scx_cgroup_sched(parent));
1671 		break;
1672 	case CGROUP_LIFETIME_OFFLINE:
1673 		/* if there is a sched attached, shoot it down */
1674 		sch = scx_cgroup_sched(cgrp);
1675 		if (sch && sch->cgrp == cgrp)
1676 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
1677 				 SCX_ECODE_RSN_CGROUP_OFFLINE,
1678 				 "cgroup %llu going offline", cgroup_id(cgrp));
1679 		break;
1680 	}
1681 
1682 	return NOTIFY_OK;
1683 }
1684 
1685 static struct notifier_block scx_cgroup_lifetime_nb = {
1686 	.notifier_call = scx_cgroup_lifetime_notify,
1687 };
1688 
1689 static s32 scx_cgroup_task_notify(struct notifier_block *nb,
1690 				  unsigned long action, void *data)
1691 {
1692 	struct cgroup_task_migrate_ctx *ctx = data;
1693 
1694 	switch (action) {
1695 	case CGROUP_TASK_MIGRATING:
1696 		return scx_cgroup_task_migrating(ctx);
1697 	case CGROUP_TASK_MIGRATED:
1698 		scx_cgroup_task_migrated(ctx);
1699 		break;
1700 	case CGROUP_TASK_MIGRATE_CANCELED:
1701 		scx_cgroup_task_migrate_canceled(ctx);
1702 		break;
1703 	}
1704 
1705 	return NOTIFY_OK;
1706 }
1707 
1708 static struct notifier_block scx_cgroup_task_nb = {
1709 	.notifier_call = scx_cgroup_task_notify,
1710 };
1711 
1712 static s32 __init scx_cgroup_notifier_init(void)
1713 {
1714 	s32 ret;
1715 
1716 	ret = blocking_notifier_chain_register(&cgroup_lifetime_notifier,
1717 					       &scx_cgroup_lifetime_nb);
1718 	if (ret)
1719 		return ret;
1720 
1721 	return blocking_notifier_chain_register(&cgroup_task_notifier,
1722 						&scx_cgroup_task_nb);
1723 }
1724 core_initcall(scx_cgroup_notifier_init);
1725 
1726 static void scx_pstack_recursion(struct bpf_prog *prog, const char *op)
1727 {
1728 	struct scx_sched *sch;
1729 
1730 	guard(rcu)();
1731 	sch = scx_prog_sched(prog->aux);
1732 	if (unlikely(!sch))
1733 		return;
1734 
1735 	scx_error(sch, "%s recursion detected", op);
1736 }
1737 
1738 void scx_pstack_recursion_on_dispatch(struct bpf_prog *prog)
1739 {
1740 	scx_pstack_recursion(prog, "dispatch");
1741 }
1742 
1743 void scx_pstack_recursion_on_caps_updated(struct bpf_prog *prog)
1744 {
1745 	scx_pstack_recursion(prog, "sub_caps_updated");
1746 }
1747 
1748 __bpf_kfunc_start_defs();
1749 
1750 /**
1751  * scx_bpf_sub_dispatch - Trigger dispatching on a child scheduler
1752  * @cgroup_id: cgroup ID of the child scheduler to dispatch
1753  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1754  *
1755  * Allows a parent scheduler to trigger dispatching on one of its direct
1756  * child schedulers. The child scheduler runs its dispatch operation to
1757  * move tasks from dispatch queues to the local runqueue.
1758  *
1759  * Returns: true on success, false if cgroup_id is invalid, not a direct
1760  * child, or caller lacks dispatch permission.
1761  */
1762 __bpf_kfunc bool scx_bpf_sub_dispatch(u64 cgroup_id, const struct bpf_prog_aux *aux)
1763 {
1764 	struct rq *this_rq = this_rq();
1765 	struct scx_sched *parent, *child;
1766 
1767 	guard(rcu)();
1768 	parent = scx_prog_sched(aux);
1769 	if (unlikely(!parent))
1770 		return false;
1771 
1772 	child = scx_find_sub_sched(cgroup_id);
1773 
1774 	if (unlikely(!child))
1775 		return false;
1776 
1777 	if (unlikely(scx_parent(child) != parent)) {
1778 		scx_error(parent, "trying to dispatch a distant sub-sched on cgroup %llu",
1779 			  cgroup_id);
1780 		return false;
1781 	}
1782 
1783 	/*
1784 	 * Skip a child that does not effectively hold the base cap on this cpu:
1785 	 * its inserts would only be rejected. ecaps are synced at the top of
1786 	 * balance_one() before dispatch, so this reflects the in-effect state.
1787 	 */
1788 	if (scx_missing_caps(child, cpu_of(this_rq), SCX_CAP_BASE))
1789 		return false;
1790 
1791 	return scx_dispatch_sched(child, this_rq, this_rq->scx.sub_dispatch_prev,
1792 				  true);
1793 }
1794 
1795 /* Validate common inputs. On success, *parent_out and *child_out are set. */
1796 static s32 sub_cap_preamble(u64 cgroup_id, u64 caps, const struct bpf_prog_aux *aux,
1797 			    struct scx_sched **parent_out, struct scx_sched **child_out)
1798 {
1799 	struct scx_sched *parent, *child;
1800 
1801 	parent = scx_prog_sched(aux);
1802 	if (unlikely(!parent))
1803 		return -ENODEV;
1804 
1805 	if (!scx_is_cid_type()) {
1806 		scx_error(parent, "sub-cap kfuncs require a cid-form scheduler");
1807 		return -EOPNOTSUPP;
1808 	}
1809 
1810 	child = scx_find_sub_sched(cgroup_id);
1811 	if (unlikely(!child))
1812 		return -ENODEV;
1813 
1814 	if (unlikely(scx_parent(child) != parent)) {
1815 		scx_error(parent, "%s: sub-%llu is not a direct child",
1816 			  parent->cgrp_path, cgroup_id);
1817 		return -EINVAL;
1818 	}
1819 
1820 	if (unlikely(caps & ~__SCX_CAP_ALL)) {
1821 		scx_error(parent, "invalid caps 0x%llx", caps);
1822 		return -EINVAL;
1823 	}
1824 
1825 	*parent_out = parent;
1826 	*child_out = child;
1827 	return 0;
1828 }
1829 
1830 /**
1831  * scx_bpf_sub_grant - Grant @caps on @cmask__ign's cids to a direct child
1832  * @cgroup_id: cgroup id of the direct child sub-sched
1833  * @caps: bitmask of SCX_CAP_* to grant
1834  * @cmask__ign: cid cmask to grant @caps on (arena pointer)
1835  * @denied_out__ign: optional arena cmask accumulating refused cids
1836  * @aux: implicit BPF argument
1837  *
1838  * A cid in @cmask__ign is granted to the child only if the parent holds every
1839  * requested cap on it. Refused cids are OR'd into @denied_out__ign when
1840  * provided. Refusals outside @denied_out__ign's range are not recorded.
1841  *
1842  * All-or-nothing keeps the caller-visible result binary per cid, so
1843  * @denied_out__ign is one mask to interpret rather than a per-cap matrix.
1844  *
1845  * Return 0 on full success, -EPERM if any cid was refused, or a negative
1846  * errno on other failures.
1847  */
1848 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps,
1849 				  const struct scx_cmask *cmask__ign,
1850 				  struct scx_cmask *denied_out__ign,
1851 				  const struct bpf_prog_aux *aux)
1852 {
1853 	struct scx_cmask_ref ref, denied_ref;
1854 	struct scx_sched *parent, *child;
1855 	bool any_denied = false;
1856 	LIST_HEAD(to_deliver);
1857 	s32 si, ret;
1858 
1859 	guard(irqsave)();
1860 
1861 	ret = sub_cap_preamble(cgroup_id, caps, aux, &parent, &child);
1862 	if (ret)
1863 		return ret;
1864 
1865 	ret = scx_cmask_ref_init(parent, cmask__ign, &ref);
1866 	if (ret) {
1867 		scx_error(parent, "invalid cmask (%d)", ret);
1868 		return ret;
1869 	}
1870 
1871 	if (denied_out__ign) {
1872 		ret = scx_cmask_ref_init(parent, denied_out__ign, &denied_ref);
1873 		if (ret) {
1874 			scx_error(parent, "invalid denied_out (%d)", ret);
1875 			return ret;
1876 		}
1877 	}
1878 
1879 	/* apply the grant one shard at a time */
1880 	for (si = ref.shard_first; si < ref.shard_end; si++) {
1881 		SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS);
1882 		struct scx_pshard *pps = parent->pshard[si];
1883 		struct scx_pshard *cps = child->pshard[si];
1884 		u64 granted_caps = 0;
1885 		u32 cap_bit;
1886 
1887 		scx_cmask_ref_shard(&ref, si, slice);
1888 		if (scx_cmask_empty(slice))
1889 			continue;
1890 
1891 		SCX_CMASK_DEFINE_SHARD(granted_cids, slice->base, slice->nr_cids);
1892 		SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids);
1893 		SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids);
1894 
1895 		scx_cmask_copy(granted_cids, slice);
1896 
1897 		scoped_guard (raw_spinlock, &pps->lock) {
1898 			guard(raw_spinlock_nested)(&cps->lock);
1899 
1900 			/*
1901 			 * Narrow granted_cids to cids the parent holds every
1902 			 * requested cap on. All-or-nothing per cid.
1903 			 */
1904 			scx_for_each_cap_bit(cap_bit, caps)
1905 				scx_cmask_and(granted_cids, &pps->caps[cap_bit].cmask);
1906 
1907 			/*
1908 			 * For each requested cap, fold the newly-set cids into
1909 			 * the child and accumulate the delta.
1910 			 */
1911 			scx_for_each_cap_bit(cap_bit, caps) {
1912 				struct scx_cmask *ccm = &cps->caps[cap_bit].cmask;
1913 
1914 				scx_cmask_copy(delta, granted_cids);
1915 				scx_cmask_andnot(delta, ccm);
1916 				if (scx_cmask_empty(delta))
1917 					continue;
1918 
1919 				scx_cmask_or(ccm, delta);
1920 				scx_cmask_or(changed_cids, delta);
1921 				granted_caps |= BIT_U64(cap_bit);
1922 			}
1923 
1924 			if (granted_caps) {
1925 				s32 cid;
1926 
1927 				caps_updated_record(cps, changed_cids, granted_caps,
1928 						    &to_deliver);
1929 				/*
1930 				 * The sync arms an update_idle() re-notify if
1931 				 * the cid gains baseline access, so the holder
1932 				 * learns of an already-idle cid.
1933 				 */
1934 				scx_cmask_for_each_cid(cid, changed_cids)
1935 					queue_sync_ecaps(child, cid);
1936 			}
1937 		}
1938 
1939 		/* record cids that didn't make it through into @denied_out */
1940 		if (!scx_cmask_subset(slice, granted_cids)) {
1941 			any_denied = true;
1942 			if (denied_out__ign) {
1943 				SCX_CMASK_DEFINE_SHARD(denied, slice->base, slice->nr_cids);
1944 
1945 				scx_cmask_copy(denied, slice);
1946 				scx_cmask_andnot(denied, granted_cids);
1947 				scx_cmask_ref_or(&denied_ref, denied);
1948 			}
1949 		}
1950 	}
1951 
1952 	caps_updated_deliver(&to_deliver);
1953 
1954 	return any_denied ? -EPERM : 0;
1955 }
1956 
1957 /**
1958  * scx_bpf_sub_revoke - Revoke @caps on @cmask__ign's cids from @child
1959  * @cgroup_id: cgroup id of the direct child sub-sched
1960  * @caps: bitmask of SCX_CAP_* to revoke
1961  * @cmask__ign: cid cmask to revoke @caps on (arena pointer)
1962  * @aux: implicit BPF argument
1963  *
1964  * Clear @caps bits on @cmask__ign from the child named by @cgroup_id and all
1965  * its descendants. The origin parent's pshard lock is held across the subtree
1966  * walk so a concurrent grant from the origin parent observes the revoked
1967  * state.
1968  */
1969 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps,
1970 				    const struct scx_cmask *cmask__ign,
1971 				    const struct bpf_prog_aux *aux)
1972 {
1973 	struct scx_cmask_ref ref;
1974 	struct scx_sched *parent, *child, *pos;
1975 	LIST_HEAD(to_deliver);
1976 	s32 si, ret;
1977 
1978 	guard(irqsave)();
1979 
1980 	if (sub_cap_preamble(cgroup_id, caps, aux, &parent, &child))
1981 		return;
1982 
1983 	ret = scx_cmask_ref_init(parent, cmask__ign, &ref);
1984 	if (ret) {
1985 		scx_error(parent, "invalid cmask (%d)", ret);
1986 		return;
1987 	}
1988 
1989 	/* per-shard, walk child's subtree and clear @caps */
1990 	for (si = ref.shard_first; si < ref.shard_end; si++) {
1991 		SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS);
1992 
1993 		scx_cmask_ref_shard(&ref, si, slice);
1994 		if (scx_cmask_empty(slice))
1995 			continue;
1996 
1997 		/*
1998 		 * Pre-order with subtree skip: a descendant that cleared
1999 		 * nothing means no descendant of it can hold @caps on these
2000 		 * cids either.
2001 		 */
2002 		guard(raw_spinlock)(&parent->pshard[si]->lock);
2003 		pos = scx_next_descendant_pre(NULL, child);
2004 		while (pos) {
2005 			struct scx_pshard *ps = pos->pshard[si];
2006 			SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids);
2007 			SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids);
2008 			u64 revoked_caps = 0;
2009 			u32 cap_bit;
2010 
2011 			scoped_guard (raw_spinlock_nested, &ps->lock) {
2012 				/*
2013 				 * For each cap, clear lost cids and accumulate
2014 				 * the per-cap diff for notification.
2015 				 */
2016 				scx_for_each_cap_bit(cap_bit, caps) {
2017 					struct scx_cmask *cm = &ps->caps[cap_bit].cmask;
2018 
2019 					scx_cmask_copy(delta, cm);
2020 					scx_cmask_and(delta, slice);
2021 					if (scx_cmask_empty(delta))
2022 						continue;
2023 
2024 					scx_cmask_andnot(cm, delta);
2025 					scx_cmask_or(changed_cids, delta);
2026 					revoked_caps |= BIT_U64(cap_bit);
2027 				}
2028 
2029 				if (revoked_caps) {
2030 					s32 cid;
2031 
2032 					caps_updated_record(ps, changed_cids, revoked_caps,
2033 							    &to_deliver);
2034 					scx_cmask_for_each_cid(cid, changed_cids)
2035 						queue_sync_ecaps(pos, cid);
2036 				}
2037 			}
2038 
2039 			if (revoked_caps)
2040 				pos = scx_next_descendant_pre(pos, child);
2041 			else
2042 				pos = scx_skip_subtree_pre(pos, child);
2043 		}
2044 	}
2045 
2046 	caps_updated_deliver(&to_deliver);
2047 }
2048 
2049 /**
2050  * scx_bpf_sub_caps - Read self's or a direct child's cap cmasks
2051  * @cgroup_id: 0 for self, or a direct child's cgroup id
2052  * @caps: one or more SCX_CAP_* bits
2053  * @out__ign: arena cmask to receive the union of @caps within its range
2054  * @aux: implicit BPF argument
2055  *
2056  * Read the cap cmasks granted on each cid for self (@cgroup_id 0) or a direct
2057  * child - the literal granted set. A sched can read only itself or a direct
2058  * child.
2059  *
2060  * Return 0, -ENODEV if @cgroup_id names no direct child, or -EINVAL on bad
2061  * inputs.
2062  */
2063 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__ign,
2064 				 const struct bpf_prog_aux *aux)
2065 {
2066 	struct scx_cmask_ref ref;
2067 	struct scx_sched *sch, *target;
2068 	struct scx_pshard **pshard;
2069 	s32 si, ret;
2070 
2071 	guard(irqsave)();
2072 
2073 	sch = scx_prog_sched(aux);
2074 	if (unlikely(!sch))
2075 		return -ENODEV;
2076 
2077 	if (!scx_is_cid_type()) {
2078 		scx_error(sch, "sub-cap kfuncs require a cid-form scheduler");
2079 		return -EOPNOTSUPP;
2080 	}
2081 
2082 	if (unlikely(caps & ~__SCX_CAP_ALL)) {
2083 		scx_error(sch, "invalid caps 0x%llx", caps);
2084 		return -EINVAL;
2085 	}
2086 
2087 	/* @cgroup_id 0 reads self, otherwise a direct child */
2088 	if (cgroup_id) {
2089 		target = scx_find_sub_sched(cgroup_id);
2090 		if (unlikely(!target))
2091 			return -ENODEV;
2092 		if (unlikely(scx_parent(target) != sch)) {
2093 			scx_error(sch, "%s: sub-%llu is not a direct child",
2094 				  sch->cgrp_path, cgroup_id);
2095 			return -EINVAL;
2096 		}
2097 	} else {
2098 		target = sch;
2099 	}
2100 
2101 	/*
2102 	 * The target's caps storage may not be set up yet (e.g. a self-read
2103 	 * during ops.init_cids()). Pairs with the publish in
2104 	 * scx_alloc_pshards(): a non-NULL pshard has every element set and the
2105 	 * acquire also orders the cid table reads below against it.
2106 	 */
2107 	pshard = smp_load_acquire(&target->pshard);
2108 	if (unlikely(!pshard)) {
2109 		scx_error(sch, "scx_bpf_sub_caps() called before caps storage is initialized");
2110 		return -ENODEV;
2111 	}
2112 
2113 	ret = scx_cmask_ref_init(sch, out__ign, &ref);
2114 	if (ret) {
2115 		scx_error(sch, "invalid out (%d)", ret);
2116 		return ret;
2117 	}
2118 
2119 	for (si = ref.shard_first; si < ref.shard_end; si++) {
2120 		const struct scx_cid_shard *shard =
2121 			&rcu_dereference_all(scx_cid_shard_ranges)[si];
2122 		SCX_CMASK_DEFINE_SHARD(local_out, shard->base_cid, shard->nr_cids);
2123 		u32 cap_bit;
2124 
2125 		scx_for_each_cap_bit(cap_bit, caps)
2126 			scx_cmask_or(local_out, &pshard[si]->caps[cap_bit].cmask);
2127 		scx_cmask_ref_copy(&ref, local_out);
2128 	}
2129 	return 0;
2130 }
2131 
2132 /**
2133  * scx_bpf_sub_kill_bstr - Kill a direct child sub-scheduler
2134  * @cgroup_id: cgroup id of the direct child to kill
2135  * @fmt: reason message format string
2136  * @data: format string parameters packaged using ___bpf_fill() macro
2137  * @data__sz: @data len, must end in '__sz' for the verifier
2138  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
2139  *
2140  * Evict a direct child sub-scheduler, disabling it with the supplied reason.
2141  * The child and its subtree are torn down asynchronously through the usual
2142  * disable path.
2143  *
2144  * Unlike scx_bpf_exit(), no exit code is taken: the child is a separate
2145  * scheduler with its own exit-code semantics, so a code chosen by the parent
2146  * would have no defined meaning. The reason string carries the intent.
2147  *
2148  * Return 0 on success or -ENODEV if @cgroup_id names no sub-scheduler, which
2149  * can race with the child detaching on its own and so is not a scheduler error.
2150  * Naming a sched that exists but is not a direct child aborts the parent.
2151  */
2152 __printf(2, 0)
2153 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt,
2154 				      unsigned long long *data, u32 data__sz,
2155 				      const struct bpf_prog_aux *aux)
2156 {
2157 	struct scx_sched *parent, *child;
2158 	s32 ret;
2159 
2160 	guard(rcu)();
2161 
2162 	parent = scx_prog_sched(aux);
2163 	if (unlikely(!parent))
2164 		return -ENODEV;
2165 
2166 	if (!scx_is_cid_type()) {
2167 		scx_error(parent, "sub-cap kfuncs require a cid-form scheduler");
2168 		return -EOPNOTSUPP;
2169 	}
2170 
2171 	child = scx_find_sub_sched(cgroup_id);
2172 	if (unlikely(!child))
2173 		return -ENODEV;
2174 
2175 	if (unlikely(scx_parent(child) != parent)) {
2176 		scx_error(parent, "%s: sub-%llu is not a direct child",
2177 			  parent->cgrp_path, cgroup_id);
2178 		return -EINVAL;
2179 	}
2180 
2181 	guard(raw_spinlock_irqsave)(&scx_exit_bstr_buf_lock);
2182 	ret = scx_bstr_format(parent, &scx_exit_bstr_buf, fmt, data, data__sz);
2183 	if (ret < 0)
2184 		return ret;
2185 	scx_exit(child, SCX_EXIT_PARENT_KILL, 0, "%s", scx_exit_bstr_buf.line);
2186 	return 0;
2187 }
2188 
2189 __bpf_kfunc_end_defs();
2190 
2191 #endif	/* CONFIG_EXT_SUB_SCHED */
2192