xref: /linux/kernel/sched/ext/sub.c (revision 8946dbd3aa91acfb75b1633859290ba248e313b2)
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 = &scx_cid_shard_ranges[shard_idx];
142 	size_t cmask_size = struct_size_t(struct scx_cmask, bits,
143 					  SCX_CMASK_NR_WORDS(shard->nr_cids));
144 	struct scx_pshard *pshard;
145 	struct scx_caps_updated *cu;
146 	s32 i;
147 
148 	pshard = kzalloc_node(sizeof(*pshard), GFP_KERNEL, node);
149 	if (!pshard)
150 		return NULL;
151 
152 	raw_spin_lock_init(&pshard->lock);
153 	pshard->sch = sch;
154 	pshard->base = shard->base_cid;
155 	pshard->nr_cids = shard->nr_cids;
156 
157 	for (i = 0; i < __SCX_NR_CAPS; i++)
158 		scx_cmask_init(&pshard->caps[i].cmask, shard->base_cid, shard->nr_cids);
159 
160 	cu = &pshard->caps_updated;
161 	raw_spin_lock_init(&cu->lock);
162 	INIT_LIST_HEAD(&cu->node_in_flight);
163 	__scx_cmask_init(&cu->cmask, shard->base_cid, shard->nr_cids, SCX_CID_SHARD_MAX_CPUS);
164 
165 	cu->cmask_arena_out = scx_arena_alloc(sch, cmask_size);
166 	if (!cu->cmask_arena_out) {
167 		free_pshard(pshard);
168 		return NULL;
169 	}
170 
171 	scx_cmask_init(cu->cmask_arena_out, shard->base_cid, shard->nr_cids);
172 
173 	return pshard;
174 }
175 
176 s32 scx_alloc_pshards(struct scx_sched *sch)
177 {
178 	struct scx_pshard **pshard;
179 	s32 si;
180 
181 	if (!sch->is_cid_type || !sch->arena_pool)
182 		return 0;
183 
184 	pshard = kzalloc_objs(pshard[0], scx_nr_cid_shards, GFP_KERNEL);
185 	if (!pshard)
186 		return -ENOMEM;
187 
188 	for (si = 0; si < scx_nr_cid_shards; si++) {
189 		pshard[si] = alloc_pshard(sch, si, scx_shard_node[si]);
190 		if (!pshard[si]) {
191 			while (--si >= 0)
192 				free_pshard(pshard[si]);
193 			kfree(pshard);
194 			return -ENOMEM;
195 		}
196 	}
197 
198 	sch->nr_pshards = scx_nr_cid_shards;
199 	/*
200 	 * Publish only after every entry is built so a reader observing
201 	 * @sch->pshard never sees a partially-filled array. Pair the store
202 	 * with a barrier and READ_ONCE() on the read side.
203 	 */
204 	smp_wmb();
205 	WRITE_ONCE(sch->pshard, pshard);
206 	return 0;
207 }
208 
209 /*
210  * Seed the root's caps fully. Root owns all cids on all caps at enable time.
211  * Children acquire caps via scx_bpf_sub_grant().
212  */
213 void scx_init_root_caps(struct scx_sched *sch)
214 {
215 	s32 si, i;
216 
217 	for (si = 0; si < sch->nr_pshards; si++) {
218 		struct scx_pshard *ps = sch->pshard[si];
219 
220 		for (i = 0; i < __SCX_NR_CAPS; i++)
221 			scx_cmask_fill(&ps->caps[i].cmask);
222 	}
223 }
224 
225 /**
226  * scx_local_or_reject_dsq - Pick the local or reject DSQ for an insert
227  * @sch: enqueuing sub-sched
228  * @rq: rq whose local DSQ @p targets
229  * @p: task being inserted
230  * @enq_flags: in/out, unhonored flags are cleared
231  *
232  * Return @rq's local DSQ if @sch holds the required caps on @rq's cid,
233  * otherwise @rq's reject DSQ after recording the reenq reason on @p.
234  *
235  * %SCX_ENQ_IMMED and %SCX_ENQ_PREEMPT are cleared when diverting to reject.
236  * %SCX_ENQ_PREEMPT is also cleared on a fallback migration-disabled admission.
237  *
238  * Bypass doesn't need special-casing as a bypassing sched's tasks are enqueued
239  * to and run by its nearest non-bypassing ancestor. If root is bypassing, it
240  * always holds all caps.
241  */
242 struct scx_dispatch_q *scx_local_or_reject_dsq(struct scx_sched *sch, struct rq *rq,
243 					       struct task_struct *p, u64 *enq_flags)
244 {
245 	if (!scx_has_subs())
246 		return &rq->scx.local_dsq;
247 
248 	s32 cid = __scx_cpu_to_cid(cpu_of(rq));
249 	struct scx_sched *asch = rq->scx.remote_activate_sch ?: sch;
250 	u64 needed = scx_caps_for_enq(*enq_flags);
251 	u64 missing;
252 
253 	/*
254 	 * On a remote activation the scheduling sched (@asch) differs from
255 	 * @p's owner (@sch). Check caps against the scheduling sched.
256 	 */
257 	if (*enq_flags & SCX_ENQ_PREEMPT)
258 		needed |= scx_caps_for_preempt(asch, rq);
259 	missing = scx_missing_caps(asch, cpu_of(rq), needed);
260 
261 	/* requirements met */
262 	if (likely(!missing))
263 		return &rq->scx.local_dsq;
264 
265 	/*
266 	 * The task must run on this CPU regardless of caps: the rq is draining
267 	 * offline (BPF scheduler bypassed), the task is migration-disabled, or a
268 	 * migration is pending. Admit despite the missing caps and count it.
269 	 * Refuse preemptions.
270 	 */
271 	if (unlikely(!scx_rq_online(rq) || is_migration_disabled(p) ||
272 		     p->migration_pending)) {
273 		__scx_add_event(sch, SCX_EV_SUB_FORCED_ADMIT, 1);
274 		*enq_flags &= ~SCX_ENQ_PREEMPT;
275 		return &rq->scx.local_dsq;
276 	}
277 
278 	p->scx.reenq_reason_caps = missing;
279 	p->scx.reenq_reason_cid = cid;
280 
281 	/*
282 	 * Only local DSQ can honor IMMED and dsq_inc_nr() WARNs on IMMED into
283 	 * others. Strip both the enq flag and the sticky task flag - the
284 	 * latter can carry in from an earlier admitted IMMED insert. Strip
285 	 * PREEMPT too.
286 	 */
287 	*enq_flags &= ~(SCX_ENQ_IMMED | SCX_ENQ_PREEMPT);
288 	p->scx.flags &= ~SCX_TASK_IMMED;
289 
290 	return &rq->scx.reject_dsq;
291 }
292 
293 /* @p lost the caps needed to stay on @rq's local DSQ? Record reason if so. */
294 bool scx_task_reenq_on_cap_revoke(struct rq *rq, struct task_struct *p)
295 {
296 	u64 missing;
297 
298 	/* migration-disabled tasks are admitted regardless of caps */
299 	if (is_migration_disabled(p))
300 		return false;
301 
302 	missing = scx_missing_caps(scx_task_sched(p), cpu_of(rq), scx_caps_for_task(p));
303 	if (likely(!missing))
304 		return false;
305 
306 	p->scx.reenq_reason_caps = missing;
307 	p->scx.reenq_reason_cid = __scx_cpu_to_cid(cpu_of(rq));
308 	return true;
309 }
310 
311 /*
312  * Drain @rq->scx.reject_dsq, reenqueueing each task so the BPF re-decides
313  * from p->scx.reenq_reason_*.
314  *
315  * A task can be re-rejected repeatedly, and there's no repeat limit here.
316  * Rejection can't happen for root, and sub-scheds can be safely ejected after
317  * triggering the stall watchdog.
318  */
319 void scx_reenq_reject(struct rq *rq)
320 {
321 	LIST_HEAD(tasks);
322 	struct task_struct *p, *n;
323 
324 	lockdep_assert_rq_held(rq);
325 
326 	if (!scx_has_subs() || list_empty(&rq->scx.reject_dsq.list))
327 		return;
328 
329 	/*
330 	 * Move to a private list so a task re-rejected by the
331 	 * scx_do_enqueue_task() below isn't revisited this round.
332 	 */
333 	list_for_each_entry_safe(p, n, &rq->scx.reject_dsq.list, scx.dsq_list.node) {
334 		/* migration_pending tasks should have bypassed to local DSQ */
335 		if (WARN_ON_ONCE(p->migration_pending))
336 			continue;
337 
338 		scx_dispatch_dequeue(rq, p);
339 
340 		if (WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK))
341 			p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
342 		p->scx.flags |= SCX_TASK_REENQ_CAP;
343 
344 		list_add_tail(&p->scx.dsq_list.node, &tasks);
345 	}
346 
347 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
348 		list_del_init(&p->scx.dsq_list.node);
349 
350 		scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
351 
352 		p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
353 	}
354 }
355 
356 /* record a caps change, see struct scx_caps_updated */
357 static void caps_updated_record(struct scx_pshard *ps, const struct scx_cmask *cids, u64 caps,
358 				struct list_head *to_deliver)
359 {
360 	struct scx_caps_updated *cu = &ps->caps_updated;
361 
362 	guard(raw_spinlock)(&cu->lock);
363 	scx_cmask_or(&cu->cmask, cids);
364 	cu->caps |= caps;
365 	if (list_empty(&cu->node_in_flight))
366 		list_add_tail(&cu->node_in_flight, to_deliver);
367 }
368 
369 /* deliver queued caps_updated callbacks, see struct scx_caps_updated */
370 static void caps_updated_deliver(struct list_head *to_deliver)
371 {
372 	struct scx_caps_updated *cu, *tmp;
373 
374 	list_for_each_entry_safe(cu, tmp, to_deliver, node_in_flight) {
375 		struct scx_pshard *ps = container_of(cu, struct scx_pshard, caps_updated);
376 		struct scx_sched *sch = ps->sch;
377 
378 		while (true) {
379 			u64 caps = 0;
380 
381 			/*
382 			 * During enable, has_op is set after ops.sub_attach(),
383 			 * so !has_op means the op is absent or the sched isn't
384 			 * live yet - e.g. caps grant from ops.sub_attach().
385 			 * Either way don't consume - leave for
386 			 * scx_sub_seed_caps() to deliver once live.
387 			 */
388 			scoped_guard (raw_spinlock, &cu->lock) {
389 				if (cu->caps && SCX_HAS_OP(sch, sub_caps_updated) &&
390 				    likely(!READ_ONCE(sch->aborting))) {
391 					struct scx_cmask_ref ref;
392 
393 					caps = cu->caps;
394 					scx_cmask_ref_init_kern(sch, cu->cmask_arena_out,
395 								ps->base, ps->nr_cids, &ref);
396 					scx_cmask_ref_copy(&ref, &cu->cmask);
397 					scx_cmask_clear(&cu->cmask);
398 					cu->caps = 0;
399 				} else {
400 					list_del_init(&cu->node_in_flight);
401 				}
402 			}
403 			if (!caps)
404 				break;
405 
406 			/* caps != 0 only when deliverable (has_op, above) */
407 			SCX_CALL_OP(sch, sub_caps_updated, NULL,
408 				    scx_kaddr_to_arena(sch, cu->cmask_arena_out),
409 				    caps);
410 		}
411 	}
412 }
413 
414 /*
415  * Deliver caps owed to @sch that couldn't be delivered earlier (e.g. a grant
416  * taken during its sub_attach(), before has_op was set). Called once @sch is
417  * enabled.
418  */
419 static void scx_sub_seed_caps(struct scx_sched *sch)
420 {
421 	LIST_HEAD(to_deliver);
422 	s32 si;
423 
424 	guard(irqsave)();
425 
426 	for (si = 0; si < sch->nr_pshards; si++) {
427 		struct scx_pshard *ps = sch->pshard[si];
428 		struct scx_caps_updated *cu = &ps->caps_updated;
429 
430 		scoped_guard (raw_spinlock, &cu->lock) {
431 			if (cu->caps && list_empty(&cu->node_in_flight))
432 				list_add_tail(&cu->node_in_flight, &to_deliver);
433 		}
434 	}
435 	caps_updated_deliver(&to_deliver);
436 }
437 
438 static u64 calc_effective_caps(struct scx_pshard *ps, s32 cid)
439 {
440 	u64 ecaps = 0;
441 	u32 cap_bit;
442 
443 	for (cap_bit = 0; cap_bit < __SCX_NR_CAPS; cap_bit++)
444 		if (scx_cmask_test(cid, &ps->caps[cap_bit].cmask))
445 			ecaps |= BIT_U64(cap_bit) | scx_caps_implied(BIT_U64(cap_bit));
446 	return ecaps;
447 }
448 
449 /**
450  * queue_sync_ecaps - Queue ecaps update for a (sch, cid) pair
451  * @sch: sched to update
452  * @cid: cid to update
453  *
454  * Queue an ecaps update for @sch's @cid and kick the cpu so that it syncs in
455  * balance_one().
456  */
457 static void queue_sync_ecaps(struct scx_sched *sch, s32 cid)
458 {
459 	s32 cpu = __scx_cid_to_cpu(cid);
460 	struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
461 
462 	/*
463 	 * Pairs with smp_mb() in scx_process_sync_ecaps(). Either the check
464 	 * below sees the node off the list and queues it, or the in-flight sync
465 	 * sees the caps[] update made before this call.
466 	 */
467 	smp_mb();
468 
469 	/* @cid's pshard->lock excludes concurrent queueing attempts */
470 	if (llist_on_list(&pcpu->ecaps_to_sync_node))
471 		return;
472 	if (llist_add(&pcpu->ecaps_to_sync_node, &cpu_rq(cpu)->scx.ecaps_to_sync))
473 		scx_kick_cpu(scx_root, cpu, 0);
474 }
475 
476 /* discard @rq's queued ecaps syncs */
477 static void discard_queued_syncs(struct rq *rq)
478 {
479 	struct llist_node *pos, *tmp;
480 
481 	lockdep_assert_rq_held(rq);
482 
483 	llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync))
484 		init_llist_node(pos);
485 }
486 
487 /**
488  * scx_process_sync_ecaps - Sync this cpu's ecaps to pshard->caps[]
489  * @rq: the cid's cpu rq
490  * @prev: @rq's previous task from the in-progress balance
491  *
492  * pshard->caps[] is the target configuration. pcpu->ecaps is the effective
493  * transposed copy owned by the cid's cpu and written only here under @rq's
494  * lock.
495  *
496  * A sched that newly gains baseline access here is owed an update_idle() so it
497  * learns the cid's idle state. Such a gain arms the per-rq
498  * %SCX_RQ_SUB_IDLE_RENOTIFY gate so the next idle pick delivers it.
499  */
500 void scx_process_sync_ecaps(struct rq *rq, struct task_struct *prev)
501 {
502 	s32 cpu = cpu_of(rq);
503 	s32 cid, shard;
504 	struct llist_node *batch, *pos, *tmp;
505 	u64 lost_all = 0;
506 
507 	lockdep_assert_rq_held(rq);
508 
509 	if (!scx_has_subs() || likely(llist_empty(&rq->scx.ecaps_to_sync)))
510 		return;
511 
512 	/*
513 	 * ecaps are zeroed while the cpu is inactive and must stay zero.
514 	 * Discard queued syncs instead of processing them - the
515 	 * scx_online_ecaps() reseed re-syncs every sched on activation.
516 	 * cpu_active() clears before the offline zeroing and sets before the
517 	 * reseed is queued, so this test can neither miss a racing sync nor
518 	 * eat the reseed.
519 	 */
520 	if (unlikely(!cpu_active(cpu))) {
521 		discard_queued_syncs(rq);
522 		return;
523 	}
524 
525 	/* @cid is valid here: the cpu is active with queued syncs */
526 	cid = __scx_cpu_to_cid(cpu);
527 	shard = scx_cid_to_shard[cid];
528 
529 	batch = llist_del_all(&rq->scx.ecaps_to_sync);
530 	llist_for_each_safe(pos, tmp, batch) {
531 		struct scx_sched_pcpu *pcpu =
532 			container_of(pos, struct scx_sched_pcpu, ecaps_to_sync_node);
533 		struct scx_pshard *ps = pcpu->sch->pshard[shard];
534 		u64 old, ecaps, lost, gained;
535 
536 		init_llist_node(pos);
537 
538 		/* pairs with smp_mb() in queue_sync_ecaps(), see there */
539 		smp_mb();
540 
541 		old = READ_ONCE(pcpu->ecaps);
542 		ecaps = calc_effective_caps(ps, cid);
543 		WRITE_ONCE(pcpu->ecaps, ecaps);
544 
545 		lost = old & ~ecaps;
546 		gained = ecaps & ~old;
547 		lost_all |= lost;
548 
549 		/*
550 		 * Tell the sched its effective caps on this cid changed. The
551 		 * invocation is equivalent to the dispatch path and may drop
552 		 * and re-acquire the rq lock temporarily while the rest of
553 		 * @batch is held privately, see scx_discard_ecaps_to_sync().
554 		 */
555 		if (ecaps != pcpu->reported_ecaps &&
556 		    SCX_HAS_OP(pcpu->sch, sub_ecaps_updated) &&
557 		    !scx_bypassing(pcpu->sch, cpu)) {
558 			struct scx_dsp_ctx *dspc = &pcpu->dsp_ctx;
559 
560 			dspc->rq = rq;
561 			/* stash @prev so nested dispatches can access it */
562 			rq->scx.sub_dispatch_prev = prev;
563 			SCX_CALL_OP(pcpu->sch, sub_ecaps_updated, rq, scx_cpu_arg(cpu),
564 				    pcpu->reported_ecaps, ecaps);
565 			rq->scx.sub_dispatch_prev = NULL;
566 			scx_flush_dispatch_buf(pcpu->sch, rq);
567 			pcpu->reported_ecaps = ecaps;
568 		}
569 
570 		/*
571 		 * Gaining baseline access owes an update_idle() so the sched
572 		 * learns the cpu's idle state. Arm the per-rq gate so the next
573 		 * idle pick flushes it. Losing access drops any pending notify.
574 		 */
575 		if (gained & SCX_CAP_BASE) {
576 			pcpu->idle_renotify = true;
577 			rq->scx.flags |= SCX_RQ_SUB_IDLE_RENOTIFY;
578 		} else if (lost & SCX_CAP_BASE) {
579 			pcpu->idle_renotify = false;
580 		}
581 	}
582 
583 	/*
584 	 * Losing a cap can strand already-queued tasks. Schedule a reenq scan
585 	 * to move the now-capless ones off the local DSQ. The scan tests
586 	 * against the effective caps and thus must come after the ecaps sync.
587 	 */
588 	if (lost_all & SCX_CAPS_REENQ_ON_LOSS)
589 		scx_schedule_reenq_local(rq, SCX_REENQ_CAP_REVOKE);
590 }
591 
592 /**
593  * scx_unbypass_replay_ecaps - Replay a bypass-suppressed ecaps notification
594  * @rq: rq of the cpu leaving bypass
595  * @sch: scheduler that just left bypass on @rq's cpu
596  *
597  * scx_process_sync_ecaps() consumes syncs while bypassing without delivering
598  * ops.sub_ecaps_updated(), leaving reported_ecaps stale. Nothing re-queues a
599  * sync when bypass lifts, so without a replay a cid that never changes again
600  * would never be notified. The attach-time initial grants are the acute case
601  * as they are consumed during the enable bypass window. Re-queue a sync for
602  * any undelivered delta so the next balance delivers it.
603  */
604 void scx_unbypass_replay_ecaps(struct rq *rq, struct scx_sched *sch)
605 {
606 	s32 cpu = cpu_of(rq);
607 	struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
608 	struct scx_pshard *ps;
609 	s32 cid;
610 
611 	lockdep_assert_rq_held(rq);
612 
613 	/* root holds every cap and never uses ecaps */
614 	if (!sch->level)
615 		return;
616 
617 	if (READ_ONCE(pcpu->ecaps) == pcpu->reported_ecaps)
618 		return;
619 
620 	cid = __scx_cpu_to_cid(cpu);
621 	ps = sch->pshard[scx_cid_to_shard[cid]];
622 
623 	guard(raw_spinlock)(&ps->lock);
624 	queue_sync_ecaps(sch, cid);
625 }
626 
627 /*
628  * A cpu came back. Re-seed each sub-sched's ecaps on the cpu's cid. The sync
629  * recomputes effective caps from the pshard and fires ops.sub_ecaps_updated()
630  * only on a real change since offline.
631  */
632 void scx_online_ecaps(struct rq *rq)
633 {
634 	s32 cid = __scx_cpu_to_cid(cpu_of(rq));
635 	s32 shard = scx_cid_to_shard[cid];
636 	struct scx_sched *pos;
637 
638 	guard(rq_lock_irqsave)(rq);
639 
640 	scx_for_each_descendant_pre(pos, scx_root) {
641 		struct scx_pshard *ps;
642 
643 		/* root holds every cap and never uses ecaps */
644 		if (pos == scx_root)
645 			continue;
646 
647 		ps = pos->pshard[shard];
648 		guard(raw_spinlock)(&ps->lock);
649 		queue_sync_ecaps(pos, cid);
650 	}
651 }
652 
653 /*
654  * A cpu is going down. Zero each sub-sched's in-effect ecaps so cap checks
655  * treat the cpu as capless while offline. Pending and late-queued syncs are
656  * discarded at consumption by scx_process_sync_ecaps() while the cpu is
657  * inactive. Leave reported_ecaps. Ownership is unchanged, so the
658  * scx_online_ecaps() reseed reports only a genuine delta. No callback fires
659  * here.
660  */
661 void scx_offline_ecaps(struct rq *rq)
662 {
663 	s32 cpu = cpu_of(rq);
664 	struct scx_sched *pos;
665 
666 	guard(rq_lock_irqsave)(rq);
667 
668 	scx_for_each_descendant_pre(pos, scx_root) {
669 		/* root holds every cap and never uses ecaps */
670 		if (pos == scx_root)
671 			continue;
672 
673 		WRITE_ONCE(per_cpu_ptr(pos->pcpu, cpu)->ecaps, 0);
674 	}
675 }
676 
677 /*
678  * @pcpu's sched was unhashed before the grace period, so nothing re-queues its
679  * sync node. Remove the node from @rq's pending list so the pcpu can be freed.
680  */
681 void scx_discard_ecaps_to_sync(s32 cpu, struct scx_sched_pcpu *pcpu)
682 {
683 	struct rq *rq = cpu_rq(cpu);
684 	struct llist_node *head = NULL, *tail = NULL;
685 	struct llist_node *pos, *tmp;
686 
687 	/*
688 	 * llist can't unlink a single node. Take all queued nodes, drop @pcpu's
689 	 * and resplice the rest. Nodes in the taken batch read as on-list
690 	 * throughout, so queue_sync_ecaps() stays correct.
691 	 */
692 	if (llist_on_list(&pcpu->ecaps_to_sync_node)) {
693 		scoped_guard (rq_lock_irqsave, rq) {
694 			llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) {
695 				if (pos == &pcpu->ecaps_to_sync_node) {
696 					init_llist_node(pos);
697 				} else {
698 					pos->next = head;
699 					head = pos;
700 					if (!tail)
701 						tail = pos;
702 				}
703 			}
704 			if (head)
705 				llist_add_batch(head, tail, &rq->scx.ecaps_to_sync);
706 		}
707 	}
708 
709 	/*
710 	 * An in-flight scx_process_sync_ecaps() batch may still hold the node
711 	 * privately across dispatch-induced rq unlocks, reading as on-list.
712 	 *
713 	 * Because a bypassing sched gets no op call, init_llist_node() and all
714 	 * @pcpu accesses share one contiguous lock hold, off-list under the rq
715 	 * lock means @pcpu won't be accessed again.
716 	 */
717 	while (true) {
718 		scoped_guard (rq_lock_irqsave, rq) {
719 			if (!llist_on_list(&pcpu->ecaps_to_sync_node))
720 				return;
721 		}
722 		cpu_relax();
723 	}
724 }
725 
726 /**
727  * scx_discard_stale_ecaps_syncs - Discard ecaps syncs from earlier schedulers
728  *
729  * To be called during root enable before the scheduler goes live. An earlier
730  * root's sub-sched may not have gone through its RCU free path yet (e.g. a
731  * still-open link fd defers it) and can leave queued ecaps syncs behind.
732  * Processing them would decode the dead sched's pshards with the current cid
733  * layout. Discard them instead. The backing scx_sched_pcpu's are still
734  * allocated as the free path removes ecaps_to_sync_node before freeing.
735  */
736 void scx_discard_stale_ecaps_syncs(void)
737 {
738 	s32 cpu;
739 
740 	for_each_possible_cpu(cpu) {
741 		struct rq *rq = cpu_rq(cpu);
742 
743 		guard(rq_lock_irqsave)(rq);
744 		discard_queued_syncs(rq);
745 	}
746 }
747 
748 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq);
749 
750 void drain_descendants(struct scx_sched *sch)
751 {
752 	/*
753 	 * Child scheds that finished the critical part of disabling will take
754 	 * themselves off @sch->children. Wait for it to drain. As propagation
755 	 * is recursive, empty @sch->children means that all proper descendant
756 	 * scheds reached unlinking stage.
757 	 */
758 	wait_event(scx_unlink_waitq, list_empty(&sch->children));
759 }
760 
761 static void scx_fail_parent(struct scx_sched *sch,
762 			    struct task_struct *failed, s32 fail_code)
763 {
764 	struct scx_sched *parent = scx_parent(sch);
765 	struct scx_task_iter sti;
766 	struct task_struct *p;
767 
768 	scx_error(parent, "ops.init_task() failed (%d) for %s[%d] while disabling a sub-scheduler",
769 		  fail_code, failed->comm, failed->pid);
770 
771 	/*
772 	 * Once $parent is bypassed, it's safe to put SCX_TASK_NONE tasks into
773 	 * it. This may cause downstream failures on the BPF side but $parent is
774 	 * dying anyway.
775 	 */
776 	scx_bypass(parent, true);
777 
778 	scx_task_iter_start(&sti, sch->cgrp);
779 	while ((p = scx_task_iter_next_locked(&sti))) {
780 		if (scx_task_on_sched(parent, p))
781 			continue;
782 
783 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
784 			scx_disable_and_exit_task(sch, p);
785 			scx_set_task_sched(p, parent);
786 		}
787 	}
788 	scx_task_iter_stop(&sti);
789 }
790 
791 void scx_sub_disable(struct scx_sched *sch)
792 {
793 	struct scx_sched *parent = scx_parent(sch);
794 	struct scx_task_iter sti;
795 	struct task_struct *p;
796 	int ret;
797 
798 	/*
799 	 * Guarantee forward progress and wait for descendants to be disabled.
800 	 * To limit disruptions, $parent is not bypassed. Tasks are fully
801 	 * prepped and then inserted back into $parent.
802 	 */
803 	scx_bypass(sch, true);
804 	drain_descendants(sch);
805 
806 	/*
807 	 * Here, every runnable task is guaranteed to make forward progress and
808 	 * we can safely use blocking synchronization constructs. Actually
809 	 * disable ops.
810 	 */
811 	mutex_lock(&scx_enable_mutex);
812 	percpu_down_write(&scx_fork_rwsem);
813 	scx_cgroup_lock();
814 
815 	set_cgroup_sched(sch_cgroup(sch), parent);
816 
817 	scx_task_iter_start(&sti, sch->cgrp);
818 	while ((p = scx_task_iter_next_locked(&sti))) {
819 		struct rq *rq;
820 		struct rq_flags rf;
821 
822 		/* filter out duplicate visits */
823 		if (scx_task_on_sched(parent, p))
824 			continue;
825 
826 		/*
827 		 * By the time control reaches here, all descendant schedulers
828 		 * should already have been disabled.
829 		 */
830 		WARN_ON_ONCE(!scx_task_on_sched(sch, p));
831 
832 		/*
833 		 * @p is pinned by the iter: css_task_iter_next() takes a
834 		 * reference and holds it until the next iter_next() call, so
835 		 * @p->usage is guaranteed > 0.
836 		 */
837 		get_task_struct(p);
838 
839 		scx_task_iter_unlock(&sti);
840 
841 		/*
842 		 * $p is READY or ENABLED on @sch. Initialize for $parent,
843 		 * disable and exit from @sch, and then switch over to $parent.
844 		 *
845 		 * If a task fails to initialize for $parent, the only available
846 		 * action is disabling $parent too. While this allows disabling
847 		 * of a child sched to cause the parent scheduler to fail, the
848 		 * failure can only originate from ops.init_task() of the
849 		 * parent. A child can't directly affect the parent through its
850 		 * own failures.
851 		 */
852 		ret = __scx_init_task(parent, p, false);
853 		if (ret) {
854 			scx_fail_parent(sch, p, ret);
855 			put_task_struct(p);
856 			break;
857 		}
858 
859 		rq = task_rq_lock(p, &rf);
860 
861 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
862 			/*
863 			 * sched_ext_dead() raced us between __scx_init_task()
864 			 * and this rq lock and ran exit_task() on @sch (the
865 			 * sched @p was on at that point), not on $parent.
866 			 * $parent's just-completed init is owed an exit_task()
867 			 * and we issue it here.
868 			 */
869 			scx_sub_init_cancel_task(parent, p);
870 			task_rq_unlock(rq, p, &rf);
871 			put_task_struct(p);
872 			continue;
873 		}
874 
875 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
876 			/*
877 			 * $p is initialized for $parent and still attached to
878 			 * @sch. Disable and exit for @sch, switch over to
879 			 * $parent, override the state to READY to account for
880 			 * $p having already been initialized, and then enable.
881 			 */
882 			scx_disable_and_exit_task(sch, p);
883 			scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
884 			scx_set_task_state(p, SCX_TASK_INIT);
885 			scx_set_task_sched(p, parent);
886 			scx_set_task_state(p, SCX_TASK_READY);
887 			scx_enable_task(parent, p);
888 		}
889 
890 		task_rq_unlock(rq, p, &rf);
891 		put_task_struct(p);
892 	}
893 	scx_task_iter_stop(&sti);
894 
895 	scx_disable_dump(sch);
896 
897 	scx_cgroup_unlock();
898 	percpu_up_write(&scx_fork_rwsem);
899 
900 	/*
901 	 * All tasks are moved off of @sch but there may still be on-going
902 	 * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use
903 	 * the expedited version as ancestors may be waiting in bypass mode.
904 	 * Also, tell the parent that there is no need to keep running bypass
905 	 * DSQs for us.
906 	 */
907 	synchronize_rcu_expedited();
908 	scx_disable_bypass_dsp(sch);
909 
910 	scx_unlink_sched(sch);
911 
912 	mutex_unlock(&scx_enable_mutex);
913 
914 	/*
915 	 * @sch is now unlinked from the parent's children list. Notify and call
916 	 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called
917 	 * after unlinking and releasing all locks. See scx_claim_exit().
918 	 */
919 	wake_up_all(&scx_unlink_waitq);
920 
921 	if (parent->ops.sub_detach && sch->sub_attached) {
922 		struct scx_sub_detach_args sub_detach_args = {
923 			.ops = &sch->ops,
924 			.cgroup_path = sch->cgrp_path,
925 		};
926 		SCX_CALL_OP(parent, sub_detach, NULL,
927 			    &sub_detach_args);
928 	}
929 
930 	scx_log_sched_disable(sch);
931 
932 	if (sch->ops.exit)
933 		SCX_CALL_OP(sch, exit, NULL, sch->exit_info);
934 
935 	/*
936 	 * @sch's non-ops programs such as timers and tracers can fire after
937 	 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from
938 	 * resolving to @sch and drain in-flight resolvers.
939 	 */
940 	WRITE_ONCE(sch->dead, true);
941 	synchronize_rcu();
942 
943 	if (sch->sub_kset)
944 		kobject_del(&sch->sub_kset->kobj);
945 	/* not added if enable failed before scx_sched_sysfs_add() */
946 	if (sch->kobj.state_in_sysfs)
947 		kobject_del(&sch->kobj);
948 }
949 
950 /* verify that a scheduler can be attached to @cgrp and return the parent */
951 static struct scx_sched *find_parent_sched(struct cgroup *cgrp)
952 {
953 	struct scx_sched *parent = cgrp->scx_sched;
954 	struct scx_sched *pos;
955 
956 	lockdep_assert_held(&scx_sched_lock);
957 
958 	/* can't attach twice to the same cgroup */
959 	if (parent->cgrp == cgrp)
960 		return ERR_PTR(-EBUSY);
961 
962 	/* does $parent allow sub-scheds? */
963 	if (!parent->ops.sub_attach)
964 		return ERR_PTR(-EOPNOTSUPP);
965 
966 	/* can't insert between $parent and its exiting children */
967 	list_for_each_entry(pos, &parent->children, sibling)
968 		if (cgroup_is_descendant(pos->cgrp, cgrp))
969 			return ERR_PTR(-EBUSY);
970 
971 	return parent;
972 }
973 
974 static bool assert_task_ready_or_enabled(struct task_struct *p)
975 {
976 	u32 state = scx_get_task_state(p);
977 
978 	switch (state) {
979 	case SCX_TASK_READY:
980 	case SCX_TASK_ENABLED:
981 		return true;
982 	default:
983 		WARN_ONCE(true, "sched_ext: Invalid task state %d for %s[%d] during enabling sub sched",
984 			  state, p->comm, p->pid);
985 		return false;
986 	}
987 }
988 
989 void scx_sub_enable_workfn(struct kthread_work *work)
990 {
991 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
992 	struct sched_ext_ops *ops = cmd->ops;
993 	struct cgroup *cgrp;
994 	struct scx_sched *parent, *sch;
995 	struct scx_task_iter sti;
996 	struct task_struct *p;
997 	s32 i, ret;
998 
999 	mutex_lock(&scx_enable_mutex);
1000 
1001 	if (!scx_enabled()) {
1002 		ret = -ENODEV;
1003 		goto out_unlock;
1004 	}
1005 
1006 	/* See scx_root_enable_workfn() for the @ops->priv check. */
1007 	if (rcu_access_pointer(ops->priv)) {
1008 		ret = -EBUSY;
1009 		goto out_unlock;
1010 	}
1011 
1012 	cgrp = cgroup_get_from_id(ops->sub_cgroup_id);
1013 	if (IS_ERR(cgrp)) {
1014 		ret = PTR_ERR(cgrp);
1015 		goto out_unlock;
1016 	}
1017 
1018 	raw_spin_lock_irq(&scx_sched_lock);
1019 	parent = find_parent_sched(cgrp);
1020 	if (IS_ERR(parent)) {
1021 		raw_spin_unlock_irq(&scx_sched_lock);
1022 		ret = PTR_ERR(parent);
1023 		goto out_put_cgrp;
1024 	}
1025 	kobject_get(&parent->kobj);
1026 	raw_spin_unlock_irq(&scx_sched_lock);
1027 
1028 	/*
1029 	 * Flip the hot-path gates before ops->priv is published - the sub's
1030 	 * programs can e.g. kick cpus from that point on. The matching dec is
1031 	 * at the end of scx_sched_free_rcu_work().
1032 	 */
1033 	static_branch_inc(&__scx_has_subs);
1034 
1035 	/* scx_alloc_and_add_sched() consumes @cgrp whether it succeeds or not */
1036 	sch = scx_alloc_and_add_sched(cmd, cgrp, parent);
1037 	kobject_put(&parent->kobj);
1038 	if (IS_ERR(sch)) {
1039 		static_branch_dec(&__scx_has_subs);
1040 		ret = PTR_ERR(sch);
1041 		goto out_unlock;
1042 	}
1043 
1044 	/*
1045 	 * Validate before scx_link_sched() publishes @sch, so an invalid sub
1046 	 * never becomes visible with an unallocated pshard.
1047 	 */
1048 	ret = scx_validate_ops(sch, ops);
1049 	if (ret)
1050 		goto err_disable;
1051 
1052 	/*
1053 	 * Allocate pshard[] before scx_link_sched() publishes @sch into the
1054 	 * parent's RCU children list. A concurrent revoke walking the tree
1055 	 * would otherwise dereference sch->pshard[si] while it's still NULL.
1056 	 * Unlike the root path, the cid shard layout is stable at this point.
1057 	 *
1058 	 * scx_alloc_pshards() skips allocation when @sch's arena pool isn't
1059 	 * initialized, so scx_arena_pool_init() must run first.
1060 	 */
1061 	ret = scx_arena_pool_init(sch);
1062 	if (ret)
1063 		goto err_disable;
1064 
1065 	ret = scx_alloc_pshards(sch);
1066 	if (ret)
1067 		goto err_disable;
1068 
1069 	ret = scx_link_sched(sch);
1070 	if (ret)
1071 		goto err_disable;
1072 
1073 	ret = scx_sched_sysfs_add(sch);
1074 	if (ret)
1075 		goto err_disable;
1076 
1077 	if (sch->level >= SCX_SUB_MAX_DEPTH) {
1078 		scx_error(sch, "max nesting depth %d violated",
1079 			  SCX_SUB_MAX_DEPTH);
1080 		goto err_disable;
1081 	}
1082 
1083 	if (sch->ops.init) {
1084 		ret = SCX_CALL_OP_RET(sch, init, NULL);
1085 		if (ret) {
1086 			ret = scx_ops_sanitize_err(sch, "init", ret);
1087 			scx_error(sch, "ops.init() failed (%d)", ret);
1088 			goto err_disable;
1089 		}
1090 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
1091 	}
1092 
1093 	ret = scx_set_cmask_scratch_alloc(sch);
1094 	if (ret)
1095 		goto err_disable;
1096 
1097 	struct scx_sub_attach_args sub_attach_args = {
1098 		.ops = &sch->ops,
1099 		.cgroup_path = sch->cgrp_path,
1100 	};
1101 
1102 	ret = SCX_CALL_OP_RET(parent, sub_attach, NULL,
1103 			      &sub_attach_args);
1104 	if (ret) {
1105 		ret = scx_ops_sanitize_err(sch, "sub_attach", ret);
1106 		scx_error(sch, "parent rejected (%d)", ret);
1107 		goto err_disable;
1108 	}
1109 	sch->sub_attached = true;
1110 
1111 	scx_bypass(sch, true);
1112 
1113 	for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++)
1114 		if (((void (**)(void))ops)[i])
1115 			set_bit(i, sch->has_op);
1116 
1117 	percpu_down_write(&scx_fork_rwsem);
1118 	scx_cgroup_lock();
1119 
1120 	/*
1121 	 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see
1122 	 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down.
1123 	 */
1124 	set_cgroup_sched(sch_cgroup(sch), sch);
1125 	if (!(cgrp->self.flags & CSS_ONLINE)) {
1126 		scx_error(sch, "cgroup is not online");
1127 		goto err_unlock_and_disable;
1128 	}
1129 
1130 	/*
1131 	 * Initialize tasks for the new child $sch without exiting them for
1132 	 * $parent so that the tasks can always be reverted back to $parent
1133 	 * sched on child init failure.
1134 	 */
1135 	WARN_ON_ONCE(scx_enabling_sub_sched);
1136 	scx_enabling_sub_sched = sch;
1137 
1138 	scx_task_iter_start(&sti, sch->cgrp);
1139 	while ((p = scx_task_iter_next_locked(&sti))) {
1140 		struct rq *rq;
1141 		struct rq_flags rf;
1142 
1143 		/*
1144 		 * Task iteration may visit the same task twice when racing
1145 		 * against exiting. Use %SCX_TASK_SUB_INIT to mark tasks which
1146 		 * finished __scx_init_task() and skip if set.
1147 		 *
1148 		 * A task may exit and get freed between __scx_init_task()
1149 		 * completion and scx_enable_task(). In such cases,
1150 		 * scx_disable_and_exit_task() must exit the task for both the
1151 		 * parent and child scheds.
1152 		 */
1153 		if (p->scx.flags & SCX_TASK_SUB_INIT)
1154 			continue;
1155 
1156 		/* @p is pinned by the iter; see scx_sub_disable() */
1157 		get_task_struct(p);
1158 
1159 		if (!assert_task_ready_or_enabled(p)) {
1160 			ret = -EINVAL;
1161 			goto abort;
1162 		}
1163 
1164 		scx_task_iter_unlock(&sti);
1165 
1166 		/*
1167 		 * As $p is still on $parent, it can't be transitioned to INIT.
1168 		 * Let's worry about task state later. Use __scx_init_task().
1169 		 */
1170 		ret = __scx_init_task(sch, p, false);
1171 		if (ret)
1172 			goto abort;
1173 
1174 		rq = task_rq_lock(p, &rf);
1175 
1176 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
1177 			/*
1178 			 * sched_ext_dead() raced us between __scx_init_task()
1179 			 * and this rq lock and ran exit_task() on $parent (the
1180 			 * sched @p was on at that point), not on @sch. @sch's
1181 			 * just-completed init is owed an exit_task() and we
1182 			 * issue it here.
1183 			 */
1184 			scx_sub_init_cancel_task(sch, p);
1185 			task_rq_unlock(rq, p, &rf);
1186 			put_task_struct(p);
1187 			continue;
1188 		}
1189 
1190 		p->scx.flags |= SCX_TASK_SUB_INIT;
1191 		task_rq_unlock(rq, p, &rf);
1192 
1193 		put_task_struct(p);
1194 	}
1195 	scx_task_iter_stop(&sti);
1196 
1197 	/*
1198 	 * All tasks are prepped. Disable/exit tasks for $parent and enable for
1199 	 * the new @sch.
1200 	 */
1201 	scx_task_iter_start(&sti, sch->cgrp);
1202 	while ((p = scx_task_iter_next_locked(&sti))) {
1203 		/*
1204 		 * Use clearing of %SCX_TASK_SUB_INIT to detect and skip
1205 		 * duplicate iterations.
1206 		 */
1207 		if (!(p->scx.flags & SCX_TASK_SUB_INIT))
1208 			continue;
1209 
1210 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
1211 			/*
1212 			 * $p must be either READY or ENABLED. If ENABLED,
1213 			 * __scx_disabled_and_exit_task() first disables and
1214 			 * makes it READY. However, after exiting $p, it will
1215 			 * leave $p as READY.
1216 			 */
1217 			assert_task_ready_or_enabled(p);
1218 			__scx_disable_and_exit_task(parent, p);
1219 
1220 			/*
1221 			 * $p is now only initialized for @sch and READY, which
1222 			 * is what we want. Assign it to @sch and enable.
1223 			 */
1224 			scx_set_task_sched(p, sch);
1225 			scx_enable_task(sch, p);
1226 
1227 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
1228 		}
1229 	}
1230 	scx_task_iter_stop(&sti);
1231 
1232 	scx_enabling_sub_sched = NULL;
1233 
1234 	scx_cgroup_unlock();
1235 	percpu_up_write(&scx_fork_rwsem);
1236 
1237 	scx_bypass(sch, false);
1238 
1239 	/* @sch is enabled; deliver any caps owed since its sub_attach() */
1240 	scx_sub_seed_caps(sch);
1241 
1242 	pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name);
1243 	kobject_uevent(&sch->kobj, KOBJ_ADD);
1244 	ret = 0;
1245 	goto out_unlock;
1246 
1247 out_put_cgrp:
1248 	cgroup_put(cgrp);
1249 out_unlock:
1250 	mutex_unlock(&scx_enable_mutex);
1251 	cmd->ret = ret;
1252 	return;
1253 
1254 abort:
1255 	put_task_struct(p);
1256 	scx_task_iter_stop(&sti);
1257 
1258 	/*
1259 	 * Undo __scx_init_task() for tasks we marked. scx_enable_task() never
1260 	 * ran for @sch on them, so calling scx_disable_task() here would invoke
1261 	 * ops.disable() without a matching ops.enable(). scx_enabling_sub_sched
1262 	 * must stay set until SUB_INIT is cleared from every marked task -
1263 	 * scx_disable_and_exit_task() reads it when a task exits concurrently.
1264 	 */
1265 	scx_task_iter_start(&sti, sch->cgrp);
1266 	while ((p = scx_task_iter_next_locked(&sti))) {
1267 		if (p->scx.flags & SCX_TASK_SUB_INIT) {
1268 			scx_sub_init_cancel_task(sch, p);
1269 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
1270 		}
1271 	}
1272 	scx_task_iter_stop(&sti);
1273 	scx_enabling_sub_sched = NULL;
1274 err_unlock_and_disable:
1275 	/* we'll soon enter disable path, keep bypass on */
1276 	scx_cgroup_unlock();
1277 	percpu_up_write(&scx_fork_rwsem);
1278 err_disable:
1279 	mutex_unlock(&scx_enable_mutex);
1280 	/*
1281 	 * Some enable failures only return an errno (e.g. -ENOMEM from an
1282 	 * allocation) without calling scx_error(). Record it so
1283 	 * scx_flush_disable_work() runs the disable and ops.exit() fires.
1284 	 */
1285 	scx_error(sch, "scx_sub_enable() failed (%d)", ret);
1286 	scx_flush_disable_work(sch);
1287 	cmd->ret = 0;
1288 }
1289 
1290 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb,
1291 				      unsigned long action, void *data)
1292 {
1293 	struct cgroup *cgrp = data;
1294 	struct cgroup *parent = cgroup_parent(cgrp);
1295 
1296 	if (!cgroup_on_dfl(cgrp))
1297 		return NOTIFY_OK;
1298 
1299 	switch (action) {
1300 	case CGROUP_LIFETIME_ONLINE:
1301 		/* inherit ->scx_sched from $parent */
1302 		if (parent)
1303 			rcu_assign_pointer(cgrp->scx_sched, parent->scx_sched);
1304 		break;
1305 	case CGROUP_LIFETIME_OFFLINE:
1306 		/* if there is a sched attached, shoot it down */
1307 		if (cgrp->scx_sched && cgrp->scx_sched->cgrp == cgrp)
1308 			scx_exit(cgrp->scx_sched, SCX_EXIT_UNREG_KERN,
1309 				 SCX_ECODE_RSN_CGROUP_OFFLINE,
1310 				 "cgroup %llu going offline", cgroup_id(cgrp));
1311 		break;
1312 	}
1313 
1314 	return NOTIFY_OK;
1315 }
1316 
1317 static struct notifier_block scx_cgroup_lifetime_nb = {
1318 	.notifier_call = scx_cgroup_lifetime_notify,
1319 };
1320 
1321 static s32 __init scx_cgroup_lifetime_notifier_init(void)
1322 {
1323 	return blocking_notifier_chain_register(&cgroup_lifetime_notifier,
1324 						&scx_cgroup_lifetime_nb);
1325 }
1326 core_initcall(scx_cgroup_lifetime_notifier_init);
1327 
1328 static void scx_pstack_recursion(struct bpf_prog *prog, const char *op)
1329 {
1330 	struct scx_sched *sch;
1331 
1332 	guard(rcu)();
1333 	sch = scx_prog_sched(prog->aux);
1334 	if (unlikely(!sch))
1335 		return;
1336 
1337 	scx_error(sch, "%s recursion detected", op);
1338 }
1339 
1340 void scx_pstack_recursion_on_dispatch(struct bpf_prog *prog)
1341 {
1342 	scx_pstack_recursion(prog, "dispatch");
1343 }
1344 
1345 void scx_pstack_recursion_on_caps_updated(struct bpf_prog *prog)
1346 {
1347 	scx_pstack_recursion(prog, "sub_caps_updated");
1348 }
1349 
1350 __bpf_kfunc_start_defs();
1351 
1352 /**
1353  * scx_bpf_sub_dispatch - Trigger dispatching on a child scheduler
1354  * @cgroup_id: cgroup ID of the child scheduler to dispatch
1355  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1356  *
1357  * Allows a parent scheduler to trigger dispatching on one of its direct
1358  * child schedulers. The child scheduler runs its dispatch operation to
1359  * move tasks from dispatch queues to the local runqueue.
1360  *
1361  * Returns: true on success, false if cgroup_id is invalid, not a direct
1362  * child, or caller lacks dispatch permission.
1363  */
1364 __bpf_kfunc bool scx_bpf_sub_dispatch(u64 cgroup_id, const struct bpf_prog_aux *aux)
1365 {
1366 	struct rq *this_rq = this_rq();
1367 	struct scx_sched *parent, *child;
1368 
1369 	guard(rcu)();
1370 	parent = scx_prog_sched(aux);
1371 	if (unlikely(!parent))
1372 		return false;
1373 
1374 	child = scx_find_sub_sched(cgroup_id);
1375 
1376 	if (unlikely(!child))
1377 		return false;
1378 
1379 	if (unlikely(scx_parent(child) != parent)) {
1380 		scx_error(parent, "trying to dispatch a distant sub-sched on cgroup %llu",
1381 			  cgroup_id);
1382 		return false;
1383 	}
1384 
1385 	/*
1386 	 * Skip a child that does not effectively hold the base cap on this cpu:
1387 	 * its inserts would only be rejected. ecaps are synced at the top of
1388 	 * balance_one() before dispatch, so this reflects the in-effect state.
1389 	 */
1390 	if (scx_missing_caps(child, cpu_of(this_rq), SCX_CAP_BASE))
1391 		return false;
1392 
1393 	return scx_dispatch_sched(child, this_rq, this_rq->scx.sub_dispatch_prev,
1394 				  true);
1395 }
1396 
1397 /* Validate common inputs. On success, *parent_out and *child_out are set. */
1398 static s32 sub_cap_preamble(u64 cgroup_id, u64 caps, const struct bpf_prog_aux *aux,
1399 			    struct scx_sched **parent_out, struct scx_sched **child_out)
1400 {
1401 	struct scx_sched *parent, *child;
1402 
1403 	parent = scx_prog_sched(aux);
1404 	if (unlikely(!parent))
1405 		return -ENODEV;
1406 
1407 	if (!scx_is_cid_type()) {
1408 		scx_error(parent, "sub-cap kfuncs require a cid-form scheduler");
1409 		return -EOPNOTSUPP;
1410 	}
1411 
1412 	child = scx_find_sub_sched(cgroup_id);
1413 	if (unlikely(!child))
1414 		return -ENODEV;
1415 
1416 	if (unlikely(scx_parent(child) != parent)) {
1417 		scx_error(parent, "%s: sub-%llu is not a direct child",
1418 			  parent->cgrp_path, cgroup_id);
1419 		return -EINVAL;
1420 	}
1421 
1422 	if (unlikely(caps & ~__SCX_CAP_ALL)) {
1423 		scx_error(parent, "invalid caps 0x%llx", caps);
1424 		return -EINVAL;
1425 	}
1426 
1427 	*parent_out = parent;
1428 	*child_out = child;
1429 	return 0;
1430 }
1431 
1432 /**
1433  * scx_bpf_sub_grant - Grant @caps on @cmask__ign's cids to a direct child
1434  * @cgroup_id: cgroup id of the direct child sub-sched
1435  * @caps: bitmask of SCX_CAP_* to grant
1436  * @cmask__ign: cid cmask to grant @caps on (arena pointer)
1437  * @denied_out__ign: optional arena cmask accumulating refused cids
1438  * @aux: implicit BPF argument
1439  *
1440  * A cid in @cmask__ign is granted to the child only if the parent holds every
1441  * requested cap on it. Refused cids are OR'd into @denied_out__ign when
1442  * provided. Refusals outside @denied_out__ign's range are not recorded.
1443  *
1444  * All-or-nothing keeps the caller-visible result binary per cid, so
1445  * @denied_out__ign is one mask to interpret rather than a per-cap matrix.
1446  *
1447  * Return 0 on full success, -EPERM if any cid was refused, or a negative
1448  * errno on other failures.
1449  */
1450 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps,
1451 				  const struct scx_cmask *cmask__ign,
1452 				  struct scx_cmask *denied_out__ign,
1453 				  const struct bpf_prog_aux *aux)
1454 {
1455 	struct scx_cmask_ref ref, denied_ref;
1456 	struct scx_sched *parent, *child;
1457 	bool any_denied = false;
1458 	LIST_HEAD(to_deliver);
1459 	s32 si, ret;
1460 
1461 	guard(irqsave)();
1462 
1463 	ret = sub_cap_preamble(cgroup_id, caps, aux, &parent, &child);
1464 	if (ret)
1465 		return ret;
1466 
1467 	ret = scx_cmask_ref_init(parent, cmask__ign, &ref);
1468 	if (ret) {
1469 		scx_error(parent, "invalid cmask (%d)", ret);
1470 		return ret;
1471 	}
1472 
1473 	if (denied_out__ign) {
1474 		ret = scx_cmask_ref_init(parent, denied_out__ign, &denied_ref);
1475 		if (ret) {
1476 			scx_error(parent, "invalid denied_out (%d)", ret);
1477 			return ret;
1478 		}
1479 	}
1480 
1481 	/* apply the grant one shard at a time */
1482 	for (si = ref.shard_first; si < ref.shard_end; si++) {
1483 		SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS);
1484 		struct scx_pshard *pps = parent->pshard[si];
1485 		struct scx_pshard *cps = child->pshard[si];
1486 		u64 granted_caps = 0;
1487 		u32 cap_bit;
1488 
1489 		scx_cmask_ref_shard(&ref, si, slice);
1490 		if (scx_cmask_empty(slice))
1491 			continue;
1492 
1493 		SCX_CMASK_DEFINE_SHARD(granted_cids, slice->base, slice->nr_cids);
1494 		SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids);
1495 		SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids);
1496 
1497 		scx_cmask_copy(granted_cids, slice);
1498 
1499 		scoped_guard (raw_spinlock, &pps->lock) {
1500 			guard(raw_spinlock_nested)(&cps->lock);
1501 
1502 			/*
1503 			 * Narrow granted_cids to cids the parent holds every
1504 			 * requested cap on. All-or-nothing per cid.
1505 			 */
1506 			scx_for_each_cap_bit(cap_bit, caps)
1507 				scx_cmask_and(granted_cids, &pps->caps[cap_bit].cmask);
1508 
1509 			/*
1510 			 * For each requested cap, fold the newly-set cids into
1511 			 * the child and accumulate the delta.
1512 			 */
1513 			scx_for_each_cap_bit(cap_bit, caps) {
1514 				struct scx_cmask *ccm = &cps->caps[cap_bit].cmask;
1515 
1516 				scx_cmask_copy(delta, granted_cids);
1517 				scx_cmask_andnot(delta, ccm);
1518 				if (scx_cmask_empty(delta))
1519 					continue;
1520 
1521 				scx_cmask_or(ccm, delta);
1522 				scx_cmask_or(changed_cids, delta);
1523 				granted_caps |= BIT_U64(cap_bit);
1524 			}
1525 
1526 			if (granted_caps) {
1527 				s32 cid;
1528 
1529 				caps_updated_record(cps, changed_cids, granted_caps,
1530 						    &to_deliver);
1531 				/*
1532 				 * The sync arms an update_idle() re-notify if
1533 				 * the cid gains baseline access, so the holder
1534 				 * learns of an already-idle cid.
1535 				 */
1536 				scx_cmask_for_each_cid(cid, changed_cids)
1537 					queue_sync_ecaps(child, cid);
1538 			}
1539 		}
1540 
1541 		/* record cids that didn't make it through into @denied_out */
1542 		if (!scx_cmask_subset(slice, granted_cids)) {
1543 			any_denied = true;
1544 			if (denied_out__ign) {
1545 				SCX_CMASK_DEFINE_SHARD(denied, slice->base, slice->nr_cids);
1546 
1547 				scx_cmask_copy(denied, slice);
1548 				scx_cmask_andnot(denied, granted_cids);
1549 				scx_cmask_ref_or(&denied_ref, denied);
1550 			}
1551 		}
1552 	}
1553 
1554 	caps_updated_deliver(&to_deliver);
1555 
1556 	return any_denied ? -EPERM : 0;
1557 }
1558 
1559 /**
1560  * scx_bpf_sub_revoke - Revoke @caps on @cmask__ign's cids from @child
1561  * @cgroup_id: cgroup id of the direct child sub-sched
1562  * @caps: bitmask of SCX_CAP_* to revoke
1563  * @cmask__ign: cid cmask to revoke @caps on (arena pointer)
1564  * @aux: implicit BPF argument
1565  *
1566  * Clear @caps bits on @cmask__ign from the child named by @cgroup_id and all
1567  * its descendants. The origin parent's pshard lock is held across the subtree
1568  * walk so a concurrent grant from the origin parent observes the revoked
1569  * state.
1570  */
1571 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps,
1572 				    const struct scx_cmask *cmask__ign,
1573 				    const struct bpf_prog_aux *aux)
1574 {
1575 	struct scx_cmask_ref ref;
1576 	struct scx_sched *parent, *child, *pos;
1577 	LIST_HEAD(to_deliver);
1578 	s32 si, ret;
1579 
1580 	guard(irqsave)();
1581 
1582 	if (sub_cap_preamble(cgroup_id, caps, aux, &parent, &child))
1583 		return;
1584 
1585 	ret = scx_cmask_ref_init(parent, cmask__ign, &ref);
1586 	if (ret) {
1587 		scx_error(parent, "invalid cmask (%d)", ret);
1588 		return;
1589 	}
1590 
1591 	/* per-shard, walk child's subtree and clear @caps */
1592 	for (si = ref.shard_first; si < ref.shard_end; si++) {
1593 		SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS);
1594 
1595 		scx_cmask_ref_shard(&ref, si, slice);
1596 		if (scx_cmask_empty(slice))
1597 			continue;
1598 
1599 		/*
1600 		 * Pre-order with subtree skip: a descendant that cleared
1601 		 * nothing means no descendant of it can hold @caps on these
1602 		 * cids either.
1603 		 */
1604 		guard(raw_spinlock)(&parent->pshard[si]->lock);
1605 		pos = scx_next_descendant_pre(NULL, child);
1606 		while (pos) {
1607 			struct scx_pshard *ps = pos->pshard[si];
1608 			SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids);
1609 			SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids);
1610 			u64 revoked_caps = 0;
1611 			u32 cap_bit;
1612 
1613 			scoped_guard (raw_spinlock_nested, &ps->lock) {
1614 				/*
1615 				 * For each cap, clear lost cids and accumulate
1616 				 * the per-cap diff for notification.
1617 				 */
1618 				scx_for_each_cap_bit(cap_bit, caps) {
1619 					struct scx_cmask *cm = &ps->caps[cap_bit].cmask;
1620 
1621 					scx_cmask_copy(delta, cm);
1622 					scx_cmask_and(delta, slice);
1623 					if (scx_cmask_empty(delta))
1624 						continue;
1625 
1626 					scx_cmask_andnot(cm, delta);
1627 					scx_cmask_or(changed_cids, delta);
1628 					revoked_caps |= BIT_U64(cap_bit);
1629 				}
1630 
1631 				if (revoked_caps) {
1632 					s32 cid;
1633 
1634 					caps_updated_record(ps, changed_cids, revoked_caps,
1635 							    &to_deliver);
1636 					scx_cmask_for_each_cid(cid, changed_cids)
1637 						queue_sync_ecaps(pos, cid);
1638 				}
1639 			}
1640 
1641 			if (revoked_caps)
1642 				pos = scx_next_descendant_pre(pos, child);
1643 			else
1644 				pos = scx_skip_subtree_pre(pos, child);
1645 		}
1646 	}
1647 
1648 	caps_updated_deliver(&to_deliver);
1649 }
1650 
1651 /**
1652  * scx_bpf_sub_caps - Read self's or a direct child's cap cmasks
1653  * @cgroup_id: 0 for self, or a direct child's cgroup id
1654  * @caps: one or more SCX_CAP_* bits
1655  * @out__ign: arena cmask to receive the union of @caps within its range
1656  * @aux: implicit BPF argument
1657  *
1658  * Read the cap cmasks granted on each cid for self (@cgroup_id 0) or a direct
1659  * child - the literal granted set. A sched can read only itself or a direct
1660  * child.
1661  *
1662  * Return 0, -ENODEV if @cgroup_id names no direct child, or -EINVAL on bad
1663  * inputs.
1664  */
1665 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__ign,
1666 				 const struct bpf_prog_aux *aux)
1667 {
1668 	struct scx_cmask_ref ref;
1669 	struct scx_sched *sch, *target;
1670 	struct scx_pshard **pshard;
1671 	s32 si, ret;
1672 
1673 	guard(irqsave)();
1674 
1675 	sch = scx_prog_sched(aux);
1676 	if (unlikely(!sch))
1677 		return -ENODEV;
1678 
1679 	if (!scx_is_cid_type()) {
1680 		scx_error(sch, "sub-cap kfuncs require a cid-form scheduler");
1681 		return -EOPNOTSUPP;
1682 	}
1683 
1684 	if (unlikely(caps & ~__SCX_CAP_ALL)) {
1685 		scx_error(sch, "invalid caps 0x%llx", caps);
1686 		return -EINVAL;
1687 	}
1688 
1689 	/* @cgroup_id 0 reads self, otherwise a direct child */
1690 	if (cgroup_id) {
1691 		target = scx_find_sub_sched(cgroup_id);
1692 		if (unlikely(!target))
1693 			return -ENODEV;
1694 		if (unlikely(scx_parent(target) != sch)) {
1695 			scx_error(sch, "%s: sub-%llu is not a direct child",
1696 				  sch->cgrp_path, cgroup_id);
1697 			return -EINVAL;
1698 		}
1699 	} else {
1700 		target = sch;
1701 	}
1702 
1703 	/*
1704 	 * The target's caps storage may not be set up yet (e.g. a self-read
1705 	 * during ops.init_cids()). Pairs with the publish in
1706 	 * scx_alloc_pshards(): a non-NULL pshard has every element set.
1707 	 */
1708 	pshard = READ_ONCE(target->pshard);
1709 	if (unlikely(!pshard)) {
1710 		scx_error(sch, "scx_bpf_sub_caps() called before caps storage is initialized");
1711 		return -ENODEV;
1712 	}
1713 
1714 	ret = scx_cmask_ref_init(sch, out__ign, &ref);
1715 	if (ret) {
1716 		scx_error(sch, "invalid out (%d)", ret);
1717 		return ret;
1718 	}
1719 
1720 	for (si = ref.shard_first; si < ref.shard_end; si++) {
1721 		const struct scx_cid_shard *shard = &scx_cid_shard_ranges[si];
1722 		SCX_CMASK_DEFINE_SHARD(local_out, shard->base_cid, shard->nr_cids);
1723 		u32 cap_bit;
1724 
1725 		scx_for_each_cap_bit(cap_bit, caps)
1726 			scx_cmask_or(local_out, &pshard[si]->caps[cap_bit].cmask);
1727 		scx_cmask_ref_copy(&ref, local_out);
1728 	}
1729 	return 0;
1730 }
1731 
1732 /**
1733  * scx_bpf_sub_kill_bstr - Kill a direct child sub-scheduler
1734  * @cgroup_id: cgroup id of the direct child to kill
1735  * @fmt: reason message format string
1736  * @data: format string parameters packaged using ___bpf_fill() macro
1737  * @data__sz: @data len, must end in '__sz' for the verifier
1738  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1739  *
1740  * Evict a direct child sub-scheduler, disabling it with the supplied reason.
1741  * The child and its subtree are torn down asynchronously through the usual
1742  * disable path.
1743  *
1744  * Unlike scx_bpf_exit(), no exit code is taken: the child is a separate
1745  * scheduler with its own exit-code semantics, so a code chosen by the parent
1746  * would have no defined meaning. The reason string carries the intent.
1747  *
1748  * Return 0 on success or -ENODEV if @cgroup_id names no sub-scheduler, which
1749  * can race with the child detaching on its own and so is not a scheduler error.
1750  * Naming a sched that exists but is not a direct child aborts the parent.
1751  */
1752 __printf(2, 0)
1753 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt,
1754 				      unsigned long long *data, u32 data__sz,
1755 				      const struct bpf_prog_aux *aux)
1756 {
1757 	struct scx_sched *parent, *child;
1758 	s32 ret;
1759 
1760 	guard(rcu)();
1761 
1762 	parent = scx_prog_sched(aux);
1763 	if (unlikely(!parent))
1764 		return -ENODEV;
1765 
1766 	if (!scx_is_cid_type()) {
1767 		scx_error(parent, "sub-cap kfuncs require a cid-form scheduler");
1768 		return -EOPNOTSUPP;
1769 	}
1770 
1771 	child = scx_find_sub_sched(cgroup_id);
1772 	if (unlikely(!child))
1773 		return -ENODEV;
1774 
1775 	if (unlikely(scx_parent(child) != parent)) {
1776 		scx_error(parent, "%s: sub-%llu is not a direct child",
1777 			  parent->cgrp_path, cgroup_id);
1778 		return -EINVAL;
1779 	}
1780 
1781 	guard(raw_spinlock_irqsave)(&scx_exit_bstr_buf_lock);
1782 	ret = scx_bstr_format(parent, &scx_exit_bstr_buf, fmt, data, data__sz);
1783 	if (ret < 0)
1784 		return ret;
1785 	scx_exit(child, SCX_EXIT_PARENT_KILL, 0, "%s", scx_exit_bstr_buf.line);
1786 	return 0;
1787 }
1788 
1789 __bpf_kfunc_end_defs();
1790 
1791 #endif	/* CONFIG_EXT_SUB_SCHED */
1792