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