xref: /linux/kernel/sched/ext/ext.c (revision 97e1c7d467d07734f8f5c8c64730e1f7c415bd46)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * BPF extensible scheduler class: Documentation/scheduler/sched-ext.rst
4  *
5  * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
6  * Copyright (c) 2022 Tejun Heo <tj@kernel.org>
7  * Copyright (c) 2022 David Vernet <dvernet@meta.com>
8  */
9 #include <linux/bitmap.h>
10 #include <linux/btf_ids.h>
11 #include <linux/rhashtable.h>
12 #include <linux/sched/clock.h>
13 #include <linux/sched/isolation.h>
14 #include <linux/suspend.h>
15 #include <linux/sysrq.h>
16 
17 #include "../pelt.h"
18 #include "internal.h"
19 #include "cid.h"
20 #include "arena.h"
21 #include "idle.h"
22 #include "sub.h"
23 #include "inlines.h"
24 
25 DEFINE_RAW_SPINLOCK(scx_sched_lock);
26 
27 /*
28  * Block a retained proxy donor, telling put_prev_task_scx() that the donor is
29  * about to be dequeued and must not be reenqueued.
30  */
31 static void scx_block_proxy_donor(struct rq *rq, struct task_struct *p)
32 {
33 	rq->scx.flags |= SCX_RQ_PROXY_BLOCKING;
34 	sched_proxy_block_task(rq, p);
35 	rq->scx.flags &= ~SCX_RQ_PROXY_BLOCKING;
36 }
37 
38 bool __scx_allow_proxy_exec(const struct task_struct *p)
39 {
40 	struct scx_sched *sch;
41 
42 	if (p->sched_class != &ext_sched_class)
43 		return true;
44 
45 	sch = scx_task_sched(p);
46 	return !sch || (sch->ops.flags & SCX_OPS_ENQ_BLOCKED);
47 }
48 
49 /*
50  * End retained proxy execution before changing @p's BPF scheduler ownership.
51  * Called with @p's pi and rq locks held immediately before
52  * sched_change_begin(). The caller must pass DEQUEUE_NOCLOCK so the rq clock
53  * is updated only once.
54  */
55 void scx_prepare_task_sched_change(struct task_struct *p)
56 {
57 	lockdep_assert_held(&p->pi_lock);
58 	lockdep_assert_rq_held(task_rq(p));
59 
60 	update_rq_clock(task_rq(p));
61 	scx_block_proxy_donor(task_rq(p), p);
62 }
63 
64 /*
65  * NOTE: sched_ext is in the process of growing multiple scheduler support and
66  * scx_root usage is in a transitional state. Naked dereferences are safe if the
67  * caller is one of the tasks attached to SCX and explicit RCU dereference is
68  * necessary otherwise. Naked scx_root dereferences trigger sparse warnings but
69  * are used as temporary markers to indicate that the dereferences need to be
70  * updated to point to the associated scheduler instances rather than scx_root.
71  */
72 struct scx_sched __rcu *scx_root;
73 
74 /*
75  * All scheds, writers must hold both scx_enable_mutex and scx_sched_lock.
76  * Readers can hold either or rcu_read_lock().
77  */
78 LIST_HEAD(scx_sched_all);
79 
80 #ifdef CONFIG_EXT_SUB_SCHED
81 static __always_inline int scx_sched_cmpfn(struct rhashtable_compare_arg *arg,
82 					   const void *ptr)
83 {
84 	const struct scx_sched *sch = ptr;
85 
86 	BUILD_BUG_ON(sizeof_field(struct scx_sched, ops.sub_cgroup_id) != sizeof(u64));
87 
88 	return sch->ops.sub_cgroup_id != *(const u64 *)arg->key;
89 }
90 
91 const struct rhashtable_params scx_sched_hash_params = {
92 	.key_len		= sizeof_field(struct scx_sched, ops.sub_cgroup_id),
93 	.key_offset		= offsetof(struct scx_sched, ops.sub_cgroup_id),
94 	.head_offset		= offsetof(struct scx_sched, hash_node),
95 	.obj_cmpfn		= scx_sched_cmpfn,
96 	.insecure_elasticity	= true,	/* inserted under scx_sched_lock */
97 };
98 
99 struct rhashtable scx_sched_hash;
100 #endif
101 
102 /* see SCX_OPS_TID_TO_TASK */
103 static __always_inline int scx_tid_cmpfn(struct rhashtable_compare_arg *arg, const void *ptr)
104 {
105 	const struct sched_ext_entity *scx = ptr;
106 
107 	BUILD_BUG_ON(sizeof_field(struct sched_ext_entity, tid) != sizeof(u64));
108 
109 	return scx->tid != *(const u64 *)arg->key;
110 }
111 
112 static const struct rhashtable_params scx_tid_hash_params = {
113 	.key_len		= sizeof_field(struct sched_ext_entity, tid),
114 	.key_offset		= offsetof(struct sched_ext_entity, tid),
115 	.head_offset		= offsetof(struct sched_ext_entity, tid_hash_node),
116 	.obj_cmpfn		= scx_tid_cmpfn,
117 	.insecure_elasticity	= true,	/* inserted/removed under scx_tasks_lock */
118 };
119 static struct rhashtable scx_tid_hash;
120 
121 /*
122  * During exit, a task may schedule after losing its PIDs. When disabling the
123  * BPF scheduler, we need to be able to iterate tasks in every state to
124  * guarantee system safety. Maintain a dedicated task list which contains every
125  * task between its fork and eventual free.
126  */
127 static DEFINE_RAW_SPINLOCK(scx_tasks_lock);
128 static LIST_HEAD(scx_tasks);
129 
130 /* ops enable/disable */
131 DEFINE_MUTEX(scx_enable_mutex);
132 DEFINE_STATIC_KEY_FALSE(__scx_enabled);
133 DEFINE_PERCPU_RWSEM(scx_fork_rwsem);
134 static atomic_t scx_enable_state_var = ATOMIC_INIT(SCX_DISABLED);
135 static DEFINE_RAW_SPINLOCK(scx_bypass_lock);
136 static bool scx_init_task_enabled;
137 static bool scx_task_switch_enabled;
138 static bool scx_switching_all;
139 DEFINE_STATIC_KEY_FALSE(__scx_switched_all);
140 static DEFINE_STATIC_KEY_FALSE(__scx_tid_to_task_enabled);
141 
142 /*
143  * Gates cgroup ops delivery. Set at the end of the cgroup init phase of root
144  * enable and cleared before root disable starts tearing down tasks, both under
145  * scx_cgroup_lock(). Holding cgroup_lock() and seeing %true guarantees no race
146  * against root tearing down tasks.
147  */
148 bool scx_cgroup_enabled;
149 
150 /*
151  * True once SCX_OPS_TID_TO_TASK has been negotiated with the root scheduler
152  * and the tid->task table is live. Wraps the static key so callers don't
153  * take the address, and hints "likely enabled" for the common case where
154  * the feature is in use.
155  */
156 static inline bool scx_tid_to_task_enabled(void)
157 {
158 	return static_branch_likely(&__scx_tid_to_task_enabled);
159 }
160 
161 static atomic_long_t scx_nr_rejected = ATOMIC_LONG_INIT(0);
162 static atomic_long_t scx_hotplug_seq = ATOMIC_LONG_INIT(0);
163 
164 /* Global cursor for the per-CPU tid allocator. Starts at 1; tid 0 is reserved. */
165 static atomic64_t scx_tid_cursor = ATOMIC64_INIT(1);
166 
167 /* is @dsq synchronized by the containing rq lock instead of dsq->lock? */
168 static bool dsq_is_rq_owned(struct scx_dispatch_q *dsq)
169 {
170 	switch (dsq->id) {
171 	case SCX_DSQ_LOCAL:
172 	case SCX_DSQ_REJECT:
173 	case SCX_DSQ_RESCUE:
174 		return true;
175 	default:
176 		return false;
177 	}
178 }
179 
180 /* Cursor for unique scx_sched instance ids. id 0 is reserved. */
181 static atomic64_t scx_sched_id_cursor = ATOMIC64_INIT(0);
182 
183 #ifdef CONFIG_EXT_SUB_SCHED
184 /*
185  * The sub sched being enabled. Used by scx_disable_and_exit_task() to exit
186  * tasks for the sub-sched being enabled. Use a global variable instead of a
187  * per-task field as all enables are serialized.
188  */
189 struct scx_sched *scx_enabling_sub_sched;
190 #else
191 #define scx_enabling_sub_sched	(struct scx_sched *)NULL
192 #endif	/* CONFIG_EXT_SUB_SCHED */
193 
194 /*
195  * A monotonically increasing sequence number that is incremented every time a
196  * scheduler is enabled. This can be used to check if any custom sched_ext
197  * scheduler has ever been used in the system.
198  */
199 static atomic_long_t scx_enable_seq = ATOMIC_LONG_INIT(0);
200 
201 /*
202  * Watchdog interval. All scx_sched's share a single watchdog timer and the
203  * interval is half of the shortest sch->watchdog_timeout.
204  */
205 static unsigned long scx_watchdog_interval;
206 
207 /*
208  * The last time the delayed work was run. This delayed work relies on
209  * ksoftirqd being able to run to service timer interrupts, so it's possible
210  * that this work itself could get wedged. To account for this, we check that
211  * it's not stalled in the timer tick, and trigger an error if it is.
212  */
213 static unsigned long scx_watchdog_timestamp = INITIAL_JIFFIES;
214 
215 static struct delayed_work scx_watchdog_work;
216 
217 /*
218  * For %SCX_KICK_WAIT: Each CPU has a pointer to an array of kick_sync sequence
219  * numbers. The arrays are allocated with kvzalloc() as size can exceed percpu
220  * allocator limits on large machines. O(nr_cpu_ids^2) allocation, allocated
221  * lazily when enabling and freed when disabling to avoid waste when sched_ext
222  * isn't active.
223  */
224 struct scx_kick_syncs {
225 	struct rcu_head		rcu;
226 	unsigned long		syncs[];
227 };
228 
229 static DEFINE_PER_CPU(struct scx_kick_syncs __rcu *, scx_kick_syncs);
230 
231 /*
232  * Per-CPU buffered allocator state for p->scx.tid. Each CPU pulls a chunk of
233  * SCX_TID_CHUNK ids from scx_tid_cursor and hands them out locally without
234  * further synchronization. See scx_alloc_tid().
235  */
236 struct scx_tid_alloc {
237 	u64	next;
238 	u64	end;
239 };
240 static DEFINE_PER_CPU(struct scx_tid_alloc, scx_tid_alloc);
241 
242 /*
243  * Direct dispatch marker.
244  *
245  * Non-NULL values are used for direct dispatch from enqueue path. A valid
246  * pointer points to the task currently being enqueued. An ERR_PTR value is used
247  * to indicate that direct dispatch has already happened.
248  */
249 static DEFINE_PER_CPU(struct task_struct *, direct_dispatch_task);
250 
251 static __always_inline int dsq_cmpfn(struct rhashtable_compare_arg *arg, const void *ptr)
252 {
253 	const struct scx_dispatch_q *dsq = ptr;
254 
255 	BUILD_BUG_ON(sizeof_field(struct scx_dispatch_q, id) != sizeof(u64));
256 
257 	return dsq->id != *(const u64 *)arg->key;
258 }
259 
260 static const struct rhashtable_params dsq_hash_params = {
261 	.key_len		= sizeof_field(struct scx_dispatch_q, id),
262 	.key_offset		= offsetof(struct scx_dispatch_q, id),
263 	.head_offset		= offsetof(struct scx_dispatch_q, hash_node),
264 	.obj_cmpfn		= dsq_cmpfn,
265 };
266 
267 static LLIST_HEAD(dsqs_to_free);
268 
269 /* ops debug dump */
270 static DEFINE_RAW_SPINLOCK(scx_dump_lock);
271 
272 struct scx_dump_data {
273 	s32			cpu;
274 	bool			first;
275 	s32			cursor;
276 	struct seq_buf		*s;
277 	const char		*prefix;
278 	struct scx_bstr_buf	buf;
279 };
280 
281 static struct scx_dump_data scx_dump_data = {
282 	.cpu			= -1,
283 };
284 
285 /* /sys/kernel/sched_ext interface */
286 static struct kset *scx_kset;
287 
288 /*
289  * Parameters that can be adjusted through /sys/module/sched_ext/parameters.
290  * There usually is no reason to modify these as normal scheduler operation
291  * shouldn't be affected by them. The knobs are primarily for debugging.
292  */
293 static unsigned int scx_slice_bypass_us = SCX_SLICE_BYPASS / NSEC_PER_USEC;
294 static unsigned int scx_bypass_lb_intv_us = SCX_BYPASS_LB_DFL_INTV_US;
295 
296 static int set_slice_us(const char *val, const struct kernel_param *kp)
297 {
298 	return param_set_uint_minmax(val, kp, 100, 100 * USEC_PER_MSEC);
299 }
300 
301 static const struct kernel_param_ops slice_us_param_ops = {
302 	.set = set_slice_us,
303 	.get = param_get_uint,
304 };
305 
306 static int set_bypass_lb_intv_us(const char *val, const struct kernel_param *kp)
307 {
308 	return param_set_uint_minmax(val, kp, 0, 10 * USEC_PER_SEC);
309 }
310 
311 static const struct kernel_param_ops bypass_lb_intv_us_param_ops = {
312 	.set = set_bypass_lb_intv_us,
313 	.get = param_get_uint,
314 };
315 
316 #undef MODULE_PARAM_PREFIX
317 #define MODULE_PARAM_PREFIX	"sched_ext."
318 
319 module_param_cb(slice_bypass_us, &slice_us_param_ops, &scx_slice_bypass_us, 0600);
320 MODULE_PARM_DESC(slice_bypass_us, "bypass slice in microseconds, applied on [un]load (100us to 100ms)");
321 module_param_cb(bypass_lb_intv_us, &bypass_lb_intv_us_param_ops, &scx_bypass_lb_intv_us, 0600);
322 MODULE_PARM_DESC(bypass_lb_intv_us, "bypass load balance interval in microseconds (0 (disable) to 10s)");
323 
324 #undef MODULE_PARAM_PREFIX
325 
326 #define CREATE_TRACE_POINTS
327 #include <trace/events/sched_ext.h>
328 
329 static void run_deferred(struct rq *rq);
330 static bool task_dead_and_done(struct task_struct *p);
331 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind);
332 
333 __printf(5, 6) bool __scx_exit(struct scx_sched *sch,
334 			       enum scx_exit_kind kind, s64 exit_code,
335 			       s32 exit_cpu, const char *fmt, ...)
336 {
337 	va_list args;
338 	bool ret;
339 
340 	va_start(args, fmt);
341 	ret = scx_vexit(sch, kind, exit_code, exit_cpu, fmt, args);
342 	va_end(args);
343 
344 	return ret;
345 }
346 
347 static long jiffies_delta_msecs(unsigned long at, unsigned long now)
348 {
349 	if (time_after(at, now))
350 		return jiffies_to_msecs(at - now);
351 	else
352 		return -(long)jiffies_to_msecs(now - at);
353 }
354 
355 static bool u32_before(u32 a, u32 b)
356 {
357 	return (s32)(a - b) < 0;
358 }
359 
360 /**
361  * scx_is_descendant - Test whether sched is a descendant
362  * @sch: sched to test
363  * @ancestor: ancestor sched to test against
364  *
365  * Test whether @sch is a descendant of @ancestor.
366  */
367 bool scx_is_descendant(struct scx_sched *sch, struct scx_sched *ancestor)
368 {
369 	if (sch->level < ancestor->level)
370 		return false;
371 	return sch->ancestors[ancestor->level] == ancestor;
372 }
373 
374 static struct scx_dispatch_q *find_global_dsq(struct scx_sched *sch, s32 cpu)
375 {
376 	return &sch->pnode[cpu_to_node(cpu)]->global_dsq;
377 }
378 
379 static struct scx_dispatch_q *find_user_dsq(struct scx_sched *sch, u64 dsq_id)
380 {
381 	return rhashtable_lookup(&sch->dsq_hash, &dsq_id, dsq_hash_params);
382 }
383 
384 static const struct sched_class *scx_setscheduler_class(struct task_struct *p)
385 {
386 	if (p->sched_class == &stop_sched_class)
387 		return &stop_sched_class;
388 
389 	return __setscheduler_class(p->policy, p->prio);
390 }
391 
392 static struct scx_dispatch_q *bypass_enq_target_dsq(struct scx_sched *sch, struct rq *rq,
393 						    struct task_struct *p, u64 *enq_flags)
394 {
395 	struct scx_sched *host = scx_exec_sched(sch, cpu_of(rq));
396 	struct scx_dispatch_q *dsq;
397 
398 	/*
399 	 * If @sch is a sub-sched which is bypassing, its tasks should go into
400 	 * the bypass DSQs of the nearest ancestor which is not bypassing. The
401 	 * not-bypassing ancestor is responsible for scheduling all tasks from
402 	 * bypassing sub-trees. If all ancestors including root are bypassing,
403 	 * all tasks should go to the root's bypass DSQs.
404 	 *
405 	 * Whenever a sched starts bypassing, all runnable tasks in its subtree
406 	 * are re-enqueued after scx_bypassing() is turned on, guaranteeing that
407 	 * all tasks are transferred to the right DSQs.
408 	 *
409 	 * A cpu's dispatch only descends into a host holding %SCX_CAP_BASE on
410 	 * it, so the bypass DSQ of a host without BASE here is never consumed.
411 	 * Send @p to rescue on this cpu instead, resolving against @host.
412 	 * scx_dispatch_enqueue() resolves a local DSQ again, against the
413 	 * bypassing @sch. %SCX_ENQ_IGNORE_CAPS makes that second resolution
414 	 * admit @p.
415 	 *
416 	 * A migration-disabled task can't leave this cpu, and a task with a
417 	 * migration pending must run here until the migration moves it. Either
418 	 * would wait on the unconsumed bypass DSQ until the host regains BASE.
419 	 * Resolve them too when rescue is disabled. The resolution admits both
420 	 * to the local DSQ, as it does any insert of such a task.
421 	 */
422 	if (unlikely(scx_missing_caps(host, cpu_of(rq), SCX_CAP_BASE)) &&
423 	    (scx_rescue_enabled() || is_migration_disabled(p) || p->migration_pending)) {
424 		*enq_flags |= SCX_ENQ_RESCUE;
425 		dsq = scx_resolve_local_dsq(host, rq, p, enq_flags);
426 		*enq_flags |= SCX_ENQ_IGNORE_CAPS;
427 	} else {
428 		dsq = scx_bypass_dsq(host, cpu_of(rq));
429 	}
430 	return dsq;
431 }
432 
433 /**
434  * rq_is_open - Is the rq available for immediate execution of an SCX task?
435  * @rq: rq to test
436  * @enq_flags: optional %SCX_ENQ_* of the task being enqueued
437  *
438  * Returns %true if @rq is currently open for executing an SCX task. After a
439  * %false return, @rq is guaranteed to invoke SCX dispatch path at least once
440  * before going to idle and not inserting a task into @rq's local DSQ after a
441  * %false return doesn't cause @rq to stall.
442  */
443 static bool rq_is_open(struct rq *rq, u64 enq_flags)
444 {
445 	lockdep_assert_rq_held(rq);
446 
447 	/*
448 	 * A higher-priority class task is either running or in the process of
449 	 * waking up on @rq.
450 	 */
451 	if (sched_class_above(rq->next_class, &ext_sched_class))
452 		return false;
453 
454 	/*
455 	 * @rq is either in transition to or in idle and there is no
456 	 * higher-priority class task waking up on it.
457 	 */
458 	if (sched_class_above(&ext_sched_class, rq->next_class))
459 		return true;
460 
461 	/*
462 	 * @rq is either picking, in transition to, or running an SCX task.
463 	 */
464 
465 	/*
466 	 * A local insertion can raise next_class to ext while the donor is
467 	 * still idle. Keep the rq open so that the local DSQ head is not
468 	 * unnecessarily reenqueued before the CPU can pick it.
469 	 */
470 	if (rq->donor == rq->idle)
471 		return true;
472 
473 	/*
474 	 * If we're in the dispatch path holding rq lock, $donor may or may not
475 	 * be ready depending on whether the on-going dispatch decides to extend
476 	 * $donor's slice. We say yes here and resolve it at the end of dispatch.
477 	 * See dispatch_one().
478 	 */
479 	if (rq->scx.flags & SCX_RQ_IN_DISPATCH)
480 		return true;
481 
482 	/*
483 	 * The preemption flags clear $donor's slice if on SCX and kick dispatch,
484 	 * so allow it to avoid spuriously triggering reenq on a combined
485 	 * PREEMPT|IMMED insertion.
486 	 */
487 	if (enq_flags & (SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY)) {
488 		struct task_struct *donor = rq->donor;
489 
490 		/*
491 		 * A protected slice refuses the preemption and the cpu stays
492 		 * occupied. See rq_owned_post_enq().
493 		 */
494 		return donor->sched_class != &ext_sched_class ||
495 			likely(!(donor->scx.flags & SCX_TASK_PROTECTED));
496 	}
497 
498 	/*
499 	 * @rq is either in transition to or running an SCX task and can't go
500 	 * idle without another SCX dispatch cycle.
501 	 */
502 	return false;
503 }
504 
505 /*
506  * Track the rq currently locked.
507  *
508  * This allows kfuncs to safely operate on rq from any scx ops callback,
509  * knowing which rq is already locked.
510  */
511 DEFINE_PER_CPU(struct rq *, scx_locked_rq_state);
512 
513 /*
514  * Under core scheduling, a pick that releases the rq lock invalidates the
515  * core-wide selection it is part of. Count the releases so that the core-sched
516  * pick can tell whether one happened across dispatch.
517  */
518 static void scx_rq_lock_drop(struct rq *rq)
519 {
520 	lockdep_assert_rq_held(rq);
521 #ifdef CONFIG_SCHED_CORE
522 	if (sched_core_enabled(rq))
523 		rq->scx.lock_drop_seq++;
524 #endif
525 }
526 
527 static void switch_rq_lock(struct rq *from, struct rq *to)
528 {
529 	bool tracked = scx_locked_rq() == from;
530 
531 	if (tracked)
532 		update_locked_rq(NULL);
533 	scx_rq_lock_drop(from);
534 	raw_spin_rq_unlock(from);
535 	raw_spin_rq_lock(to);
536 	if (tracked)
537 		update_locked_rq(to);
538 }
539 
540 /*
541  * Flipped on enable per sch->is_cid_type. Declared in internal.h so
542  * subsystem inlines can read it.
543  */
544 DEFINE_STATIC_KEY_FALSE(__scx_is_cid_type);
545 
546 /**
547  * scx_fill_cmask_scratch - Build this cpu's arena cmask from @cpumask
548  * @sch: scx_sched whose scratch to fill
549  * @cpumask: cpus to translate into cids
550  *
551  * The scratch lives in BPF-writable arena memory and its header can't be
552  * trusted, so it is rewritten from kernel geometry rather than read. Caller
553  * must hold an rq lock so this cpu is the sole kernel writer for as long as the
554  * returned address is in use.
555  */
556 static struct scx_cmask *scx_fill_cmask_scratch(struct scx_sched *sch,
557 						const struct cpumask *cpumask)
558 {
559 	struct scx_cmask *kern_va = *this_cpu_ptr(sch->set_cmask_scratch);
560 	struct scx_cmask_ref ref;
561 
562 	scx_cmask_ref_init_kern(sch, kern_va, 0, num_possible_cpus(), &ref);
563 	scx_cmask_ref_from_cpumask(&ref, cpumask);
564 	return kern_va;
565 }
566 
567 /**
568  * scx_call_op_set_cpumask - Invoke the set_cpumask or set_cmask op for @task
569  * @sch: scx_sched being invoked
570  * @rq: rq to update as the currently-locked rq, or NULL
571  * @task: task whose affinity is changing
572  * @cpumask: new cpumask
573  *
574  * For cid-form schedulers, translate @cpumask to a cmask in the per-cpu scratch
575  * and dispatch through the ops_cid union view. Caller must hold @rq's rq lock.
576  */
577 static inline void scx_call_op_set_cpumask(struct scx_sched *sch, struct rq *rq,
578 					   struct task_struct *task,
579 					   const struct cpumask *cpumask)
580 {
581 	if (scx_is_cid_type())
582 		SCX_CALL_CID_OP_TASK(sch, set_cmask, rq, task,
583 				     scx_fill_cmask_scratch(sch, cpumask));
584 	else
585 		SCX_CALL_OP_TASK(sch, set_cpumask, rq, task, cpumask);
586 }
587 
588 enum scx_dsq_iter_flags {
589 	/* iterate in the reverse dispatch order */
590 	SCX_DSQ_ITER_REV		= 1U << 16,
591 
592 	__SCX_DSQ_ITER_DRAINED		= 1U << 28,
593 	__SCX_DSQ_ITER_HAS_REENQ	= 1U << 29,
594 	__SCX_DSQ_ITER_HAS_SLICE	= 1U << 30,
595 	__SCX_DSQ_ITER_HAS_VTIME	= 1U << 31,
596 
597 	__SCX_DSQ_ITER_USER_FLAGS	= SCX_DSQ_ITER_REV,
598 	__SCX_DSQ_ITER_ALL_FLAGS	= __SCX_DSQ_ITER_USER_FLAGS |
599 					  __SCX_DSQ_ITER_DRAINED |
600 					  __SCX_DSQ_ITER_HAS_REENQ |
601 					  __SCX_DSQ_ITER_HAS_SLICE |
602 					  __SCX_DSQ_ITER_HAS_VTIME,
603 };
604 
605 /**
606  * nldsq_next_task - Iterate to the next task in a non-local DSQ
607  * @dsq: non-local dsq being iterated
608  * @cur: current position, %NULL to start iteration
609  * @rev: walk backwards
610  *
611  * Returns %NULL when iteration is finished.
612  */
613 static struct task_struct *nldsq_next_task(struct scx_dispatch_q *dsq,
614 					   struct task_struct *cur, bool rev)
615 {
616 	struct list_head *list_node;
617 	struct scx_dsq_list_node *dsq_lnode;
618 
619 	lockdep_assert_held(&dsq->lock);
620 
621 	if (cur)
622 		list_node = &cur->scx.dsq_list.node;
623 	else
624 		list_node = &dsq->list;
625 
626 	/* find the next task, need to skip BPF iteration cursors */
627 	do {
628 		if (rev)
629 			list_node = list_node->prev;
630 		else
631 			list_node = list_node->next;
632 
633 		if (list_node == &dsq->list)
634 			return NULL;
635 
636 		dsq_lnode = container_of(list_node, struct scx_dsq_list_node,
637 					 node);
638 	} while (dsq_lnode->flags & SCX_DSQ_LNODE_ITER_CURSOR);
639 
640 	return container_of(dsq_lnode, struct task_struct, scx.dsq_list);
641 }
642 
643 #define nldsq_for_each_task(p, dsq)						\
644 	for ((p) = nldsq_next_task((dsq), NULL, false); (p);			\
645 	     (p) = nldsq_next_task((dsq), (p), false))
646 
647 /**
648  * nldsq_cursor_next_task - Iterate to the next task given a cursor in a non-local DSQ
649  * @cursor: scx_dsq_list_node initialized with INIT_DSQ_LIST_CURSOR()
650  * @dsq: non-local dsq being iterated
651  *
652  * Find the next task in a cursor based iteration. The caller must have
653  * initialized @cursor using INIT_DSQ_LIST_CURSOR() and can release the DSQ lock
654  * between the iteration steps.
655  *
656  * Only tasks which were queued before @cursor was initialized are visible. This
657  * bounds the iteration and guarantees that vtime never jumps in the other
658  * direction while iterating.
659  */
660 static struct task_struct *nldsq_cursor_next_task(struct scx_dsq_list_node *cursor,
661 						  struct scx_dispatch_q *dsq)
662 {
663 	bool rev = cursor->flags & SCX_DSQ_ITER_REV;
664 	struct task_struct *p;
665 
666 	lockdep_assert_held(&dsq->lock);
667 	BUG_ON(!(cursor->flags & SCX_DSQ_LNODE_ITER_CURSOR));
668 
669 	if (list_empty(&cursor->node))
670 		p = NULL;
671 	else
672 		p = container_of(cursor, struct task_struct, scx.dsq_list);
673 
674 	/* skip cursors and tasks that were queued after @cursor init */
675 	do {
676 		p = nldsq_next_task(dsq, p, rev);
677 	} while (p && unlikely(u32_before(cursor->priv, p->scx.dsq_seq)));
678 
679 	if (p) {
680 		if (rev)
681 			list_move_tail(&cursor->node, &p->scx.dsq_list.node);
682 		else
683 			list_move(&cursor->node, &p->scx.dsq_list.node);
684 	} else {
685 		list_del_init(&cursor->node);
686 	}
687 
688 	return p;
689 }
690 
691 /**
692  * nldsq_cursor_lost_task - Test whether someone else took the task since iteration
693  * @cursor: scx_dsq_list_node initialized with INIT_DSQ_LIST_CURSOR()
694  * @rq: rq @p was on
695  * @dsq: dsq @p was on
696  * @p: target task
697  *
698  * @p is a task returned by nldsq_cursor_next_task(). The locks may have been
699  * dropped and re-acquired inbetween. Verify that no one else took or is in the
700  * process of taking @p from @dsq.
701  *
702  * On %false return, the caller can assume full ownership of @p.
703  */
704 static bool nldsq_cursor_lost_task(struct scx_dsq_list_node *cursor,
705 				   struct rq *rq, struct scx_dispatch_q *dsq,
706 				   struct task_struct *p)
707 {
708 	lockdep_assert_rq_held(rq);
709 	lockdep_assert_held(&dsq->lock);
710 
711 	/*
712 	 * @p could have already left $src_dsq, got re-enqueud, or be in the
713 	 * process of being consumed by someone else.
714 	 */
715 	if (unlikely(p->scx.dsq != dsq ||
716 		     u32_before(cursor->priv, p->scx.dsq_seq) ||
717 		     p->scx.holding_cpu >= 0))
718 		return true;
719 
720 	/* if @p has stayed on @dsq, its rq couldn't have changed */
721 	if (WARN_ON_ONCE(rq != task_rq(p)))
722 		return true;
723 
724 	return false;
725 }
726 
727 /*
728  * BPF DSQ iterator. Tasks in a non-local DSQ can be iterated in [reverse]
729  * dispatch order. BPF-visible iterator is opaque and larger to allow future
730  * changes without breaking backward compatibility. Can be used with
731  * bpf_for_each(). See bpf_iter_scx_dsq_*().
732  */
733 struct bpf_iter_scx_dsq_kern {
734 	struct scx_dsq_list_node	cursor;
735 	struct scx_dispatch_q		*dsq;
736 	u64				slice;
737 	u64				vtime;
738 } __attribute__((aligned(8)));
739 
740 struct bpf_iter_scx_dsq {
741 	u64				__opaque[6];
742 } __attribute__((aligned(8)));
743 
744 
745 u32 scx_get_task_state(const struct task_struct *p)
746 {
747 	return p->scx.flags & SCX_TASK_STATE_MASK;
748 }
749 
750 void scx_set_task_state(struct task_struct *p, u32 state)
751 {
752 	u32 prev_state = scx_get_task_state(p);
753 	bool warn = false;
754 
755 	switch (state) {
756 	case SCX_TASK_NONE:
757 		warn = prev_state == SCX_TASK_DEAD;
758 		break;
759 	case SCX_TASK_INIT_BEGIN:
760 		warn = prev_state != SCX_TASK_NONE;
761 		break;
762 	case SCX_TASK_INIT:
763 		warn = prev_state != SCX_TASK_INIT_BEGIN;
764 		p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
765 		break;
766 	case SCX_TASK_READY:
767 		warn = !(prev_state == SCX_TASK_INIT ||
768 			 prev_state == SCX_TASK_ENABLED);
769 		break;
770 	case SCX_TASK_ENABLED:
771 		warn = prev_state != SCX_TASK_READY;
772 		break;
773 	case SCX_TASK_DEAD:
774 		warn = !(prev_state == SCX_TASK_NONE ||
775 			 prev_state == SCX_TASK_INIT_BEGIN);
776 		break;
777 	default:
778 		WARN_ONCE(1, "sched_ext: Invalid task state %d -> %d for %s[%d]",
779 			  prev_state, state, p->comm, p->pid);
780 		return;
781 	}
782 
783 	WARN_ONCE(warn, "sched_ext: Invalid task state transition 0x%x -> 0x%x for %s[%d]",
784 		  prev_state, state, p->comm, p->pid);
785 
786 	p->scx.flags &= ~SCX_TASK_STATE_MASK;
787 	p->scx.flags |= state;
788 }
789 
790 /**
791  * scx_task_iter_start - Lock scx_tasks_lock and start a task iteration
792  * @iter: iterator to init
793  * @cgrp: Optional root of cgroup subhierarchy to iterate
794  *
795  * Initialize @iter. Once initialized, @iter must eventually be stopped with
796  * scx_task_iter_stop().
797  *
798  * If @cgrp is %NULL, scx_tasks is used for iteration and this function returns
799  * with scx_tasks_lock held and @iter->cursor inserted into scx_tasks.
800  *
801  * If @cgrp is not %NULL, @cgrp and its descendants' tasks are walked using
802  * @iter->css_iter. The caller must be holding cgroup_lock() to prevent cgroup
803  * task migrations.
804  *
805  * The two modes of iterations are largely independent and it's likely that
806  * scx_tasks can be removed in favor of always using cgroup iteration if
807  * CONFIG_SCHED_CLASS_EXT depends on CONFIG_CGROUPS.
808  *
809  * scx_tasks_lock and the rq lock may be released using scx_task_iter_unlock()
810  * between this and the first next() call or between any two next() calls. If
811  * the locks are released between two next() calls, the caller is responsible
812  * for ensuring that the task being iterated remains accessible either through
813  * RCU read lock or obtaining a reference count.
814  *
815  * All tasks which existed when the iteration started are guaranteed to be
816  * visited as long as they are not dead.
817  */
818 void scx_task_iter_start(struct scx_task_iter *iter, struct cgroup *cgrp)
819 {
820 	memset(iter, 0, sizeof(*iter));
821 
822 #ifdef CONFIG_EXT_SUB_SCHED
823 	if (cgrp) {
824 		lockdep_assert_held(&cgroup_mutex);
825 		iter->cgrp = cgrp;
826 		iter->css_pos = css_next_descendant_pre(NULL, &iter->cgrp->self);
827 		css_task_iter_start(iter->css_pos, CSS_TASK_ITER_WITH_DEAD,
828 				    &iter->css_iter);
829 		return;
830 	}
831 #endif
832 	raw_spin_lock_irq(&scx_tasks_lock);
833 
834 	iter->cursor = (struct sched_ext_entity){ .flags = SCX_TASK_CURSOR };
835 	list_add(&iter->cursor.tasks_node, &scx_tasks);
836 	iter->list_locked = true;
837 }
838 
839 static void __scx_task_iter_rq_unlock(struct scx_task_iter *iter)
840 {
841 	if (iter->locked_task) {
842 		__balance_callbacks(iter->rq, &iter->rf);
843 		task_rq_unlock(iter->rq, iter->locked_task, &iter->rf);
844 		iter->locked_task = NULL;
845 	}
846 }
847 
848 /**
849  * scx_task_iter_unlock - Unlock rq and scx_tasks_lock held by a task iterator
850  * @iter: iterator to unlock
851  *
852  * If @iter is in the middle of a locked iteration, it may be locking the rq of
853  * the task currently being visited in addition to scx_tasks_lock. Unlock both.
854  * This function can be safely called anytime during an iteration. The next
855  * iterator operation will automatically restore the necessary locking.
856  */
857 void scx_task_iter_unlock(struct scx_task_iter *iter)
858 {
859 	__scx_task_iter_rq_unlock(iter);
860 	if (iter->list_locked) {
861 		iter->list_locked = false;
862 		raw_spin_unlock_irq(&scx_tasks_lock);
863 	}
864 }
865 
866 static void __scx_task_iter_maybe_relock(struct scx_task_iter *iter)
867 {
868 	if (!iter->list_locked) {
869 		raw_spin_lock_irq(&scx_tasks_lock);
870 		iter->list_locked = true;
871 	}
872 }
873 
874 /**
875  * scx_task_iter_relock - Re-acquire scx_tasks_lock and, optionally, @p's rq
876  * @iter: iterator to relock
877  * @p: task whose rq to lock, or %NULL for scx_tasks_lock only
878  *
879  * Counterpart to scx_task_iter_unlock(). Locking @p's rq is optional. Once
880  * re-acquired, both locks are managed by the iterator from here on.
881  */
882 static void scx_task_iter_relock(struct scx_task_iter *iter,
883 				 struct task_struct *p)
884 {
885 	__scx_task_iter_maybe_relock(iter);
886 	if (p) {
887 		iter->rq = task_rq_lock(p, &iter->rf);
888 		iter->locked_task = p;
889 	}
890 }
891 
892 /**
893  * scx_task_iter_stop - Stop a task iteration and unlock scx_tasks_lock
894  * @iter: iterator to exit
895  *
896  * Exit a previously initialized @iter. Must be called with scx_tasks_lock held
897  * which is released on return. If the iterator holds a task's rq lock, that rq
898  * lock is also released. See scx_task_iter_start() for details.
899  */
900 void scx_task_iter_stop(struct scx_task_iter *iter)
901 {
902 #ifdef CONFIG_EXT_SUB_SCHED
903 	if (iter->cgrp) {
904 		if (iter->css_pos)
905 			css_task_iter_end(&iter->css_iter);
906 		__scx_task_iter_rq_unlock(iter);
907 		return;
908 	}
909 #endif
910 	__scx_task_iter_maybe_relock(iter);
911 	list_del_init(&iter->cursor.tasks_node);
912 	scx_task_iter_unlock(iter);
913 }
914 
915 /**
916  * scx_task_iter_next - Next task
917  * @iter: iterator to walk
918  *
919  * Visit the next task. See scx_task_iter_start() for details. Locks are dropped
920  * and re-acquired every %SCX_TASK_ITER_BATCH iterations to avoid causing stalls
921  * by holding scx_tasks_lock for too long.
922  */
923 static struct task_struct *scx_task_iter_next(struct scx_task_iter *iter)
924 {
925 	struct list_head *cursor = &iter->cursor.tasks_node;
926 	struct sched_ext_entity *pos;
927 
928 	if (!(++iter->cnt % SCX_TASK_ITER_BATCH)) {
929 		scx_task_iter_unlock(iter);
930 		cond_resched();
931 	}
932 
933 #ifdef CONFIG_EXT_SUB_SCHED
934 	if (iter->cgrp) {
935 		while (iter->css_pos) {
936 			struct task_struct *p;
937 
938 			p = css_task_iter_next(&iter->css_iter);
939 			if (p)
940 				return p;
941 
942 			css_task_iter_end(&iter->css_iter);
943 			iter->css_pos = css_next_descendant_pre(iter->css_pos,
944 								&iter->cgrp->self);
945 			if (iter->css_pos)
946 				css_task_iter_start(iter->css_pos, CSS_TASK_ITER_WITH_DEAD,
947 						    &iter->css_iter);
948 		}
949 		return NULL;
950 	}
951 #endif
952 	__scx_task_iter_maybe_relock(iter);
953 
954 	list_for_each_entry(pos, cursor, tasks_node) {
955 		if (&pos->tasks_node == &scx_tasks)
956 			return NULL;
957 		if (!(pos->flags & SCX_TASK_CURSOR)) {
958 			list_move(cursor, &pos->tasks_node);
959 			return container_of(pos, struct task_struct, scx);
960 		}
961 	}
962 
963 	/* can't happen, should always terminate at scx_tasks above */
964 	BUG();
965 }
966 
967 /**
968  * scx_task_iter_next_locked - Next non-idle task with its rq locked
969  * @iter: iterator to walk
970  *
971  * Visit the non-idle task with its rq lock held. Allows callers to specify
972  * whether they would like to filter out dead tasks. See scx_task_iter_start()
973  * for details.
974  */
975 struct task_struct *scx_task_iter_next_locked(struct scx_task_iter *iter)
976 {
977 	struct task_struct *p;
978 
979 	__scx_task_iter_rq_unlock(iter);
980 
981 	while ((p = scx_task_iter_next(iter))) {
982 		/*
983 		 * scx_task_iter is used to prepare and move tasks into SCX
984 		 * while loading the BPF scheduler and vice-versa while
985 		 * unloading. The init_tasks ("swappers") should be excluded
986 		 * from the iteration because:
987 		 *
988 		 * - It's unsafe to use __setscheduler_class() on an init_task
989 		 *   to determine the sched_class to use as it won't preserve
990 		 *   its idle_sched_class.
991 		 *
992 		 * - ops.init/exit_task() can easily be confused if called with
993 		 *   init_tasks as they, e.g., share PID 0.
994 		 *
995 		 * As init_tasks are never scheduled through SCX, they can be
996 		 * skipped safely. Note that is_idle_task() which tests %PF_IDLE
997 		 * doesn't work here:
998 		 *
999 		 * - %PF_IDLE may not be set for an init_task whose CPU hasn't
1000 		 *   yet been onlined.
1001 		 *
1002 		 * - %PF_IDLE can be set on tasks that are not init_tasks. See
1003 		 *   play_idle_precise() used by CONFIG_IDLE_INJECT.
1004 		 *
1005 		 * Test for idle_sched_class as only init_tasks are on it.
1006 		 */
1007 		if (p->sched_class == &idle_sched_class)
1008 			continue;
1009 
1010 		iter->rq = task_rq_lock(p, &iter->rf);
1011 		iter->locked_task = p;
1012 
1013 		/*
1014 		 * cgroup_task_dead() removes the dead tasks from cset->tasks
1015 		 * after sched_ext_dead() and cgroup iteration may see tasks
1016 		 * which already finished sched_ext_dead(). %SCX_TASK_DEAD is
1017 		 * set by sched_ext_dead() under @p's rq lock. Test it to
1018 		 * avoid visiting tasks which are already dead from SCX POV.
1019 		 */
1020 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
1021 			__scx_task_iter_rq_unlock(iter);
1022 			continue;
1023 		}
1024 
1025 		return p;
1026 	}
1027 	return NULL;
1028 }
1029 
1030 /**
1031  * scx_dump_event - Dump an event 'kind' in 'events' to 's'
1032  * @s: output seq_buf
1033  * @events: event stats
1034  * @kind: a kind of event to dump
1035  */
1036 #define scx_dump_event(s, events, kind) do {					\
1037 	scx_dump_line(&(s), "%40s: %16lld", #kind, (events)->kind);		\
1038 } while (0)
1039 
1040 
1041 static void scx_read_events(struct scx_sched *sch,
1042 			    struct scx_event_stats *events);
1043 
1044 static enum scx_enable_state scx_enable_state(void)
1045 {
1046 	return atomic_read(&scx_enable_state_var);
1047 }
1048 
1049 static enum scx_enable_state scx_set_enable_state(enum scx_enable_state to)
1050 {
1051 	return atomic_xchg(&scx_enable_state_var, to);
1052 }
1053 
1054 static bool scx_tryset_enable_state(enum scx_enable_state to,
1055 				    enum scx_enable_state from)
1056 {
1057 	int from_v = from;
1058 
1059 	return atomic_try_cmpxchg(&scx_enable_state_var, &from_v, to);
1060 }
1061 
1062 /**
1063  * wait_ops_state - Busy-wait the specified ops state to end
1064  * @p: target task
1065  * @opss: state to wait the end of
1066  *
1067  * Busy-wait for @p to transition out of @opss. This can only be used when the
1068  * state part of @opss is %SCX_QUEUEING or %SCX_DISPATCHING. This function also
1069  * has load_acquire semantics to ensure that the caller can see the updates made
1070  * in the enqueueing and dispatching paths.
1071  */
1072 static void wait_ops_state(struct task_struct *p, unsigned long opss)
1073 {
1074 	do {
1075 		cpu_relax();
1076 	} while (atomic_long_read_acquire(&p->scx.ops_state) == opss);
1077 }
1078 
1079 static inline bool __cpu_valid(s32 cpu)
1080 {
1081 	return likely(cpu >= 0 && cpu < nr_cpu_ids && cpu_possible(cpu));
1082 }
1083 
1084 /**
1085  * scx_cpu_valid - Verify a cpu number, to be used on ops input args
1086  * @sch: scx_sched to abort on error
1087  * @cpu: cpu number which came from a BPF ops
1088  * @where: extra information reported on error
1089  *
1090  * @cpu is a cpu number which came from the BPF scheduler and can be any value.
1091  * Verify that it is in range and one of the possible cpus. If invalid, trigger
1092  * an ops error.
1093  */
1094 bool scx_cpu_valid(struct scx_sched *sch, s32 cpu, const char *where)
1095 {
1096 	if (__cpu_valid(cpu)) {
1097 		return true;
1098 	} else {
1099 		scx_error(sch, "invalid CPU %d%s%s", cpu, where ? " " : "", where ?: "");
1100 		return false;
1101 	}
1102 }
1103 
1104 static void deferred_bal_cb_workfn(struct rq *rq)
1105 {
1106 	run_deferred(rq);
1107 }
1108 
1109 static void deferred_irq_workfn(struct irq_work *irq_work)
1110 {
1111 	struct rq *rq = container_of(irq_work, struct rq, scx.deferred_irq_work);
1112 
1113 	raw_spin_rq_lock(rq);
1114 	run_deferred(rq);
1115 	scx_rq_lock_drop(rq);
1116 	raw_spin_rq_unlock(rq);
1117 }
1118 
1119 /**
1120  * schedule_deferred - Schedule execution of deferred actions on an rq
1121  * @rq: target rq
1122  *
1123  * Schedule execution of deferred actions on @rq. Deferred actions are executed
1124  * with @rq locked but unpinned, and thus can unlock @rq to e.g. migrate tasks
1125  * to other rqs.
1126  */
1127 static void schedule_deferred(struct rq *rq)
1128 {
1129 	/*
1130 	 * This is the fallback when schedule_deferred_locked() can't use
1131 	 * the cheaper balance callback or wakeup hook paths (the target
1132 	 * CPU is not in dispatch or wakeup). Currently, this is primarily
1133 	 * hit by reenqueue operations targeting a remote CPU.
1134 	 *
1135 	 * Queue on the target CPU. The deferred work can run from any CPU
1136 	 * correctly - the _locked() path already processes remote rqs from
1137 	 * the calling CPU - but targeting the owning CPU allows IPI delivery
1138 	 * without waiting for the calling CPU to re-enable IRQs and is
1139 	 * cheaper as the reenqueue runs locally.
1140 	 */
1141 	irq_work_queue_on(&rq->scx.deferred_irq_work, cpu_of(rq));
1142 }
1143 
1144 /**
1145  * schedule_deferred_locked - Schedule execution of deferred actions on an rq
1146  * @rq: target rq
1147  *
1148  * Schedule execution of deferred actions on @rq. Equivalent to
1149  * schedule_deferred() but requires @rq to be locked and can be more efficient.
1150  */
1151 static void schedule_deferred_locked(struct rq *rq)
1152 {
1153 	lockdep_assert_rq_held(rq);
1154 
1155 	/*
1156 	 * If in the middle of waking up a task, task_woken_scx() will be called
1157 	 * afterwards which will then run the deferred actions, no need to
1158 	 * schedule anything.
1159 	 */
1160 	if (rq->scx.flags & SCX_RQ_IN_WAKEUP)
1161 		return;
1162 
1163 	/* Don't do anything if there already is a deferred operation. */
1164 	if (rq->scx.flags & SCX_RQ_BAL_CB_PENDING)
1165 		return;
1166 
1167 	/*
1168 	 * If in dispatch without proxy execution, the balance callbacks will
1169 	 * be called before rq lock is released. Schedule one. With proxy
1170 	 * execution, proxy resolution can zap the callbacks without another
1171 	 * SCX dispatch to requeue them, so use irq_work instead.
1172 	 *
1173 	 * We can't directly insert the callback into the
1174 	 * rq's list: The call can drop its lock and make the pending balance
1175 	 * callback visible to unrelated code paths that call rq_pin_lock().
1176 	 *
1177 	 * Just let dispatch_one() know that it must do it itself.
1178 	 */
1179 	if ((rq->scx.flags & SCX_RQ_IN_DISPATCH) && !sched_proxy_exec()) {
1180 		rq->scx.flags |= SCX_RQ_BAL_CB_PENDING;
1181 		return;
1182 	}
1183 
1184 	/*
1185 	 * No scheduler hooks available. Use the generic irq_work path. The
1186 	 * above WAKEUP and DISPATCH paths should cover most of the cases and
1187 	 * the time to IRQ re-enable shouldn't be long.
1188 	 */
1189 	schedule_deferred(rq);
1190 }
1191 
1192 static void resched_irq_workfn(struct irq_work *irq_work)
1193 {
1194 	struct rq *rq = container_of(irq_work, struct rq, scx.resched_irq_work);
1195 
1196 	guard(rq_lock)(rq);
1197 	/* a higher class task would only be picked again, see kick_one_cpu() */
1198 	if (!sched_class_above(rq->donor->sched_class, &ext_sched_class))
1199 		resched_curr(rq);
1200 	scx_rq_lock_drop(rq);
1201 }
1202 
1203 /**
1204  * scx_resched_curr_deferred - Reschedule @rq's cpu from hard irq work on it
1205  * @rq: rq to reschedule
1206  *
1207  * A kick, like a direct resched, only guarantees that a scheduling event on the
1208  * cpu completes after it, and that can be the one in progress. Work that a pick
1209  * processes only at the start of its dispatch, such as the ecaps syncs, can be
1210  * queued after that point and miss the pick. A pick on @rq's cpu runs with IRQs
1211  * off, so the irq work runs after it, and the scheduling event its resched
1212  * triggers starts after this call. A sibling's core scheduling pick for @rq
1213  * isn't covered. A cpu running a task of a higher class isn't rescheduled, as
1214  * its pick would return that task again. @rq's cpu must stay online until the
1215  * irq work is queued.
1216  */
1217 void scx_resched_curr_deferred(struct rq *rq)
1218 {
1219 	irq_work_queue_on(&rq->scx.resched_irq_work, cpu_of(rq));
1220 }
1221 
1222 #ifdef CONFIG_NO_HZ_FULL
1223 static void scx_proxy_tick_bal_cb(struct rq *rq)
1224 {
1225 	sched_update_tick_dependency(rq);
1226 }
1227 
1228 static void scx_proxy_update_tick(struct rq *rq, struct task_struct *next)
1229 {
1230 	bool proxy = next != rq->donor;
1231 	bool was_proxy = rq->scx.flags & SCX_RQ_PROXY_TICK;
1232 
1233 	if (likely(proxy == was_proxy))
1234 		return;
1235 
1236 	if (proxy) {
1237 		/* Keep proxy execution tick-driven for now. */
1238 		rq->scx.flags |= SCX_RQ_PROXY_TICK;
1239 		tick_nohz_dep_set_cpu(cpu_of(rq), TICK_DEP_BIT_SCHED);
1240 	} else {
1241 		rq->scx.flags &= ~SCX_RQ_PROXY_TICK;
1242 		/*
1243 		 * The selected donor is already visible, but rq->curr still
1244 		 * identifies the outgoing execution context. Reevaluate after
1245 		 * context_switch() updates rq->curr so sched_can_stop_tick() sees
1246 		 * the complete selection.
1247 		 */
1248 		queue_balance_callback(rq, &rq->scx.proxy_tick_bal_cb,
1249 				       scx_proxy_tick_bal_cb);
1250 	}
1251 }
1252 #endif
1253 
1254 /*
1255  * Complete sched_ext bookkeeping after proxy resolution and retry tasks which
1256  * couldn't be reenqueued by an earlier reject DSQ drain.
1257  */
1258 void scx_proxy_reenqueue_retry(struct rq *rq, struct task_struct *next)
1259 {
1260 	lockdep_assert_rq_held(rq);
1261 
1262 #ifdef CONFIG_NO_HZ_FULL
1263 	if (scx_enabled() && tick_nohz_full_cpu(cpu_of(rq)))
1264 		scx_proxy_update_tick(rq, next);
1265 #endif
1266 
1267 	/*
1268 	 * A higher priority class may wake up while @rq is transiently idle
1269 	 * for proxy resolution. wakeup_preempt_scx() isn't invoked in that
1270 	 * case, so reenqueue IMMED donors parked on the local DSQ here.
1271 	 */
1272 	if (rq->scx.nr_immed && sched_class_above(rq->next_class, &ext_sched_class))
1273 		scx_schedule_reenq_local(rq, 0);
1274 
1275 	if (rq->scx.flags & SCX_RQ_PROXY_RETRY) {
1276 		rq->scx.flags &= ~SCX_RQ_PROXY_RETRY;
1277 		schedule_deferred_locked(rq);
1278 	}
1279 }
1280 
1281 void schedule_dsq_reenq(struct scx_sched *sch, struct scx_dispatch_q *dsq,
1282 			u64 reenq_flags, struct rq *locked_rq)
1283 {
1284 	struct rq *rq;
1285 
1286 	/*
1287 	 * Allowing reenqueues doesn't make sense while bypassing. This also
1288 	 * blocks from new reenqueues to be scheduled on dead scheds.
1289 	 */
1290 	if (unlikely(READ_ONCE(sch->bypass_depth)))
1291 		return;
1292 
1293 	if (dsq->id == SCX_DSQ_LOCAL) {
1294 		rq = container_of(dsq, struct rq, scx.local_dsq);
1295 
1296 		/*
1297 		 * An inactive cpu's local DSQ holds only tasks that are bound
1298 		 * to it or are being moved off, so a reenq of it is pointless.
1299 		 * Once balance push is installed, queue_balance_callback() also
1300 		 * drops the callback that would run a reenq requested from
1301 		 * dispatch, and irq_work_queue_on() can't reach an offline cpu.
1302 		 * The reenq's node would then stay on this rq's list after
1303 		 * @sch's pcpu is freed.
1304 		 */
1305 		if (unlikely(!cpu_active(cpu_of(rq))))
1306 			return;
1307 
1308 		/*
1309 		 * A sub-sched lacking baseline access on the target cid has no
1310 		 * business triggering IPIs. The lockless test is fine: slipping
1311 		 * through right after a revoke is harmless and a wrong denial
1312 		 * can't happen - if the caller has seen its ownership, so does
1313 		 * this test.
1314 		 */
1315 		if (unlikely(scx_missing_caps(sch, cpu_of(rq), SCX_CAP_BASE))) {
1316 			__scx_add_event(sch, SCX_EV_SUB_REENQ_DENIED, 1);
1317 			return;
1318 		}
1319 
1320 		struct scx_sched_pcpu *sch_pcpu = per_cpu_ptr(sch->pcpu, cpu_of(rq));
1321 		struct scx_deferred_reenq_local *drl = &sch_pcpu->deferred_reenq_local;
1322 
1323 		/*
1324 		 * Pairs with smp_mb() in process_deferred_reenq_locals() and
1325 		 * guarantees that there is a reenq_local() afterwards.
1326 		 */
1327 		smp_mb();
1328 
1329 		if (list_empty(&drl->node) ||
1330 		    (READ_ONCE(drl->flags) & reenq_flags) != reenq_flags) {
1331 
1332 			guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
1333 
1334 			if (list_empty(&drl->node))
1335 				list_move_tail(&drl->node, &rq->scx.deferred_reenq_locals);
1336 			WRITE_ONCE(drl->flags, drl->flags | reenq_flags);
1337 		}
1338 	} else if (!(dsq->id & SCX_DSQ_FLAG_BUILTIN)) {
1339 		rq = this_rq();
1340 
1341 		struct scx_dsq_pcpu *dsq_pcpu = per_cpu_ptr(dsq->pcpu_user, cpu_of(rq));
1342 		struct scx_deferred_reenq_user *dru = &dsq_pcpu->deferred_reenq_user;
1343 
1344 		/*
1345 		 * Pairs with smp_mb() in process_deferred_reenq_users() and
1346 		 * guarantees that there is a reenq_user() afterwards.
1347 		 */
1348 		smp_mb();
1349 
1350 		if (list_empty(&dru->node) ||
1351 		    (READ_ONCE(dru->flags) & reenq_flags) != reenq_flags) {
1352 
1353 			guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
1354 
1355 			/* @dsq is being destroyed, see free_dsq_irq_workfn() */
1356 			if (unlikely(READ_ONCE(dsq->id) == SCX_DSQ_INVALID))
1357 				return;
1358 
1359 			if (list_empty(&dru->node))
1360 				list_move_tail(&dru->node, &rq->scx.deferred_reenq_users);
1361 			WRITE_ONCE(dru->flags, dru->flags | reenq_flags);
1362 		}
1363 	} else {
1364 		/* destroyed since the caller resolved it, nothing to reenq */
1365 		if (READ_ONCE(dsq->id) != SCX_DSQ_INVALID)
1366 			scx_error(sch, "DSQ 0x%llx not allowed for reenq", dsq->id);
1367 		return;
1368 	}
1369 
1370 	if (rq == locked_rq)
1371 		schedule_deferred_locked(rq);
1372 	else
1373 		schedule_deferred(rq);
1374 }
1375 
1376 /*
1377  * p->scx.slice_oob packs an out-of-band slice request into one atomic64. A zero
1378  * word means no request. Otherwise the fields are:
1379  *
1380  *   63      SCX_SLICE_OOB_PENDING, set on every request
1381  *   62-43   lower bits of issuing scheduler's id
1382  *   42-0    requested slice duration in nsecs
1383  *
1384  * A duration of SCX_SLICE_OOB_DUR_MASK means SCX_SLICE_INF. A finite dur
1385  * saturates at SCX_SLICE_OOB_DUR_MASK - 1. The id is used to detect and ignore
1386  * a request that outlived a task ownership change.
1387  *
1388  * Only the low 20 bits of sch->id are packed, which is enough to make
1389  * collisions practically impossible. A theoretical collision just lets a stale
1390  * request through once.
1391  */
1392 enum scx_slice_oob_consts {
1393 	SCX_SLICE_OOB_DUR_BITS	= 43,
1394 	SCX_SLICE_OOB_ID_BITS	= 64 - SCX_SLICE_OOB_DUR_BITS - 1,
1395 
1396 	SCX_SLICE_OOB_DUR_MASK	= (1LLU << SCX_SLICE_OOB_DUR_BITS) - 1,
1397 	SCX_SLICE_OOB_ID_SHIFT	= SCX_SLICE_OOB_DUR_BITS,
1398 	SCX_SLICE_OOB_ID_MASK	= (1LLU << SCX_SLICE_OOB_ID_BITS) - 1,
1399 	SCX_SLICE_OOB_PENDING	= 1LLU << 63,
1400 };
1401 
1402 /*
1403  * Slice and dsq_vtime write rules
1404  *
1405  * While @p is running, sleeping or queued on an rq-owned DSQ, both fields are
1406  * protected by the rq lock. While running, the rq lock is required because
1407  * update_curr_scx() RMWs the slice and the cap check for slice extension is
1408  * only reliable under the rq lock.
1409  *
1410  * While @p is queued on a user DSQ or on the BPF side, the kernel neither
1411  * consumes nor decides on the fields. Synchronizing the writers is the BPF
1412  * scheduler's responsibility. An rq-locked scx_bpf_task_set_slice() write and a
1413  * concurrent DSQ insertion commit can race each other and whichever lands last
1414  * wins.
1415  *
1416  * A DSQ insert kfunc doesn't update the fields directly. The verdict carries
1417  * the values and apply_slice_vtime() commits them at the insertion.
1418  *
1419  * scx_bpf_task_set_slice() may be called from any context and writes directly
1420  * only if @p's rq lock is already held, otherwise it bounces through
1421  * p->scx.slice_oob, applied under @p's rq lock at the next slice consideration.
1422  *
1423  * While %SCX_TASK_PROTECTED is set, every scheduler-reachable slice update is
1424  * refused. See set_task_slice_keep_oob(). A kernel slice, see
1425  * %SCX_TASK_KERNEL_SLICE, can be shortened but not extended.
1426  *
1427  * dsq_vtime orders the next PRIQ insertion and has no running-side consumer, so
1428  * scx_bpf_task_set_dsq_vtime() writes it directly. Fork-time init and direct
1429  * BPF stores from non-cid-form schedulers are outside these rules.
1430  */
1431 
1432 /* clear a pending slice request */
1433 static void clear_task_slice_oob(struct task_struct *p)
1434 {
1435 	if (unlikely(atomic64_read(&p->scx.slice_oob)))
1436 		atomic64_set(&p->scx.slice_oob, 0);
1437 }
1438 
1439 /**
1440  * dsq_insert_head - FIFO head insertion honoring %SCX_TASK_PROTECTED
1441  * @dsq: DSQ to insert into
1442  * @p: task being inserted
1443  *
1444  * A HEAD insert should land behind any leading protected tasks. Return %true
1445  * indicates whether @p became the first entry.
1446  */
1447 static bool dsq_insert_head(struct scx_dispatch_q *dsq, struct task_struct *p)
1448 {
1449 	struct list_head *pos = &dsq->list;
1450 	struct scx_dsq_list_node *node;
1451 
1452 	/*
1453 	 * Only rq-owned DSQs can hold protected tasks and the associated rq
1454 	 * lock keeps their flags stable.
1455 	 */
1456 	if (!dsq_is_rq_owned(dsq)) {
1457 		list_add(&p->scx.dsq_list.node, &dsq->list);
1458 		return true;
1459 	}
1460 
1461 	list_for_each_entry(node, &dsq->list, node) {
1462 		struct task_struct *q;
1463 
1464 		if (WARN_ON_ONCE(node->flags & SCX_DSQ_LNODE_ITER_CURSOR))
1465 			continue;
1466 
1467 		q = container_of(node, struct task_struct, scx.dsq_list);
1468 		if (!(q->scx.flags & SCX_TASK_PROTECTED))
1469 			break;
1470 
1471 		pos = &node->node;
1472 	}
1473 
1474 	list_add(&p->scx.dsq_list.node, pos);
1475 
1476 	return pos == &dsq->list;
1477 }
1478 
1479 /**
1480  * set_task_slice_keep_oob - Set @p's slice, leaving any pending oob request
1481  * @p: task of interest
1482  * @slice: slice to set
1483  *
1484  * While %SCX_TASK_PROTECTED is set, BPF schedulers may not modify the slice.
1485  * Refuse and return %false.
1486  */
1487 static bool set_task_slice_keep_oob(struct task_struct *p, u64 slice)
1488 {
1489 	lockdep_assert_rq_held(task_rq(p));
1490 
1491 	if (unlikely(p->scx.flags & SCX_TASK_PROTECTED))
1492 		return false;
1493 
1494 	p->scx.slice = slice;
1495 	return true;
1496 }
1497 
1498 /* set @p's slice, superseding any pending out-of-band request */
1499 bool scx_set_task_slice(struct task_struct *p, u64 slice)
1500 {
1501 	if (!set_task_slice_keep_oob(p, slice))
1502 		return false;
1503 	clear_task_slice_oob(p);
1504 	return true;
1505 }
1506 
1507 /**
1508  * scx_task_slice_ended - @p's slice is consumed or given up
1509  * @rq: rq @p is on
1510  * @p: task of interest
1511  *
1512  * End what rides on the slice - the protection, the kernel's ownership of the
1513  * slice, and the rescue if @p is being rescued.
1514  *
1515  * A dequeue normally ends the slice too. The exception is a save/restore pair
1516  * on the running task. Attribute changes like renice cycle the task through
1517  * dequeue and enqueue while it keeps executing, so the slice continues. A
1518  * queued task instead loses its DSQ position on any dequeue and the slice ends
1519  * with it.
1520  */
1521 void scx_task_slice_ended(struct rq *rq, struct task_struct *p)
1522 {
1523 	lockdep_assert_rq_held(rq);
1524 
1525 	p->scx.flags &= ~(SCX_TASK_PROTECTED | SCX_TASK_KERNEL_SLICE);
1526 	if (unlikely(p == scx_rescuee(rq)))
1527 		scx_rescue_end(rq);
1528 }
1529 
1530 /* request @p's slice to be set to @slice, see the write rules above */
1531 static void set_task_slice_oob(struct scx_sched *sch, struct task_struct *p, u64 slice)
1532 {
1533 	u64 dur;
1534 
1535 	if (slice == SCX_SLICE_INF) {
1536 		dur = SCX_SLICE_OOB_DUR_MASK;
1537 	} else if (unlikely(slice >= SCX_SLICE_OOB_DUR_MASK)) {
1538 		dur = SCX_SLICE_OOB_DUR_MASK - 1;
1539 		scx_add_event(sch, SCX_EV_SLICE_CLAMPED, 1);
1540 	} else {
1541 		dur = slice;
1542 	}
1543 
1544 	atomic64_set(&p->scx.slice_oob, SCX_SLICE_OOB_PENDING |
1545 		     ((sch->id & SCX_SLICE_OOB_ID_MASK) << SCX_SLICE_OOB_ID_SHIFT) | dur);
1546 }
1547 
1548 /*
1549  * Apply a pending out-of-band slice request under @rq's lock. A request whose
1550  * packed id no longer matches @p's current owner is dropped. An extension needs
1551  * baseline cpu access on @p's cid and is refused on a kernel slice. Shortening
1552  * is always allowed. A protected slice refuses both. %SCX_EV_SLICE_DENIED
1553  * counts the denials. See the write rules above.
1554  */
1555 static void apply_task_slice_oob(struct rq *rq, struct task_struct *p)
1556 {
1557 	u64 oob, dur, slice;
1558 
1559 	lockdep_assert_rq_held(rq);
1560 
1561 	if (likely(!atomic64_read(&p->scx.slice_oob)))
1562 		return;
1563 
1564 	oob = atomic64_xchg(&p->scx.slice_oob, 0);
1565 	if (unlikely(!oob))
1566 		return;
1567 
1568 	/* the issuing scheduler no longer owns @p, drop the request */
1569 	if (unlikely(((oob >> SCX_SLICE_OOB_ID_SHIFT) & SCX_SLICE_OOB_ID_MASK) !=
1570 		     (scx_task_sched(p)->id & SCX_SLICE_OOB_ID_MASK)))
1571 		return;
1572 
1573 	dur = oob & SCX_SLICE_OOB_DUR_MASK;
1574 	slice = dur == SCX_SLICE_OOB_DUR_MASK ? SCX_SLICE_INF : dur;
1575 
1576 	if (slice > p->scx.slice &&
1577 	    unlikely(scx_task_has_kernel_slice(p) ||
1578 		     scx_missing_caps(scx_task_sched(p), cpu_of(rq), SCX_CAP_BASE))) {
1579 		__scx_add_event(scx_task_sched(p), SCX_EV_SLICE_DENIED, 1);
1580 		return;
1581 	}
1582 
1583 	if (unlikely(!set_task_slice_keep_oob(p, slice)))
1584 		__scx_add_event(scx_task_sched(p), SCX_EV_SLICE_DENIED, 1);
1585 }
1586 
1587 /*
1588  * A dsq insert kfunc doesn't write slice or dsq_vtime. The verdict carries them
1589  * and they are committed here, at the insertion. A zero @slice keeps the
1590  * current value, floored at 1 so the task isn't treated as expired.
1591  */
1592 static void apply_slice_vtime(struct task_struct *p, u64 slice, u64 vtime, u64 enq_flags)
1593 {
1594 	if (slice) {
1595 		p->scx.slice = slice;
1596 		/*
1597 		 * An explicit slice supersedes a pending oob request. A carried
1598 		 * default refill is not an explicit request and must keep it.
1599 		 */
1600 		if (!(enq_flags & SCX_ENQ_SLICE_DFL))
1601 			clear_task_slice_oob(p);
1602 	} else if (!p->scx.slice) {
1603 		p->scx.slice = 1;
1604 	}
1605 
1606 	if (enq_flags & SCX_ENQ_DSQ_PRIQ)
1607 		p->scx.dsq_vtime = vtime;
1608 }
1609 
1610 /*
1611  * refill_task_slice_dfl() supplies a slice when the scheduler left none and
1612  * expire_task_slice() takes it away to force the task off the cpu. Neither
1613  * touches a kernel slice, see %SCX_TASK_KERNEL_SLICE.
1614  */
1615 static void refill_task_slice_dfl(struct scx_sched *sch, struct task_struct *p)
1616 {
1617 	if (scx_task_has_kernel_slice(p))
1618 		return;
1619 
1620 	/*
1621 	 * A default refill is not an explicit request, so it must not drop a
1622 	 * pending out-of-band one, which is applied when @p next runs.
1623 	 */
1624 	set_task_slice_keep_oob(p, READ_ONCE(sch->slice_dfl));
1625 	__scx_add_event(sch, SCX_EV_REFILL_SLICE_DFL, 1);
1626 }
1627 
1628 static void expire_task_slice(struct task_struct *p)
1629 {
1630 	/*
1631 	 * Unlike the refill above, an expiry supersedes a pending out-of-band
1632 	 * request. A kept request would be applied at the next
1633 	 * update_curr_scx() and undo the expiry.
1634 	 */
1635 	if (!scx_task_has_kernel_slice(p))
1636 		scx_set_task_slice(p, 0);
1637 }
1638 
1639 static void update_curr_scx(struct rq *rq)
1640 {
1641 	struct task_struct *donor;
1642 	s64 delta_exec;
1643 
1644 	/*
1645 	 * update_curr_scx() is selected through rq->donor->sched_class, not
1646 	 * rq->curr->sched_class, so @donor is always an EXT task here. If an EXT
1647 	 * owner executes for a FAIR donor, FAIR's update_curr() runs instead.
1648 	 */
1649 	donor = rq->donor;
1650 
1651 	/* apply even on 0 delta_exec, callers may still act on the slice */
1652 	apply_task_slice_oob(rq, donor);
1653 
1654 	delta_exec = update_curr_common(rq);
1655 	if (unlikely(delta_exec <= 0))
1656 		return;
1657 
1658 	if (donor->scx.slice != SCX_SLICE_INF)
1659 		donor->scx.slice -= min_t(u64, donor->scx.slice, delta_exec);
1660 
1661 	if (unlikely(donor == scx_rescuee(rq)))
1662 		scx_rescue_charge(rq, delta_exec);
1663 
1664 	dl_server_update(&rq->ext_server, delta_exec);
1665 }
1666 
1667 static bool scx_dsq_priq_less(struct rb_node *node_a,
1668 			      const struct rb_node *node_b)
1669 {
1670 	const struct task_struct *a =
1671 		container_of(node_a, struct task_struct, scx.dsq_priq);
1672 	const struct task_struct *b =
1673 		container_of(node_b, struct task_struct, scx.dsq_priq);
1674 
1675 	return time_before64(a->scx.dsq_vtime, b->scx.dsq_vtime);
1676 }
1677 
1678 static void dsq_inc_nr(struct scx_dispatch_q *dsq, struct task_struct *p, u64 enq_flags)
1679 {
1680 	/* scx_bpf_dsq_nr_queued() reads ->nr without locking, use WRITE_ONCE() */
1681 	WRITE_ONCE(dsq->nr, dsq->nr + 1);
1682 
1683 	/*
1684 	 * Once @p reaches a local DSQ, it can only leave it by being dispatched
1685 	 * to the CPU or dequeued. In both cases, the only way @p can go back to
1686 	 * the BPF sched is through enqueueing. If being inserted into a local
1687 	 * DSQ with IMMED, persist the state until the next enqueueing event in
1688 	 * scx_do_enqueue_task() so that we can maintain IMMED protection
1689 	 * through e.g. SAVE/RESTORE cycles and slice extensions.
1690 	 */
1691 	if (enq_flags & SCX_ENQ_IMMED) {
1692 		if (unlikely(dsq->id != SCX_DSQ_LOCAL)) {
1693 			WARN_ON_ONCE(!(enq_flags & SCX_ENQ_GDSQ_FALLBACK));
1694 			return;
1695 		}
1696 		p->scx.flags |= SCX_TASK_IMMED;
1697 	}
1698 
1699 	if (p->scx.flags & SCX_TASK_IMMED) {
1700 		struct rq *rq = container_of(dsq, struct rq, scx.local_dsq);
1701 
1702 		if (WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL))
1703 			return;
1704 
1705 		rq->scx.nr_immed++;
1706 
1707 		/*
1708 		 * If @rq already had other tasks or the current task is not
1709 		 * done yet, @p can't go on the CPU immediately. Re-enqueue.
1710 		 */
1711 		if (unlikely(dsq->nr > 1 || !rq_is_open(rq, enq_flags)))
1712 			scx_schedule_reenq_local(rq, 0);
1713 	}
1714 }
1715 
1716 static void dsq_dec_nr(struct scx_dispatch_q *dsq, struct task_struct *p)
1717 {
1718 	/* see dsq_inc_nr() */
1719 	WRITE_ONCE(dsq->nr, dsq->nr - 1);
1720 
1721 	if (p->scx.flags & SCX_TASK_IMMED) {
1722 		struct rq *rq = container_of(dsq, struct rq, scx.local_dsq);
1723 
1724 		if (WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL) ||
1725 		    WARN_ON_ONCE(rq->scx.nr_immed <= 0))
1726 			return;
1727 
1728 		rq->scx.nr_immed--;
1729 	}
1730 }
1731 
1732 /*
1733  * Return true if @p is moving due to an internal SCX migration, false
1734  * otherwise.
1735  */
1736 static inline bool task_scx_migrating(struct task_struct *p)
1737 {
1738 	/*
1739 	 * We only need to check sticky_cpu: it is set to the destination
1740 	 * CPU in move_remote_task_to_local_dsq() before deactivate_task()
1741 	 * and cleared when the task is enqueued on the destination, so it
1742 	 * is only non-negative during an internal SCX migration.
1743 	 */
1744 	return p->scx.sticky_cpu >= 0;
1745 }
1746 
1747 /* Must be called under the lock serializing @p's custody transfers. */
1748 static bool task_leave_custody(struct task_struct *p)
1749 {
1750 	if (!(p->scx.flags & SCX_TASK_IN_CUSTODY) || task_scx_migrating(p))
1751 		return false;
1752 
1753 	p->scx.flags &= ~SCX_TASK_IN_CUSTODY;
1754 	return true;
1755 }
1756 
1757 /*
1758  * A task with an infinite slice may be running with its tick stopped. Lazy
1759  * rescheduling doesn't send an IPI, so restore the tick dependency to guarantee
1760  * that the lazy request is promoted by a real scheduler tick. Set the lazy
1761  * request first so that the dependency update's IPI can also serve it on return
1762  * to user space.
1763  */
1764 static void scx_resched_curr_lazy(struct rq *rq)
1765 {
1766 	resched_curr_lazy(rq);
1767 
1768 	if (rq->scx.flags & SCX_RQ_CAN_STOP_TICK) {
1769 		rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK;
1770 		if (rq->clock_update_flags < RQCF_UPDATED)
1771 			update_rq_clock(rq);
1772 		update_other_load_avgs(rq);
1773 		sched_update_tick_dependency(rq);
1774 	}
1775 }
1776 
1777 static void rq_owned_post_enq(struct scx_sched *sch, struct rq *rq,
1778 			      struct scx_dispatch_q *dsq, struct task_struct *p,
1779 			      u64 enq_flags)
1780 {
1781 	if (task_leave_custody(p) && SCX_HAS_OP(sch, dequeue))
1782 		SCX_CALL_OP_TASK(sch, dequeue, rq, p, 0);
1783 
1784 	/*
1785 	 * Only local inserts get the wakeup treatment below. Rejects kick a
1786 	 * deferred reenq and rescue parks are paced by the rescue timer. Proxy
1787 	 * rejects which aren't ready when drained request a later retry from
1788 	 * scx_proxy_reenqueue_retry().
1789 	 */
1790 	if (unlikely(dsq->id != SCX_DSQ_LOCAL)) {
1791 		if (dsq->id == SCX_DSQ_REJECT)
1792 			schedule_deferred_locked(rq);
1793 		return;
1794 	}
1795 
1796 	/*
1797 	 * Note that @rq's lock may be dropped between this enqueue and @p
1798 	 * actually getting on CPU. This gives higher-class tasks (e.g. RT)
1799 	 * an opportunity to wake up on @rq and prevent @p from running.
1800 	 * Here are some concrete examples:
1801 	 *
1802 	 * Example 1:
1803 	 *
1804 	 * We dispatch two tasks from a single ops.dispatch():
1805 	 * - First, a local task to this CPU's local DSQ;
1806 	 * - Second, a local/remote task to a remote CPU's local DSQ.
1807 	 * We must drop the local rq lock in order to finish the second
1808 	 * dispatch. In that time, an RT task can wake up on the local rq.
1809 	 *
1810 	 * Example 2:
1811 	 *
1812 	 * We dispatch a local/remote task to a remote CPU's local DSQ.
1813 	 * We must drop the remote rq lock before the dispatched task can run,
1814 	 * which gives an RT task an opportunity to wake up on the remote rq.
1815 	 *
1816 	 * Both examples work the same if we replace dispatching with moving
1817 	 * the tasks from a user-created DSQ.
1818 	 *
1819 	 * We must detect these wakeups so that we can re-enqueue IMMED tasks
1820 	 * from @rq's local DSQ. scx_wakeup_preempt() serves exactly this
1821 	 * purpose, but for it to be invoked, we must ensure that we bump
1822 	 * @rq->next_class to &ext_sched_class if it's currently idle.
1823 	 *
1824 	 * wakeup_preempt() does the bumping, and since we only invoke it if
1825 	 * @rq->next_class is below &ext_sched_class, it will also
1826 	 * resched_curr(rq).
1827 	 */
1828 	if (sched_class_above(p->sched_class, rq->next_class))
1829 		wakeup_preempt(rq, p, 0);
1830 
1831 	/*
1832 	 * If @rq is in dispatch, the CPU is already vacant and looking for the
1833 	 * next task to run. No need to preempt or trigger resched after moving
1834 	 * @p into its local DSQ.
1835 	 * Note that the wakeup_preempt() above may have already triggered
1836 	 * a resched if @rq->next_class was idle. It's harmless, since
1837 	 * need_resched is cleared immediately after task pick.
1838 	 */
1839 	if (rq->scx.flags & SCX_RQ_IN_DISPATCH)
1840 		return;
1841 
1842 	if ((enq_flags & (SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY)) &&
1843 	    p != rq->donor && rq->donor->sched_class == &ext_sched_class) {
1844 		if (likely(scx_set_task_slice(rq->donor, 0))) {
1845 			if (enq_flags & SCX_ENQ_PREEMPT)
1846 				resched_curr(rq);
1847 			else
1848 				scx_resched_curr_lazy(rq);
1849 		} else {
1850 			__scx_add_event(sch, SCX_EV_SLICE_DENIED, 1);
1851 		}
1852 	}
1853 }
1854 
1855 static void scx_dispatch_enqueue(struct scx_sched *sch, struct rq *rq,
1856 				 struct scx_dispatch_q *dsq, struct task_struct *p,
1857 				 u64 slice, u64 vtime, u64 enq_flags)
1858 {
1859 	bool is_rq_owned = dsq_is_rq_owned(dsq);
1860 
1861 	if (dsq->id == SCX_DSQ_LOCAL)
1862 		dsq = scx_resolve_local_dsq(sch, rq, p, &enq_flags);
1863 
1864 	WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node));
1865 	WARN_ON_ONCE((p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) ||
1866 		     !RB_EMPTY_NODE(&p->scx.dsq_priq));
1867 
1868 	if (!is_rq_owned) {
1869 		raw_spin_lock_nested(&dsq->lock,
1870 			(enq_flags & SCX_ENQ_NESTED) ? SINGLE_DEPTH_NESTING : 0);
1871 
1872 		if (unlikely(dsq->id == SCX_DSQ_INVALID)) {
1873 			scx_error(sch, "attempting to dispatch to a destroyed dsq");
1874 			/* fall back to the global dsq */
1875 			raw_spin_unlock(&dsq->lock);
1876 			dsq = find_global_dsq(sch, task_cpu(p));
1877 			raw_spin_lock(&dsq->lock);
1878 		}
1879 	}
1880 
1881 	if (unlikely((dsq->id & SCX_DSQ_FLAG_BUILTIN) &&
1882 		     (enq_flags & SCX_ENQ_DSQ_PRIQ))) {
1883 		/*
1884 		 * SCX_DSQ_LOCAL and SCX_DSQ_GLOBAL DSQs always consume from
1885 		 * their FIFO queues. To avoid confusion and accidentally
1886 		 * starving vtime-dispatched tasks by FIFO-dispatched tasks, we
1887 		 * disallow any internal DSQ from doing vtime ordering of
1888 		 * tasks.
1889 		 */
1890 		scx_error(sch, "cannot use vtime ordering for built-in DSQs");
1891 		enq_flags &= ~SCX_ENQ_DSQ_PRIQ;
1892 	}
1893 
1894 	/*
1895 	 * @dsq is locked and @enq_flags is sanitized. Commit the carried slice
1896 	 * and vtime before the PRIQ insertion below reads the new dsq_vtime.
1897 	 */
1898 	if (enq_flags & SCX_ENQ_APPLY_SLICE)
1899 		apply_slice_vtime(p, slice, vtime, enq_flags);
1900 
1901 	if (enq_flags & SCX_ENQ_DSQ_PRIQ) {
1902 		struct rb_node *rbp;
1903 
1904 		/*
1905 		 * A PRIQ DSQ shouldn't be using FIFO enqueueing. As tasks are
1906 		 * linked to both the rbtree and list on PRIQs, this can only be
1907 		 * tested easily when adding the first task.
1908 		 */
1909 		if (unlikely(RB_EMPTY_ROOT(&dsq->priq) &&
1910 			     nldsq_next_task(dsq, NULL, false)))
1911 			scx_error(sch, "DSQ ID 0x%016llx already had FIFO-enqueued tasks",
1912 				  dsq->id);
1913 
1914 		p->scx.dsq_flags |= SCX_TASK_DSQ_ON_PRIQ;
1915 		rb_add(&p->scx.dsq_priq, &dsq->priq, scx_dsq_priq_less);
1916 
1917 		/*
1918 		 * Find the previous task and insert after it on the list so
1919 		 * that @dsq->list is vtime ordered.
1920 		 */
1921 		rbp = rb_prev(&p->scx.dsq_priq);
1922 		if (rbp) {
1923 			struct task_struct *prev =
1924 				container_of(rbp, struct task_struct,
1925 					     scx.dsq_priq);
1926 			list_add(&p->scx.dsq_list.node, &prev->scx.dsq_list.node);
1927 			/* first task unchanged - no update needed */
1928 		} else {
1929 			list_add(&p->scx.dsq_list.node, &dsq->list);
1930 			/* not builtin and new task is at head - use fastpath */
1931 			rcu_assign_pointer(dsq->first_task, p);
1932 		}
1933 	} else {
1934 		/* a FIFO DSQ shouldn't be using PRIQ enqueuing */
1935 		if (unlikely(!RB_EMPTY_ROOT(&dsq->priq)))
1936 			scx_error(sch, "DSQ ID 0x%016llx already had PRIQ-enqueued tasks",
1937 				  dsq->id);
1938 
1939 		if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY)) {
1940 			/* new task inserted at head - use fastpath */
1941 			if (dsq_insert_head(dsq, p) && !(dsq->id & SCX_DSQ_FLAG_BUILTIN))
1942 				rcu_assign_pointer(dsq->first_task, p);
1943 		} else {
1944 			/*
1945 			 * dsq->list can contain parked BPF iterator cursors, so
1946 			 * list_empty() here isn't a reliable proxy for "no real
1947 			 * task in the DSQ". Test dsq->first_task directly.
1948 			 */
1949 			list_add_tail(&p->scx.dsq_list.node, &dsq->list);
1950 			if (!dsq->first_task && !(dsq->id & SCX_DSQ_FLAG_BUILTIN))
1951 				rcu_assign_pointer(dsq->first_task, p);
1952 		}
1953 	}
1954 
1955 	/* seq records the order tasks are queued, used by BPF DSQ iterator */
1956 	WRITE_ONCE(dsq->seq, dsq->seq + 1);
1957 	p->scx.dsq_seq = dsq->seq;
1958 
1959 	dsq_inc_nr(dsq, p, enq_flags);
1960 	p->scx.dsq = dsq;
1961 
1962 	/*
1963 	 * Update custody and call ops.dequeue() before clearing ops_state:
1964 	 * once ops_state is cleared, waiters in ops_dequeue() can proceed
1965 	 * and dequeue_task_scx() will RMW p->scx.flags. If we clear
1966 	 * ops_state first, both sides would modify p->scx.flags
1967 	 * concurrently in a non-atomic way.
1968 	 */
1969 	if (is_rq_owned) {
1970 		rq_owned_post_enq(sch, rq, dsq, p, enq_flags);
1971 	} else {
1972 		bool call_dequeue = false;
1973 
1974 		/*
1975 		 * Global and bypass DSQs are terminal - the task leaves the
1976 		 * scheduler's custody, so ops.dequeue() fires. It can run
1977 		 * without @p's rq lock (finish_dispatch() passes the dispatch
1978 		 * rq); that's safe because dequeue_task_scx() waits on
1979 		 * SCX_OPSS_DISPATCHING (see the ops_state note above) and so
1980 		 * can't race it. A non-terminal DSQ keeps the task in custody.
1981 		 * The custody transfer happens under @dsq->lock so that later
1982 		 * consumers see the flag clear; the callback runs after
1983 		 * @dsq->lock is dropped because it may lock a DSQ itself.
1984 		 */
1985 		if (dsq->id == SCX_DSQ_GLOBAL || dsq->id == SCX_DSQ_BYPASS)
1986 			call_dequeue = task_leave_custody(p);
1987 		else
1988 			p->scx.flags |= SCX_TASK_IN_CUSTODY;
1989 
1990 		raw_spin_unlock(&dsq->lock);
1991 
1992 		if (call_dequeue && SCX_HAS_OP(sch, dequeue))
1993 			SCX_CALL_OP_TASK(sch, dequeue, rq, p, 0);
1994 	}
1995 
1996 	/*
1997 	 * We're transitioning out of QUEUEING or DISPATCHING. store_release to
1998 	 * match waiters' load_acquire.
1999 	 */
2000 	if (enq_flags & SCX_ENQ_CLEAR_OPSS)
2001 		atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
2002 }
2003 
2004 void scx_task_unlink_from_dsq(struct task_struct *p, struct scx_dispatch_q *dsq)
2005 {
2006 	WARN_ON_ONCE(list_empty(&p->scx.dsq_list.node));
2007 
2008 	if (p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) {
2009 		rb_erase(&p->scx.dsq_priq, &dsq->priq);
2010 		RB_CLEAR_NODE(&p->scx.dsq_priq);
2011 		p->scx.dsq_flags &= ~SCX_TASK_DSQ_ON_PRIQ;
2012 	}
2013 	p->scx.dsq_flags &= ~SCX_TASK_DSQ_REENQ;
2014 
2015 	list_del_init(&p->scx.dsq_list.node);
2016 	dsq_dec_nr(dsq, p);
2017 
2018 	if (!(dsq->id & SCX_DSQ_FLAG_BUILTIN) && rcu_access_pointer(dsq->first_task) == p) {
2019 		struct task_struct *first_task;
2020 
2021 		first_task = nldsq_next_task(dsq, NULL, false);
2022 		rcu_assign_pointer(dsq->first_task, first_task);
2023 	}
2024 }
2025 
2026 void scx_dispatch_dequeue(struct rq *rq, struct task_struct *p)
2027 {
2028 	struct scx_dispatch_q *dsq = p->scx.dsq;
2029 	bool is_rq_owned = dsq && dsq_is_rq_owned(dsq);
2030 
2031 	lockdep_assert_rq_held(rq);
2032 
2033 	if (!dsq) {
2034 		/*
2035 		 * If !dsq && on-list, @p is on @rq's ddsp_deferred_locals.
2036 		 * Unlinking is all that's needed to cancel.
2037 		 */
2038 		if (unlikely(!list_empty(&p->scx.dsq_list.node)))
2039 			list_del_init(&p->scx.dsq_list.node);
2040 
2041 		/*
2042 		 * When dispatch_to_local_dsq() or remote consumption moves a
2043 		 * task to a local DSQ, the task isn't associated with any DSQ
2044 		 * but @p->scx.holding_cpu may be set. Clearing holding_cpu
2045 		 * tells dispatch_to_local_dsq() that it lost to a dequeue.
2046 		 */
2047 		if (p->scx.holding_cpu >= 0)
2048 			p->scx.holding_cpu = -1;
2049 
2050 		return;
2051 	}
2052 
2053 	if (!is_rq_owned)
2054 		raw_spin_lock(&dsq->lock);
2055 
2056 	/*
2057 	 * Now that we hold @dsq->lock, @p->holding_cpu and @p->scx.dsq_* can't
2058 	 * change underneath us.
2059 	*/
2060 	if (p->scx.holding_cpu < 0) {
2061 		/* @p must still be on @dsq, dequeue */
2062 		scx_task_unlink_from_dsq(p, dsq);
2063 	} else {
2064 		/*
2065 		 * We're racing against unlink_dsq_and_switch_rq_lock(),
2066 		 * which already removed @p from @dsq and set
2067 		 * @p->scx.holding_cpu. Clear holding_cpu to tell
2068 		 * unlink_dsq_and_switch_rq_lock() that it lost the race.
2069 		 */
2070 		WARN_ON_ONCE(!list_empty(&p->scx.dsq_list.node));
2071 		p->scx.holding_cpu = -1;
2072 	}
2073 	p->scx.dsq = NULL;
2074 
2075 	if (!is_rq_owned)
2076 		raw_spin_unlock(&dsq->lock);
2077 }
2078 
2079 /*
2080  * Abbreviated version of scx_dispatch_dequeue() that can be used when both
2081  * @p's rq and dsq are locked.
2082  */
2083 static void dispatch_dequeue_locked(struct task_struct *p,
2084 				    struct scx_dispatch_q *dsq)
2085 {
2086 	lockdep_assert_rq_held(task_rq(p));
2087 	lockdep_assert_held(&dsq->lock);
2088 
2089 	scx_task_unlink_from_dsq(p, dsq);
2090 	p->scx.dsq = NULL;
2091 }
2092 
2093 static struct scx_dispatch_q *find_dsq_for_dispatch(struct scx_sched *sch,
2094 						    struct rq *rq, u64 dsq_id,
2095 						    s32 tcpu)
2096 {
2097 	struct scx_dispatch_q *dsq;
2098 
2099 	if (dsq_id == SCX_DSQ_LOCAL)
2100 		return &rq->scx.local_dsq;
2101 
2102 	if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
2103 		s32 cpu = scx_cpu_ret(sch, dsq_id & SCX_DSQ_LOCAL_CPU_MASK);
2104 
2105 		if (!scx_cpu_valid(sch, cpu, "in SCX_DSQ_LOCAL_ON dispatch verdict"))
2106 			return find_global_dsq(sch, tcpu);
2107 
2108 		return &cpu_rq(cpu)->scx.local_dsq;
2109 	}
2110 
2111 	if (dsq_id == SCX_DSQ_GLOBAL)
2112 		dsq = find_global_dsq(sch, tcpu);
2113 	else
2114 		dsq = find_user_dsq(sch, dsq_id);
2115 
2116 	/*
2117 	 * Built-in DSQs are never inserted into dsq_hash, so REJECT and RESCUE
2118 	 * hit the error below. They cannot be reached with an ID.
2119 	 */
2120 	if (unlikely(!dsq)) {
2121 		scx_error(sch, "non-existent DSQ 0x%llx", dsq_id);
2122 		return find_global_dsq(sch, tcpu);
2123 	}
2124 
2125 	return dsq;
2126 }
2127 
2128 static void mark_direct_dispatch(struct scx_sched *sch,
2129 				 struct task_struct *ddsp_task,
2130 				 struct task_struct *p, u64 dsq_id,
2131 				 u64 slice, u64 vtime, u64 enq_flags)
2132 {
2133 	/*
2134 	 * Mark that dispatch already happened from ops.select_cpu() or
2135 	 * ops.enqueue() by spoiling direct_dispatch_task with a non-NULL value
2136 	 * which can never match a valid task pointer.
2137 	 */
2138 	__this_cpu_write(direct_dispatch_task, ERR_PTR(-ESRCH));
2139 
2140 	/* @p must match the task on the enqueue path */
2141 	if (unlikely(p != ddsp_task)) {
2142 		if (IS_ERR(ddsp_task))
2143 			scx_error(sch, "%s[%d] already direct-dispatched",
2144 				  p->comm, p->pid);
2145 		else
2146 			scx_error(sch, "scheduling for %s[%d] but trying to direct-dispatch %s[%d]",
2147 				  ddsp_task->comm, ddsp_task->pid,
2148 				  p->comm, p->pid);
2149 		return;
2150 	}
2151 
2152 	WARN_ON_ONCE(p->scx.ddsp_dsq_id != SCX_DSQ_INVALID);
2153 	WARN_ON_ONCE(p->scx.ddsp_enq_flags);
2154 
2155 	p->scx.ddsp_slice = slice;
2156 	p->scx.ddsp_vtime = vtime;
2157 	p->scx.ddsp_dsq_id = dsq_id;
2158 	p->scx.ddsp_enq_flags = enq_flags;
2159 }
2160 
2161 /*
2162  * Clear @p direct dispatch state when leaving the scheduler.
2163  *
2164  * Direct dispatch state must be cleared in the following cases:
2165  *  - direct_dispatch(): cleared on the synchronous enqueue path, deferred
2166  *    dispatch keeps the state until consumed
2167  *  - process_ddsp_deferred_locals(): cleared after consuming deferred state,
2168  *  - scx_do_enqueue_task(): cleared on enqueue fallbacks where the dispatch
2169  *    verdict is ignored (local/global/bypass)
2170  *  - dequeue_task_scx(): cleared after scx_dispatch_dequeue(), covering
2171  *    deferred cancellation and holding_cpu races
2172  *  - scx_disable_task(): cleared for queued wakeup tasks, which are excluded by
2173  *    the scx_bypass() loop, so that stale state is not reused by a subsequent
2174  *    scheduler instance
2175  */
2176 static inline void clear_direct_dispatch(struct task_struct *p)
2177 {
2178 	p->scx.ddsp_dsq_id = SCX_DSQ_INVALID;
2179 	p->scx.ddsp_enq_flags = 0;
2180 }
2181 
2182 static void direct_dispatch(struct scx_sched *sch, struct task_struct *p,
2183 			    u64 enq_flags)
2184 {
2185 	struct rq *rq = task_rq(p);
2186 	struct scx_dispatch_q *dsq =
2187 		find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, task_cpu(p));
2188 	u64 ddsp_enq_flags, slice, vtime;
2189 
2190 	p->scx.ddsp_enq_flags |= enq_flags;
2191 
2192 	/*
2193 	 * We are in the enqueue path with @rq locked and pinned, and thus can't
2194 	 * double lock a remote rq and enqueue to its local DSQ. For
2195 	 * DSQ_LOCAL_ON verdicts targeting the local DSQ of a remote CPU, defer
2196 	 * the enqueue so that it's executed when @rq can be unlocked.
2197 	 */
2198 	if (dsq->id == SCX_DSQ_LOCAL && dsq != &rq->scx.local_dsq) {
2199 		unsigned long opss;
2200 
2201 		opss = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_STATE_MASK;
2202 
2203 		switch (opss & SCX_OPSS_STATE_MASK) {
2204 		case SCX_OPSS_NONE:
2205 			break;
2206 		case SCX_OPSS_QUEUEING:
2207 			/*
2208 			 * As @p was never passed to the BPF side, _release is
2209 			 * not strictly necessary. Still do it for consistency.
2210 			 */
2211 			atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
2212 			break;
2213 		default:
2214 			WARN_ONCE(true, "sched_ext: %s[%d] has invalid ops state 0x%lx in direct_dispatch()",
2215 				  p->comm, p->pid, opss);
2216 			atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
2217 			break;
2218 		}
2219 
2220 		WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node));
2221 		list_add_tail(&p->scx.dsq_list.node,
2222 			      &rq->scx.ddsp_deferred_locals);
2223 		schedule_deferred_locked(rq);
2224 		return;
2225 	}
2226 
2227 	ddsp_enq_flags = p->scx.ddsp_enq_flags;
2228 	slice = p->scx.ddsp_slice;
2229 	vtime = p->scx.ddsp_vtime;
2230 	clear_direct_dispatch(p);
2231 
2232 	scx_dispatch_enqueue(sch, rq, dsq, p, slice, vtime,
2233 			     ddsp_enq_flags | SCX_ENQ_APPLY_SLICE | SCX_ENQ_CLEAR_OPSS);
2234 }
2235 
2236 bool scx_rq_online(struct rq *rq)
2237 {
2238 	/*
2239 	 * Test both cpu_active() and %SCX_RQ_ONLINE. %SCX_RQ_ONLINE is set
2240 	 * after the root's ops.cpu_online() and cleared when the cpu goes down.
2241 	 * cpu_active() test guarantees that, if this function returns %true,
2242 	 * %SCX_RQ_ONLINE will stay set until the current scheduling operation
2243 	 * is complete even if we aren't locking @rq.
2244 	 */
2245 	return likely((rq->scx.flags & SCX_RQ_ONLINE) && cpu_active(cpu_of(rq)));
2246 }
2247 
2248 void scx_do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags,
2249 			 int sticky_cpu)
2250 {
2251 	enum {
2252 		ENQ_ACTION_NONE,
2253 		ENQ_ACTION_DIRECT,
2254 		ENQ_ACTION_LOCAL_NOREFILL,
2255 		ENQ_ACTION_ENQUEUE,
2256 	} action = ENQ_ACTION_NONE;
2257 	struct scx_sched *sch = scx_task_sched(p);
2258 	struct task_struct **ddsp_taskp;
2259 	struct scx_dispatch_q *dsq;
2260 	unsigned long qseq;
2261 
2262 	WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_QUEUED));
2263 
2264 	/* internal movements - rq migration / RESTORE */
2265 	if (sticky_cpu == cpu_of(rq))
2266 		goto local_norefill;
2267 
2268 	/*
2269 	 * Clear persistent TASK_IMMED for fresh enqueues, see dsq_inc_nr().
2270 	 * Note that exiting and migration-disabled tasks that skip
2271 	 * ops.enqueue() below will lose IMMED protection unless
2272 	 * %SCX_OPS_ENQ_EXITING / %SCX_OPS_ENQ_MIGRATION_DISABLED are set.
2273 	 */
2274 	p->scx.flags &= ~SCX_TASK_IMMED;
2275 
2276 	/*
2277 	 * If !scx_rq_online(), we already told the BPF scheduler that the CPU
2278 	 * is offline and are just running the hotplug path. Don't bother the
2279 	 * BPF scheduler.
2280 	 */
2281 	if (!scx_rq_online(rq))
2282 		goto local;
2283 
2284 	if (scx_bypassing(sch, cpu_of(rq))) {
2285 		__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
2286 		goto bypass;
2287 	}
2288 
2289 	/*
2290 	 * A task reenqueued too many times without running means the scheduler
2291 	 * keeps re-deciding a placement it can't honor, e.g. re-inserting to a
2292 	 * cid it lacks caps on. Eject the owning scheduler and strand the task
2293 	 * to be picked up during sched exit.
2294 	 *
2295 	 * Bypass guarantees that every runnable task keeps running, and the
2296 	 * disable relies on that to take sleeping locks. The kernel places the
2297 	 * tasks of a bypassing scheduler and those on an offline rq, and
2298 	 * counting their reenqueues could strand a task under bypass and
2299 	 * deadlock the disable on a lock the task holds, so both tests stay
2300 	 * above the count.
2301 	 */
2302 	if (enq_flags & SCX_ENQ_REENQ) {
2303 		if (++p->scx.reenq_cnt > 1)
2304 			__scx_add_event(sch, SCX_EV_REENQ_REPEAT, 1);
2305 
2306 		if (unlikely(p->scx.reenq_cnt > SCX_REENQ_MAX_REPEAT)) {
2307 			__scx_exit(sch, SCX_EXIT_ERROR_REENQ, 0, cpu_of(rq),
2308 				   "%s[%d] reenqueued %u times without running",
2309 				   p->comm, p->pid, p->scx.reenq_cnt);
2310 			goto out;
2311 		}
2312 	}
2313 
2314 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
2315 		goto direct;
2316 
2317 	/*
2318 	 * A full wakeup enqueue happens before is_blocked is cleared. Don't
2319 	 * report it as another blocked-donor admission.
2320 	 */
2321 	if ((sch->ops.flags & SCX_OPS_ENQ_BLOCKED) && p->is_blocked &&
2322 	    !(enq_flags & SCX_ENQ_WAKEUP)) {
2323 		enq_flags |= SCX_ENQ_BLOCKED;
2324 	} else {
2325 		/* see %SCX_OPS_ENQ_EXITING */
2326 		if (unlikely(p->flags & PF_EXITING) &&
2327 		    !(sch->ops.flags & SCX_OPS_ENQ_EXITING)) {
2328 			__scx_add_event(sch, SCX_EV_ENQ_SKIP_EXITING, 1);
2329 			enq_flags |= SCX_ENQ_RESCUE;	/* avoid looping on cap rejection */
2330 			goto local;
2331 		}
2332 
2333 		/* see %SCX_OPS_ENQ_MIGRATION_DISABLED */
2334 		if (!(sch->ops.flags & SCX_OPS_ENQ_MIGRATION_DISABLED) &&
2335 		    is_migration_disabled(p)) {
2336 			__scx_add_event(sch, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED, 1);
2337 			goto local;
2338 		}
2339 	}
2340 
2341 	if (unlikely(!SCX_HAS_OP(sch, enqueue)))
2342 		goto global;
2343 
2344 	/*
2345 	 * DSQ bypass didn't trigger, enqueue on the BPF scheduler. Wrap the
2346 	 * per-task qseq counter where the QSEQ field wraps and skip 0, which is
2347 	 * what scx_bpf_dsq_insert() records for a task in NONE or DISPATCHING.
2348 	 */
2349 	p->scx.ops_qseq = ((p->scx.ops_qseq + 1) &
2350 			   (SCX_OPSS_QSEQ_MASK >> SCX_OPSS_QSEQ_SHIFT)) ?: 1;
2351 	qseq = (unsigned long)p->scx.ops_qseq << SCX_OPSS_QSEQ_SHIFT;
2352 
2353 	WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
2354 	atomic_long_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq);
2355 
2356 	ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
2357 	WARN_ON_ONCE(*ddsp_taskp);
2358 	*ddsp_taskp = p;
2359 
2360 	SCX_CALL_OP_TASK(sch, enqueue, rq, p, enq_flags);
2361 
2362 	*ddsp_taskp = NULL;
2363 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
2364 		goto direct;
2365 
2366 	/*
2367 	 * Task is now in BPF scheduler's custody. Set %SCX_TASK_IN_CUSTODY
2368 	 * so ops.dequeue() is called when it leaves custody.
2369 	 */
2370 	p->scx.flags |= SCX_TASK_IN_CUSTODY;
2371 
2372 	/*
2373 	 * If not directly dispatched, QUEUEING isn't clear yet and dispatch or
2374 	 * dequeue may be waiting. The store_release matches their load_acquire.
2375 	 */
2376 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_QUEUED | qseq);
2377 	goto out;
2378 
2379 direct:
2380 	action = ENQ_ACTION_DIRECT;
2381 	goto out;
2382 local_norefill:
2383 	action = ENQ_ACTION_LOCAL_NOREFILL;
2384 	goto out;
2385 local:
2386 	dsq = &rq->scx.local_dsq;
2387 	goto enqueue;
2388 global:
2389 	dsq = find_global_dsq(sch, task_cpu(p));
2390 	goto enqueue;
2391 bypass:
2392 	dsq = bypass_enq_target_dsq(sch, rq, p, &enq_flags);
2393 	goto enqueue;
2394 
2395 enqueue:
2396 	action = ENQ_ACTION_ENQUEUE;
2397 out:
2398 	/* The reason is input to ops.enqueue(), not to the resulting placement. */
2399 	p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
2400 
2401 	switch (action) {
2402 	case ENQ_ACTION_DIRECT:
2403 		direct_dispatch(sch, p, enq_flags);
2404 		break;
2405 	case ENQ_ACTION_LOCAL_NOREFILL:
2406 		scx_dispatch_enqueue(sch, rq, &rq->scx.local_dsq, p, 0, 0,
2407 				     enq_flags);
2408 		break;
2409 	case ENQ_ACTION_ENQUEUE:
2410 		refill_task_slice_dfl(sch, p);
2411 		clear_direct_dispatch(p);
2412 		scx_dispatch_enqueue(sch, rq, dsq, p, 0, 0, enq_flags);
2413 		break;
2414 	case ENQ_ACTION_NONE:
2415 		break;
2416 	}
2417 }
2418 
2419 static bool task_runnable(const struct task_struct *p)
2420 {
2421 	return !list_empty(&p->scx.runnable_node);
2422 }
2423 
2424 static void set_task_runnable(struct rq *rq, struct task_struct *p)
2425 {
2426 	lockdep_assert_rq_held(rq);
2427 
2428 	if (p->scx.flags & SCX_TASK_RESET_RUNNABLE_AT) {
2429 		p->scx.runnable_at = jiffies;
2430 		p->scx.flags &= ~SCX_TASK_RESET_RUNNABLE_AT;
2431 	}
2432 
2433 	/*
2434 	 * list_add_tail() must be used. scx_bypass() and drain_offline_rq()
2435 	 * depend on tasks being appended to the runnable_list.
2436 	 */
2437 	list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list);
2438 
2439 	/*
2440 	 * Record the rq @p is runnable on, maintained under the rq lock so it
2441 	 * stays valid unlike task_cpu(), which a remote wakeup can move under
2442 	 * pi_lock alone.
2443 	 */
2444 	WRITE_ONCE(p->scx.runnable_cpu, cpu_of(rq));
2445 }
2446 
2447 static void clr_task_runnable(struct task_struct *p, bool reset_runnable_at)
2448 {
2449 	list_del_init(&p->scx.runnable_node);
2450 	WRITE_ONCE(p->scx.runnable_cpu, -1);
2451 	if (reset_runnable_at) {
2452 		p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
2453 		p->scx.reenq_cnt = 0;
2454 	}
2455 }
2456 
2457 static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int core_enq_flags)
2458 {
2459 	struct scx_sched *sch = scx_task_sched(p);
2460 	int sticky_cpu = p->scx.sticky_cpu;
2461 	u64 enq_flags = core_enq_flags | rq->scx.remote_activate_enq_flags;
2462 
2463 	/*
2464 	 * An SCX-internal migration ends on arrival. Clear sticky_cpu so @p can
2465 	 * leave custody when inserted into the destination DSQ.
2466 	 */
2467 	if (sticky_cpu >= 0)
2468 		p->scx.sticky_cpu = -1;
2469 
2470 	/*
2471 	 * SCX_RQ_IN_WAKEUP promises a task_woken_scx() call once this enqueue
2472 	 * returns. Only the core's wakeup path delivers one. The flags stashed
2473 	 * for a remote activation may carry the wakeup bit without it.
2474 	 */
2475 	if (core_enq_flags & ENQUEUE_WAKEUP)
2476 		rq->scx.flags |= SCX_RQ_IN_WAKEUP;
2477 
2478 	/*
2479 	 * Restoring the current scheduling context will be immediately followed
2480 	 * by set_next_task_scx() which expects the task to not be on the BPF
2481 	 * scheduler as tasks can only start running through local DSQs. Force
2482 	 * direct-dispatch into the local DSQ by setting the sticky_cpu. Mark
2483 	 * IGNORE_CAPS to force entry into the local DSQ.
2484 	 */
2485 	if (unlikely(enq_flags & ENQUEUE_RESTORE) &&
2486 	    task_current_donor(rq, p)) {
2487 		sticky_cpu = cpu_of(rq);
2488 		enq_flags |= SCX_ENQ_IGNORE_CAPS;
2489 	}
2490 
2491 	if (p->scx.flags & SCX_TASK_QUEUED) {
2492 		WARN_ON_ONCE(!task_runnable(p));
2493 		goto out;
2494 	}
2495 
2496 	set_task_runnable(rq, p);
2497 	p->scx.flags |= SCX_TASK_QUEUED;
2498 	rq->scx.nr_running++;
2499 	add_nr_running(rq, 1);
2500 
2501 	if (SCX_HAS_OP(sch, runnable) && !task_on_rq_migrating(p))
2502 		SCX_CALL_OP_TASK(sch, runnable, rq, p, enq_flags);
2503 
2504 	/* Start dl_server if this is the first task being enqueued */
2505 	if (rq->scx.nr_running == 1)
2506 		dl_server_start(&rq->ext_server);
2507 
2508 	scx_do_enqueue_task(rq, p, enq_flags, sticky_cpu);
2509 out:
2510 	rq->scx.flags &= ~SCX_RQ_IN_WAKEUP;
2511 
2512 	if ((enq_flags & SCX_ENQ_CPU_SELECTED) &&
2513 	    unlikely(cpu_of(rq) != p->scx.selected_cpu))
2514 		__scx_add_event(sch, SCX_EV_SELECT_CPU_FALLBACK, 1);
2515 }
2516 
2517 static void ops_dequeue(struct rq *rq, struct task_struct *p, u64 deq_flags)
2518 {
2519 	struct scx_sched *sch = scx_task_sched(p);
2520 	unsigned long opss;
2521 
2522 	/*
2523 	 * Don't reset runnable_at. If @p is waiting, the wait continues across
2524 	 * temporary dequeues, e.g. for a migration or an attribute change.
2525 	 * scx_reset_task_fields() ends it if @p leaves its sched's control.
2526 	 * scx_bypass() restarts it when its requeue can change the sched
2527 	 * running @p.
2528 	 */
2529 	clr_task_runnable(p, false);
2530 
2531 retry:
2532 	/* acquire ensures that we see the preceding updates on QUEUED */
2533 	opss = atomic_long_read_acquire(&p->scx.ops_state);
2534 
2535 	switch (opss & SCX_OPSS_STATE_MASK) {
2536 	case SCX_OPSS_NONE:
2537 		break;
2538 	case SCX_OPSS_QUEUEING:
2539 		/*
2540 		 * QUEUEING is started and finished while holding @p's rq lock.
2541 		 * As we're holding the rq lock now, we shouldn't see QUEUEING.
2542 		 */
2543 		BUG();
2544 	case SCX_OPSS_QUEUED:
2545 		/*
2546 		 * A queued task must always be in BPF scheduler's custody. If
2547 		 * SCX_TASK_IN_CUSTODY is clear, finish_dispatch() on another
2548 		 * CPU has already passed task_leave_custody() (which clears the
2549 		 * flag), but has not yet written SCX_OPSS_NONE. That final
2550 		 * store does not require this rq's lock, so retrying with
2551 		 * cpu_relax() is bounded: we will observe NONE (or DISPATCHING,
2552 		 * handled by the fallthrough) on a subsequent iteration.
2553 		 */
2554 		if (unlikely(!(READ_ONCE(p->scx.flags) & SCX_TASK_IN_CUSTODY))) {
2555 			cpu_relax();
2556 			goto retry;
2557 		}
2558 
2559 		if (atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
2560 					    SCX_OPSS_NONE))
2561 			break;
2562 		fallthrough;
2563 	case SCX_OPSS_DISPATCHING:
2564 		/*
2565 		 * If @p is being dispatched from the BPF scheduler to a DSQ,
2566 		 * wait for the transfer to complete so that @p doesn't get
2567 		 * added to its DSQ after dequeueing is complete.
2568 		 *
2569 		 * As we're waiting on DISPATCHING with the rq locked, the
2570 		 * dispatching side shouldn't try to lock the rq while
2571 		 * DISPATCHING is set. See dispatch_to_local_dsq().
2572 		 *
2573 		 * DISPATCHING shouldn't have qseq set and control can reach
2574 		 * here with NONE @opss from the above QUEUED case block.
2575 		 * Explicitly wait on %SCX_OPSS_DISPATCHING instead of @opss.
2576 		 */
2577 		wait_ops_state(p, SCX_OPSS_DISPATCHING);
2578 		BUG_ON(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
2579 		break;
2580 	}
2581 
2582 	/*
2583 	 * Call ops.dequeue() if the task is still in BPF custody.
2584 	 *
2585 	 * The code that clears ops_state to %SCX_OPSS_NONE does not always
2586 	 * clear %SCX_TASK_IN_CUSTODY: in dispatch_to_local_dsq(), when
2587 	 * we're moving a task that was in %SCX_OPSS_DISPATCHING to a
2588 	 * remote CPU's local DSQ, we only set ops_state to %SCX_OPSS_NONE
2589 	 * so that a concurrent dequeue can proceed, but we clear
2590 	 * %SCX_TASK_IN_CUSTODY only when we later enqueue or move the
2591 	 * task. So we can see NONE + IN_CUSTODY here and we must handle
2592 	 * it. Similarly, after waiting on %SCX_OPSS_DISPATCHING we see
2593 	 * NONE but the task may still have %SCX_TASK_IN_CUSTODY set until
2594 	 * it is enqueued on the destination.
2595 	 */
2596 	if (task_leave_custody(p) && SCX_HAS_OP(sch, dequeue))
2597 		SCX_CALL_OP_TASK(sch, dequeue, rq, p, deq_flags);
2598 }
2599 
2600 static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int core_deq_flags)
2601 {
2602 	struct scx_sched *sch = scx_task_sched(p);
2603 	u64 deq_flags = core_deq_flags;
2604 
2605 	/*
2606 	 * Set %SCX_DEQ_SCHED_CHANGE when the dequeue is due to a property
2607 	 * change (not sleep).
2608 	 */
2609 	if (!(deq_flags & DEQUEUE_SLEEP))
2610 		deq_flags |= SCX_DEQ_SCHED_CHANGE;
2611 
2612 	if (!(p->scx.flags & SCX_TASK_QUEUED)) {
2613 		WARN_ON_ONCE(task_runnable(p));
2614 		return true;
2615 	}
2616 
2617 	ops_dequeue(rq, p, deq_flags);
2618 
2619 	/*
2620 	 * A current scheduling context which is going off @rq first gets
2621 	 * dequeued and then stops running. As we want running <-> stopping
2622 	 * transitions to be contained within runnable <-> quiescent transitions,
2623 	 * trigger ->stopping() early here instead of in put_prev_task_scx().
2624 	 *
2625 	 * @p may go through multiple stopping <-> running transitions between
2626 	 * here and put_prev_task_scx() if task attribute changes occur while
2627 	 * dispatch_one() leaves @rq unlocked. However, they don't contain any
2628 	 * information meaningful to the BPF scheduler and can be suppressed by
2629 	 * skipping the callbacks if the task is !QUEUED.
2630 	 */
2631 	if (task_current_donor(rq, p) && (p->scx.flags & SCX_TASK_RUN_TRACKED)) {
2632 		if (SCX_HAS_OP(sch, stopping) || unlikely(p == scx_rescuee(rq))) {
2633 			update_curr_scx(rq);
2634 			if (SCX_HAS_OP(sch, stopping))
2635 				SCX_CALL_OP_TASK(sch, stopping, rq, p, false);
2636 		}
2637 		p->scx.flags &= ~SCX_TASK_RUN_TRACKED;
2638 	}
2639 
2640 	if (SCX_HAS_OP(sch, quiescent) && !task_on_rq_migrating(p))
2641 		SCX_CALL_OP_TASK(sch, quiescent, rq, p, deq_flags);
2642 
2643 	if (deq_flags & SCX_DEQ_SLEEP)
2644 		p->scx.flags |= SCX_TASK_DEQD_FOR_SLEEP;
2645 	else
2646 		p->scx.flags &= ~SCX_TASK_DEQD_FOR_SLEEP;
2647 
2648 	p->scx.flags &= ~SCX_TASK_QUEUED;
2649 	rq->scx.nr_running--;
2650 	sub_nr_running(rq, 1);
2651 
2652 	scx_dispatch_dequeue(rq, p);
2653 	p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
2654 
2655 	/* see scx_task_slice_ended() for the save/restore exception */
2656 	if (!((deq_flags & DEQUEUE_SAVE) && task_current_donor(rq, p)))
2657 		scx_task_slice_ended(rq, p);
2658 
2659 	clear_direct_dispatch(p);
2660 	return true;
2661 }
2662 
2663 static void yield_task_scx(struct rq *rq)
2664 {
2665 	struct task_struct *p = rq->donor;
2666 	struct scx_sched *sch = scx_task_sched(p);
2667 
2668 	/* a yield gives the slice up */
2669 	scx_task_slice_ended(rq, p);
2670 
2671 	if (SCX_HAS_OP(sch, yield))
2672 		SCX_CALL_OP_2TASKS_RET(sch, yield, rq, p, NULL);
2673 	else
2674 		scx_set_task_slice(p, 0);
2675 }
2676 
2677 static bool yield_to_task_scx(struct rq *rq, struct task_struct *to)
2678 {
2679 	struct task_struct *from = rq->donor;
2680 	struct scx_sched *sch = scx_task_sched(from);
2681 
2682 	/* like a plain yield, giving the slice up ends the protection */
2683 	scx_task_slice_ended(rq, from);
2684 
2685 	if (SCX_HAS_OP(sch, yield) && sch == scx_task_sched(to))
2686 		return SCX_CALL_OP_2TASKS_RET(sch, yield, rq, from, to);
2687 	else
2688 		return false;
2689 }
2690 
2691 static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p, int wake_flags)
2692 {
2693 	/*
2694 	 * Preemption between SCX tasks is implemented by resetting the victim
2695 	 * task's slice to 0 and triggering reschedule on the target CPU.
2696 	 *
2697 	 * A retained proxy donor can wake through ttwu_runnable() without another
2698 	 * ops.enqueue(). WF_TTWU_RQ identifies this path. Request rescheduling so
2699 	 * that ops.dispatch() can reconsider the task after ttwu_runnable() clears
2700 	 * is_blocked. A full wakeup activation has already enqueued the task and
2701 	 * doesn't need the additional reschedule.
2702 	 */
2703 	if (p->sched_class == &ext_sched_class) {
2704 		if (sched_proxy_exec() && (wake_flags & WF_TTWU_RQ) &&
2705 		    p->is_blocked) {
2706 			struct scx_sched *sch = scx_task_sched(p);
2707 
2708 			if (sch && (sch->ops.flags & SCX_OPS_ENQ_BLOCKED))
2709 				resched_curr(rq);
2710 		}
2711 		return;
2712 	}
2713 
2714 	/*
2715 	 * Getting preempted by a higher-priority class. Reenqueue IMMED tasks.
2716 	 * This captures all preemption cases including:
2717 	 *
2718 	 * - A SCX task is currently running.
2719 	 *
2720 	 * - @rq is waking from idle due to a SCX task waking to it.
2721 	 *
2722 	 * - A higher-priority wakes up while SCX dispatch is in progress.
2723 	 */
2724 	if (rq->scx.nr_immed)
2725 		scx_schedule_reenq_local(rq, 0);
2726 }
2727 
2728 void scx_move_local_task_to_local_dsq(struct scx_sched *sch, struct task_struct *p,
2729 				      u64 enq_flags, struct rq *dst_rq)
2730 {
2731 	struct scx_dispatch_q *dst_dsq;
2732 
2733 	lockdep_assert_rq_held(dst_rq);
2734 
2735 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
2736 	scx_wait_dispatching(p);
2737 
2738 	dst_dsq = scx_resolve_local_dsq(sch, dst_rq, p, &enq_flags);
2739 
2740 	if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY))
2741 		dsq_insert_head(dst_dsq, p);
2742 	else
2743 		list_add_tail(&p->scx.dsq_list.node, &dst_dsq->list);
2744 
2745 	dsq_inc_nr(dst_dsq, p, enq_flags);
2746 	p->scx.dsq = dst_dsq;
2747 
2748 	rq_owned_post_enq(sch, dst_rq, dst_dsq, p, enq_flags);
2749 }
2750 
2751 /**
2752  * move_remote_task_to_local_dsq - Move a task from a foreign rq to a local DSQ
2753  * @sch: scheduler placing @p
2754  * @p: task to move
2755  * @enq_flags: %SCX_ENQ_*
2756  * @src_rq: rq to move the task from, locked on entry, released on return
2757  * @dst_rq: rq to move the task into, locked on return
2758  *
2759  * Move @p which is currently on @src_rq to @dst_rq's local DSQ.
2760  */
2761 static void move_remote_task_to_local_dsq(struct scx_sched *sch,
2762 					  struct task_struct *p, u64 enq_flags,
2763 					  struct rq *src_rq, struct rq *dst_rq)
2764 {
2765 	lockdep_assert_rq_held(src_rq);
2766 
2767 	/*
2768 	 * Set sticky_cpu before deactivate_task() to properly mark the
2769 	 * beginning of an SCX-internal migration.
2770 	 */
2771 	p->scx.sticky_cpu = cpu_of(dst_rq);
2772 	deactivate_task(src_rq, p, 0);
2773 	set_task_cpu(p, cpu_of(dst_rq));
2774 
2775 	switch_rq_lock(src_rq, dst_rq);
2776 
2777 	/*
2778 	 * activate_task() below truncates enq_flags to 32 bits and re-derives
2779 	 * @p's owner, dropping our scx flags and the placing @sch. We own @rq,
2780 	 * so stash both across the call. The enqueue reads them back, keeping
2781 	 * the scx flags and checking caps against the placer, not the owner.
2782 	 */
2783 	WARN_ON_ONCE(!cpumask_test_cpu(cpu_of(dst_rq), p->cpus_ptr));
2784 	WARN_ON_ONCE(dst_rq->scx.remote_activate_enq_flags ||
2785 		     dst_rq->scx.remote_activate_sch);
2786 	dst_rq->scx.remote_activate_enq_flags = enq_flags;
2787 	dst_rq->scx.remote_activate_sch = sch;
2788 	activate_task(dst_rq, p, 0);
2789 	dst_rq->scx.remote_activate_enq_flags = 0;
2790 	dst_rq->scx.remote_activate_sch = NULL;
2791 }
2792 
2793 /*
2794  * Similar to kernel/sched/core.c::is_cpu_allowed(). However, there are two
2795  * differences:
2796  *
2797  * - is_cpu_allowed() asks "Can this task run on this CPU?" while
2798  *   task_can_run_on_remote_rq() asks "Can the BPF scheduler migrate the task to
2799  *   this CPU?".
2800  *
2801  *   While migration is disabled, is_cpu_allowed() has to say "yes" as the task
2802  *   must be allowed to finish on the CPU that it's currently on regardless of
2803  *   the CPU state. However, task_can_run_on_remote_rq() must say "no" as the
2804  *   BPF scheduler shouldn't attempt to migrate a task which has migration
2805  *   disabled.
2806  *
2807  * - The BPF scheduler is bypassed while the rq is offline and we can always say
2808  *   no to the BPF scheduler initiated migrations while offline.
2809  *
2810  * The caller must ensure that @p and @rq are on different CPUs. If @enforce is
2811  * true, report violations attributable to BPF-directed migrations. The caller
2812  * must hold @p's rq lock to avoid reporting a transient race as a scheduler
2813  * error.
2814  */
2815 static bool task_can_run_on_remote_rq(struct scx_sched *sch,
2816 				      struct task_struct *p, struct rq *rq,
2817 				      bool enforce)
2818 {
2819 	s32 cpu = cpu_of(rq);
2820 
2821 	if (enforce)
2822 		lockdep_assert_rq_held(task_rq(p));
2823 
2824 	WARN_ON_ONCE(task_cpu(p) == cpu);
2825 
2826 	/*
2827 	 * proxy_set_task_cpu() preserves wake_cpu when moving a donor's scheduling
2828 	 * context to its lock owner's rq. For example, if BPF places donor D on
2829 	 * CPU0 while its lock owner runs on CPU1, proxy execution moves D to CPU1
2830 	 * but leaves D->wake_cpu pointing to CPU0. If D is later put on a shared
2831 	 * DSQ, CPU0 could otherwise consume it and move it back, only for proxy
2832 	 * execution to return it to CPU1 again.
2833 	 *
2834 	 * When task_cpu() == wake_cpu, the donor has not been proxy-migrated and
2835 	 * BPF may still choose its placement. An actively donating task is
2836 	 * rejected separately by task_proxy_running_or_donating().
2837 	 */
2838 	if (sched_proxy_exec() && p->is_blocked && task_cpu(p) != p->wake_cpu)
2839 		return false;
2840 
2841 	/*
2842 	 * If @p has migration disabled, @p->cpus_ptr is updated to contain only
2843 	 * the pinned CPU in migrate_disable_switch() while @p is being switched
2844 	 * out. However, put_prev_task_scx() is called before @p->cpus_ptr is
2845 	 * updated and thus another CPU may see @p on a DSQ inbetween leading to
2846 	 * @p passing the below task_allowed_on_cpu() check while migration is
2847 	 * disabled.
2848 	 *
2849 	 * Test the migration disabled state first as the race window is narrow
2850 	 * and the BPF scheduler failing to check migration disabled state can
2851 	 * easily be masked if task_allowed_on_cpu() is done first.
2852 	 */
2853 	if (unlikely(is_migration_disabled(p))) {
2854 		if (enforce)
2855 			scx_error(sch, "SCX_DSQ_LOCAL[_ON] cannot move migration disabled %s[%d] from CPU %d to %d",
2856 				  p->comm, p->pid, task_cpu(p), cpu);
2857 		return false;
2858 	}
2859 
2860 	/*
2861 	 * We don't require the BPF scheduler to avoid dispatching to offline
2862 	 * CPUs mostly for convenience but also because CPUs can go offline
2863 	 * between scx_bpf_dsq_insert() calls and here. Trigger error iff the
2864 	 * picked CPU is outside the allowed mask.
2865 	 */
2866 	if (!task_allowed_on_cpu(p, cpu)) {
2867 		if (enforce)
2868 			scx_error(sch, "SCX_DSQ_LOCAL[_ON] target CPU %d not allowed for %s[%d]",
2869 				  cpu, p->comm, p->pid);
2870 		return false;
2871 	}
2872 
2873 	if (!scx_rq_online(rq)) {
2874 		if (enforce)
2875 			__scx_add_event(sch, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE, 1);
2876 		return false;
2877 	}
2878 
2879 	return true;
2880 }
2881 
2882 /*
2883  * Proxy execution can change @p's execution and migration-disabled state
2884  * without touching its DSQ entry or clearing holding_cpu. Check those states
2885  * with @p's rq locked. Without proxy execution, the holding_cpu handshake is
2886  * sufficient and this must not affect the existing migration path.
2887  *
2888  * A BPF-directed transfer to a remote local DSQ performs a normal task
2889  * migration and thus cannot move a migration-disabled task. In contrast,
2890  * proxy_migrate_task() moves only a blocked donor's scheduling context towards
2891  * the mutex owner and preserves its execution home in wake_cpu. The latter is
2892  * therefore allowed even when the donor is migration-disabled.
2893  */
2894 static bool task_proxy_running_or_donating(struct task_struct *p)
2895 {
2896 	struct rq *src_rq = task_rq(p);
2897 
2898 	lockdep_assert_rq_held(src_rq);
2899 
2900 	if (!sched_proxy_exec())
2901 		return false;
2902 
2903 	/* @p may be rq->curr under another task's scheduling context. */
2904 	if (task_on_cpu(src_rq, p))
2905 		return true;
2906 
2907 	/* Don't move an active scheduling context off its source rq. */
2908 	if (task_current_donor(src_rq, p))
2909 		return true;
2910 
2911 	return false;
2912 }
2913 
2914 static bool task_proxy_unsafe_to_move(struct task_struct *p)
2915 {
2916 	if (!sched_proxy_exec())
2917 		return false;
2918 
2919 	return task_proxy_running_or_donating(p) || is_migration_disabled(p);
2920 }
2921 
2922 /*
2923  * Park a task whose remote transfer raced with proxy execution. Reenqueueing
2924  * from the source rq makes the task's owning scheduler choose its placement
2925  * again and preserves sub-scheduler containment.
2926  */
2927 static void scx_proxy_reject_task(struct scx_sched *sch, struct rq *rq,
2928 				  struct task_struct *p, u64 enq_flags)
2929 {
2930 	lockdep_assert_rq_held(rq);
2931 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK);
2932 
2933 	p->scx.flags |= SCX_TASK_REENQ_PROXY;
2934 	scx_divert_strip_flags(p, &enq_flags);
2935 
2936 	scx_dispatch_enqueue(sch, rq, &rq->scx.reject_dsq, p, 0, 0, enq_flags);
2937 }
2938 
2939 /**
2940  * unlink_dsq_and_switch_rq_lock() - Unlink task and switch to its rq lock
2941  * @p: target task
2942  * @dsq: locked DSQ @p is currently on
2943  * @locked_rq: currently locked rq
2944  * @src_rq: rq @p is currently on, stable with @dsq locked
2945  *
2946  * Called with @dsq and @locked_rq locked. We want to move @p to a different DSQ,
2947  * including any local DSQ, but are not locking @src_rq. Locking @src_rq is
2948  * required when transferring into a local DSQ. Even when transferring into a
2949  * non-local DSQ, it's better to use the same mechanism to protect against
2950  * dequeues and maintain the invariant that @p->scx.dsq can only change while
2951  * @src_rq is locked, which e.g. scx_dump_task() depends on.
2952  *
2953  * We want to grab @src_rq but that can deadlock if we try while locking @dsq,
2954  * so we want to unlink @p from @dsq, drop its lock and then lock @src_rq. As
2955  * this may race with dequeue, which can't drop the rq lock or fail, do a little
2956  * dancing from our side.
2957  *
2958  * @p->scx.holding_cpu is set to this CPU before @dsq is unlocked. If @p gets
2959  * dequeued after we unlock @dsq but before locking @src_rq, the holding_cpu
2960  * would be cleared to -1. While other cpus may have updated it to different
2961  * values afterwards, as this operation can't be preempted or recurse, the
2962  * holding_cpu can never become this CPU again before we're done. Thus, we can
2963  * tell whether we lost to dequeue by testing whether the holding_cpu still
2964  * points to this CPU. See scx_dispatch_dequeue() for the counterpart.
2965  *
2966  * On return, @dsq is unlocked and @src_rq is locked. Return %true if @p is
2967  * still valid and detached from @dsq, with holding_cpu cleared. Return %false
2968  * if @p was lost to a dequeue.
2969  */
2970 static bool unlink_dsq_and_switch_rq_lock(struct task_struct *p,
2971 					  struct scx_dispatch_q *dsq,
2972 					  struct rq *locked_rq,
2973 					  struct rq *src_rq)
2974 {
2975 	s32 cpu = raw_smp_processor_id();
2976 
2977 	lockdep_assert_held(&dsq->lock);
2978 	lockdep_assert_rq_held(locked_rq);
2979 
2980 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
2981 	scx_task_unlink_from_dsq(p, dsq);
2982 	p->scx.holding_cpu = cpu;
2983 
2984 	raw_spin_unlock(&dsq->lock);
2985 	switch_rq_lock(locked_rq, src_rq);
2986 
2987 	/* task_rq couldn't have changed if we're still the holding cpu */
2988 	if (likely(p->scx.holding_cpu == cpu) && !WARN_ON_ONCE(src_rq != task_rq(p))) {
2989 		/*
2990 		 * Keep ->dsq set until we own @src_rq so that a racing dequeue
2991 		 * can find @dsq and clear holding_cpu. Once we own @src_rq, the
2992 		 * handshake is over. Clear ->dsq so that deactivate_task()
2993 		 * takes the !dsq path instead of retaking @dsq->lock. Clear
2994 		 * holding_cpu with it so that no caller has to.
2995 		 */
2996 		p->scx.dsq = NULL;
2997 		p->scx.holding_cpu = -1;
2998 		scx_wait_dispatching(p);
2999 		return true;
3000 	}
3001 
3002 	return false;
3003 }
3004 
3005 static bool consume_remote_task(struct scx_sched *sch, struct rq *this_rq,
3006 				struct task_struct *p, u64 enq_flags,
3007 				struct scx_dispatch_q *dsq, struct rq *src_rq)
3008 {
3009 	if (unlink_dsq_and_switch_rq_lock(p, dsq, this_rq, src_rq)) {
3010 		/*
3011 		 * Proxy execution may have changed @p's running or
3012 		 * migration-disabled state while switching rq locks without
3013 		 * clearing holding_cpu. Park it on the source rq and let its
3014 		 * owning scheduler choose its placement again.
3015 		 */
3016 		if (unlikely(task_proxy_unsafe_to_move(p))) {
3017 			p->scx.dsq = NULL;
3018 			scx_proxy_reject_task(sch, src_rq, p, enq_flags | SCX_ENQ_CLEAR_OPSS);
3019 			switch_rq_lock(src_rq, this_rq);
3020 			return false;
3021 		}
3022 
3023 		move_remote_task_to_local_dsq(sch, p, enq_flags, src_rq, this_rq);
3024 		return true;
3025 	} else {
3026 		switch_rq_lock(src_rq, this_rq);
3027 		return false;
3028 	}
3029 }
3030 
3031 /**
3032  * move_task_between_dsqs() - Move a task from one DSQ to another
3033  * @sch: scx_sched being operated on
3034  * @p: target task
3035  * @enq_flags: %SCX_ENQ_*
3036  * @src_dsq: DSQ @p is currently on, must not be a local DSQ
3037  * @dst_dsq: DSQ @p is being moved to, can be any DSQ
3038  *
3039  * Must be called with @p's task_rq and @src_dsq locked. If @dst_dsq is a local
3040  * DSQ and @p is on a different CPU, @p will be migrated and thus its task_rq
3041  * will change. As @p's task_rq is locked, this function doesn't need to use the
3042  * holding_cpu mechanism.
3043  *
3044  * On return, @src_dsq is unlocked and only @p's new task_rq, which is the
3045  * return value, is locked.
3046  */
3047 static struct rq *move_task_between_dsqs(struct scx_sched *sch,
3048 					 struct task_struct *p, u64 enq_flags,
3049 					 struct scx_dispatch_q *src_dsq,
3050 					 struct scx_dispatch_q *dst_dsq)
3051 {
3052 	struct rq *src_rq = task_rq(p), *dst_rq;
3053 
3054 	BUG_ON(src_dsq->id == SCX_DSQ_LOCAL);
3055 	lockdep_assert_held(&src_dsq->lock);
3056 	lockdep_assert_rq_held(src_rq);
3057 
3058 	scx_wait_dispatching(p);
3059 
3060 	if (dst_dsq->id == SCX_DSQ_LOCAL) {
3061 		dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
3062 		/*
3063 		 * Unlike the rq-lock handoff paths, @src_rq has been locked
3064 		 * throughout this operation. Only active proxy state can race the
3065 		 * move here; let the enforcing check below diagnose an ordinary
3066 		 * migration-disabled task.
3067 		 */
3068 		if (src_rq != dst_rq &&
3069 		    unlikely(task_proxy_running_or_donating(p))) {
3070 			dispatch_dequeue_locked(p, src_dsq);
3071 			raw_spin_unlock(&src_dsq->lock);
3072 			scx_proxy_reject_task(sch, src_rq, p, enq_flags);
3073 			return src_rq;
3074 		}
3075 		if (src_rq != dst_rq &&
3076 		    unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) {
3077 			dst_dsq = find_global_dsq(sch, task_cpu(p));
3078 			dst_rq = src_rq;
3079 			enq_flags |= SCX_ENQ_GDSQ_FALLBACK;
3080 		}
3081 	} else {
3082 		/* no need to migrate if destination is a non-local DSQ */
3083 		dst_rq = src_rq;
3084 	}
3085 
3086 	/*
3087 	 * Move @p into $dst_dsq. If $dst_dsq is the local DSQ of a different
3088 	 * CPU, @p will be migrated.
3089 	 */
3090 	if (dst_dsq->id == SCX_DSQ_LOCAL) {
3091 		/* @p is going from a non-local DSQ to a local DSQ */
3092 		if (src_rq == dst_rq) {
3093 			scx_task_unlink_from_dsq(p, src_dsq);
3094 			raw_spin_unlock(&src_dsq->lock);
3095 			scx_move_local_task_to_local_dsq(sch, p, enq_flags, dst_rq);
3096 		} else {
3097 			dispatch_dequeue_locked(p, src_dsq);
3098 			raw_spin_unlock(&src_dsq->lock);
3099 			move_remote_task_to_local_dsq(sch, p, enq_flags, src_rq, dst_rq);
3100 		}
3101 	} else {
3102 		/*
3103 		 * @p is going from a non-local DSQ to a non-local DSQ. As
3104 		 * $src_dsq is already locked, do an abbreviated dequeue.
3105 		 */
3106 		dispatch_dequeue_locked(p, src_dsq);
3107 		raw_spin_unlock(&src_dsq->lock);
3108 
3109 		scx_dispatch_enqueue(sch, dst_rq, dst_dsq, p, 0, 0, enq_flags);
3110 	}
3111 
3112 	return dst_rq;
3113 }
3114 
3115 bool scx_consume_dispatch_q(struct scx_sched *sch, struct rq *rq,
3116 			    struct scx_dispatch_q *dsq, u64 enq_flags)
3117 {
3118 	struct task_struct *p;
3119 retry:
3120 	/*
3121 	 * The caller can't expect to successfully consume a task if the task's
3122 	 * addition to @dsq isn't guaranteed to be visible somehow. Test
3123 	 * @dsq->list without locking and skip if it seems empty.
3124 	 */
3125 	if (list_empty(&dsq->list))
3126 		return false;
3127 
3128 	raw_spin_lock(&dsq->lock);
3129 
3130 	nldsq_for_each_task(p, dsq) {
3131 		struct rq *task_rq = task_rq(p);
3132 
3133 		/*
3134 		 * This loop can lead to multiple lockup scenarios, e.g. the BPF
3135 		 * scheduler can put an enormous number of affinitized tasks into
3136 		 * a contended DSQ, or the outer retry loop can repeatedly race
3137 		 * against scx_bypass() dequeueing tasks from @dsq trying to put
3138 		 * the system into the bypass mode. This can easily live-lock the
3139 		 * machine. If aborting, exit from all non-bypass DSQs.
3140 		 */
3141 		if (unlikely(READ_ONCE(sch->aborting)) && dsq->id != SCX_DSQ_BYPASS)
3142 			break;
3143 
3144 		if (rq == task_rq) {
3145 			scx_task_unlink_from_dsq(p, dsq);
3146 			raw_spin_unlock(&dsq->lock);
3147 			scx_move_local_task_to_local_dsq(sch, p, enq_flags, rq);
3148 			return true;
3149 		}
3150 
3151 		if (task_can_run_on_remote_rq(sch, p, rq, false)) {
3152 			if (likely(consume_remote_task(sch, rq, p, enq_flags, dsq, task_rq)))
3153 				return true;
3154 			goto retry;
3155 		}
3156 	}
3157 
3158 	raw_spin_unlock(&dsq->lock);
3159 	return false;
3160 }
3161 
3162 bool scx_consume_global_dsq(struct scx_sched *sch, struct rq *rq)
3163 {
3164 	int node = cpu_to_node(cpu_of(rq));
3165 
3166 	return scx_consume_dispatch_q(sch, rq, &sch->pnode[node]->global_dsq, 0);
3167 }
3168 
3169 /**
3170  * dispatch_to_local_dsq - Dispatch a task to a local dsq
3171  * @sch: scx_sched being operated on
3172  * @rq: current rq which is locked
3173  * @dst_dsq: destination DSQ
3174  * @p: task to dispatch
3175  * @slice: slice carried by the insert verdict, 0 keeps the current value
3176  * @vtime: vtime carried by the insert verdict, committed on PRIQ inserts
3177  * @enq_flags: %SCX_ENQ_*
3178  *
3179  * We're holding @rq lock and want to dispatch @p to @dst_dsq which is a local
3180  * DSQ. This function performs all the synchronization dancing needed because
3181  * local DSQs are protected with rq locks.
3182  *
3183  * The caller must have exclusive ownership of @p (e.g. through
3184  * %SCX_OPSS_DISPATCHING).
3185  */
3186 static void dispatch_to_local_dsq(struct scx_sched *sch, struct rq *rq,
3187 				  struct scx_dispatch_q *dst_dsq, struct task_struct *p,
3188 				  u64 slice, u64 vtime, u64 enq_flags)
3189 {
3190 	struct rq *src_rq = task_rq(p);
3191 	struct rq *dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
3192 	struct rq *locked_rq = rq;
3193 
3194 	/*
3195 	 * We're synchronized against dequeue through DISPATCHING. As @p can't
3196 	 * be dequeued, its task_rq and cpus_allowed are stable too.
3197 	 *
3198 	 * If dispatching to @rq that @p is already on, no lock dancing needed.
3199 	 */
3200 	if (rq == src_rq && rq == dst_rq) {
3201 		scx_dispatch_enqueue(sch, rq, dst_dsq, p, slice, vtime,
3202 				     enq_flags | SCX_ENQ_APPLY_SLICE | SCX_ENQ_CLEAR_OPSS);
3203 		return;
3204 	}
3205 
3206 	/*
3207 	 * @p is on a possibly remote @src_rq which we need to lock to move the
3208 	 * task. If dequeue is in progress, it'd be locking @src_rq and waiting
3209 	 * on DISPATCHING, so we can't grab @src_rq lock while holding
3210 	 * DISPATCHING.
3211 	 *
3212 	 * As DISPATCHING guarantees that @p is wholly ours, we can pretend that
3213 	 * we're moving from a DSQ and use the same mechanism - mark the task
3214 	 * under transfer with holding_cpu, release DISPATCHING and then follow
3215 	 * the same protocol. See unlink_dsq_and_switch_rq_lock().
3216 	 */
3217 	p->scx.holding_cpu = raw_smp_processor_id();
3218 
3219 	/* store_release ensures that dequeue sees the above */
3220 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
3221 
3222 	/* switch to @src_rq lock */
3223 	if (locked_rq != src_rq) {
3224 		switch_rq_lock(locked_rq, src_rq);
3225 		locked_rq = src_rq;
3226 	}
3227 
3228 	/* task_rq couldn't have changed if we're still the holding cpu */
3229 	if (likely(p->scx.holding_cpu == raw_smp_processor_id()) &&
3230 	    !WARN_ON_ONCE(src_rq != task_rq(p))) {
3231 		bool fallback = false;
3232 
3233 		/* the handshake is over, see unlink_dsq_and_switch_rq_lock() */
3234 		p->scx.holding_cpu = -1;
3235 
3236 		/*
3237 		 * If @p is staying on the same rq, there's no need to go
3238 		 * through the full deactivate/activate cycle. Optimize by
3239 		 * abbreviating move_remote_task_to_local_dsq().
3240 		 */
3241 		if (src_rq == dst_rq) {
3242 			scx_dispatch_enqueue(sch, dst_rq, &dst_rq->scx.local_dsq, p,
3243 					     slice, vtime, enq_flags | SCX_ENQ_APPLY_SLICE);
3244 		} else if (unlikely(task_proxy_unsafe_to_move(p))) {
3245 			fallback = true;
3246 			scx_proxy_reject_task(sch, src_rq, p, enq_flags);
3247 		} else if (unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) {
3248 			fallback = true;
3249 			scx_dispatch_enqueue(sch, src_rq, find_global_dsq(sch, task_cpu(p)),
3250 					     p, slice, vtime,
3251 					     enq_flags | SCX_ENQ_APPLY_SLICE |
3252 					     SCX_ENQ_GDSQ_FALLBACK);
3253 		} else {
3254 			apply_slice_vtime(p, slice, vtime, enq_flags);
3255 			move_remote_task_to_local_dsq(sch, p, enq_flags, src_rq, dst_rq);
3256 			/* task has been moved to dst_rq, which is now locked */
3257 			locked_rq = dst_rq;
3258 		}
3259 
3260 		/* if the destination CPU is idle, wake it up */
3261 		if (!fallback && sched_class_above(p->sched_class,
3262 						      dst_rq->donor->sched_class))
3263 			resched_curr(dst_rq);
3264 	}
3265 
3266 	/* switch back to @rq lock */
3267 	if (locked_rq != rq)
3268 		switch_rq_lock(locked_rq, rq);
3269 }
3270 
3271 /**
3272  * finish_dispatch - Asynchronously finish dispatching a task
3273  * @sch: the scheduler
3274  * @rq: current rq which is locked
3275  * @p: task to finish dispatching
3276  * @qseq_at_dispatch: qseq when @p started getting dispatched
3277  * @dsq_id: destination DSQ ID
3278  * @slice: slice carried by the insert verdict, 0 keeps the current value
3279  * @vtime: vtime carried by the insert verdict, committed on PRIQ inserts
3280  * @enq_flags: %SCX_ENQ_*
3281  *
3282  * Dispatching to local DSQs may need to wait for queueing to complete or
3283  * require rq lock dancing. As we don't wanna do either while inside
3284  * ops.dispatch() to avoid locking order inversion, we split dispatching into
3285  * two parts. scx_bpf_dsq_insert() which is called by ops.dispatch() records the
3286  * task and its qseq. Once ops.dispatch() returns, this function is called to
3287  * finish up.
3288  *
3289  * There is no guarantee that @p is still valid for dispatching or even that it
3290  * was valid in the first place. Make sure that the task is still owned by the
3291  * BPF scheduler and claim the ownership before dispatching.
3292  */
3293 static void finish_dispatch(struct scx_sched *sch, struct rq *rq, struct task_struct *p,
3294 			    unsigned long qseq_at_dispatch, u64 dsq_id,
3295 			    u64 slice, u64 vtime, u64 enq_flags)
3296 {
3297 	struct scx_dispatch_q *dsq;
3298 	unsigned long opss;
3299 
3300 retry:
3301 	/*
3302 	 * No need for _acquire here. @p is accessed only after a successful
3303 	 * try_cmpxchg to DISPATCHING.
3304 	 */
3305 	opss = atomic_long_read(&p->scx.ops_state);
3306 
3307 	switch (opss & SCX_OPSS_STATE_MASK) {
3308 	case SCX_OPSS_DISPATCHING:
3309 	case SCX_OPSS_NONE:
3310 		/* someone else already got to it */
3311 		return;
3312 	case SCX_OPSS_QUEUED:
3313 		/*
3314 		 * If qseq doesn't match, @p has gone through at least one
3315 		 * dispatch/dequeue and re-enqueue cycle between
3316 		 * scx_bpf_dsq_insert() and here and we have no claim on it.
3317 		 */
3318 		if ((opss & SCX_OPSS_QSEQ_MASK) != qseq_at_dispatch)
3319 			return;
3320 
3321 		/* see SCX_EV_INSERT_NOT_OWNED definition */
3322 		if (unlikely(!scx_task_on_sched(sch, p))) {
3323 			__scx_add_event(sch, SCX_EV_INSERT_NOT_OWNED, 1);
3324 			return;
3325 		}
3326 
3327 		/*
3328 		 * While we know @p is accessible, we don't yet have a claim on
3329 		 * it - the BPF scheduler is allowed to dispatch tasks
3330 		 * spuriously and there can be a racing dequeue attempt. Let's
3331 		 * claim @p by atomically transitioning it from QUEUED to
3332 		 * DISPATCHING.
3333 		 */
3334 		if (likely(atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
3335 						   SCX_OPSS_DISPATCHING)))
3336 			break;
3337 		goto retry;
3338 	case SCX_OPSS_QUEUEING:
3339 		/*
3340 		 * scx_do_enqueue_task() is in the process of transferring the
3341 		 * task to the BPF scheduler while holding @p's rq lock. As we
3342 		 * aren't holding any kernel or BPF resource that the enqueue
3343 		 * path may depend upon, it's safe to wait.
3344 		 */
3345 		wait_ops_state(p, opss);
3346 		goto retry;
3347 	}
3348 
3349 	BUG_ON(!(p->scx.flags & SCX_TASK_QUEUED));
3350 
3351 	dsq = find_dsq_for_dispatch(sch, rq, dsq_id, task_cpu(p));
3352 
3353 	if (dsq->id == SCX_DSQ_LOCAL)
3354 		dispatch_to_local_dsq(sch, rq, dsq, p, slice, vtime, enq_flags);
3355 	else
3356 		scx_dispatch_enqueue(sch, rq, dsq, p, slice, vtime,
3357 				     enq_flags | SCX_ENQ_APPLY_SLICE | SCX_ENQ_CLEAR_OPSS);
3358 }
3359 
3360 void scx_flush_dispatch_buf(struct scx_sched *sch, struct rq *rq)
3361 {
3362 	struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
3363 	u32 u;
3364 
3365 	for (u = 0; u < dspc->cursor; u++) {
3366 		struct scx_dsp_buf_ent *ent = &dspc->buf[u];
3367 
3368 		finish_dispatch(sch, rq, ent->task, ent->qseq, ent->dsq_id,
3369 				ent->slice, ent->vtime, ent->enq_flags);
3370 	}
3371 
3372 	dspc->nr_tasks += dspc->cursor;
3373 	dspc->cursor = 0;
3374 }
3375 
3376 static inline void maybe_queue_balance_callback(struct rq *rq)
3377 {
3378 	lockdep_assert_rq_held(rq);
3379 
3380 	if (!(rq->scx.flags & SCX_RQ_BAL_CB_PENDING))
3381 		return;
3382 
3383 	queue_balance_callback(rq, &rq->scx.deferred_bal_cb,
3384 				deferred_bal_cb_workfn);
3385 
3386 	rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING;
3387 }
3388 
3389 static enum scx_dsp_verdict dispatch_one(struct rq *rq, struct task_struct *prev)
3390 {
3391 	struct scx_sched *root_sch = scx_root_protected_live();
3392 	enum scx_dsp_verdict verdict;
3393 	s32 cpu = cpu_of(rq);
3394 
3395 	lockdep_assert_rq_held(rq);
3396 	rq->scx.flags |= SCX_RQ_IN_DISPATCH;
3397 
3398 	scx_process_sync_ecaps(rq, prev);
3399 
3400 	if ((root_sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) &&
3401 	    unlikely(rq->scx.cpu_released)) {
3402 		/*
3403 		 * If the previous sched_class for the current CPU was not SCX,
3404 		 * notify the BPF scheduler that it again has control of the
3405 		 * core. This callback complements ->cpu_release(), which is
3406 		 * emitted in switch_class().
3407 		 */
3408 		if (root_sch->ops.cpu_acquire)
3409 			SCX_CALL_OP(root_sch, cpu_acquire, rq, cpu, NULL);
3410 		rq->scx.cpu_released = false;
3411 	}
3412 
3413 	/* the ecaps sync may have dropped the rq lock */
3414 	if (scx_dsp_prev_stale(rq, prev)) {
3415 		verdict = SCX_DSP_RETRY;
3416 		goto has_tasks;
3417 	}
3418 
3419 	if (prev->sched_class == &ext_sched_class) {
3420 		update_curr_scx(rq);
3421 
3422 		/*
3423 		 * Under bypass, @prev's slice can't be trusted as a cpu-form
3424 		 * scheduler can write it directly from BPF. Skipping the keep
3425 		 * below is not enough as the post-dispatch test in
3426 		 * scx_dispatch_sched() would keep @prev on the same slice.
3427 		 *
3428 		 * Expire it as the bypass tick would, so that neither test
3429 		 * keeps @prev on it and @prev rotates through the bypass
3430 		 * enqueue. A kernel slice is left alone and the keep below
3431 		 * keeps @prev on it, see %SCX_TASK_KERNEL_SLICE.
3432 		 *
3433 		 * TODO: Once the cpu form is deprecated and the kfuncs refuse
3434 		 * slice raises from a bypassing scheduler, slices can be
3435 		 * trusted under bypass. This expiry, the bypass tick's zeroing
3436 		 * and the related slice handling can then be cleaned up.
3437 		 */
3438 		if (scx_bypassing(scx_task_sched(prev), cpu))
3439 			expire_task_slice(prev);
3440 
3441 		/*
3442 		 * If @prev is runnable & has slice left, it has priority and
3443 		 * fetching more just increases latency for the fetched tasks.
3444 		 * Tell pick_task_scx() to keep running @prev. If the BPF
3445 		 * scheduler wants to handle this explicitly, it should
3446 		 * implement ->cpu_release().
3447 		 */
3448 		if ((prev->scx.flags & SCX_TASK_QUEUED) && prev->scx.slice) {
3449 			verdict = SCX_DSP_PREV;
3450 			goto has_tasks;
3451 		}
3452 	}
3453 
3454 	/* if there already are tasks to run, nothing to do */
3455 	if (rq->scx.local_dsq.nr) {
3456 		verdict = SCX_DSP_LOCAL;
3457 		goto has_tasks;
3458 	}
3459 
3460 	verdict = scx_dispatch_sched(root_sch, rq, prev, false);
3461 
3462 	/* scx_dispatch_sched() may have dropped the rq lock */
3463 	if (scx_dsp_prev_stale(rq, prev))
3464 		verdict = SCX_DSP_RETRY;
3465 	if (verdict != SCX_DSP_NONE)
3466 		goto has_tasks;
3467 
3468 	/*
3469 	 * Didn't find another task to run. Keep running @prev unless its own
3470 	 * scheduler set %SCX_OPS_ENQ_LAST and takes the enqueue instead, see
3471 	 * put_prev_task_scx(). Read the scheduler here as the dispatch above
3472 	 * may have dropped the rq lock while @prev changed class or scheduler.
3473 	 */
3474 	if (prev->scx.flags & SCX_TASK_QUEUED) {
3475 		struct scx_sched *prev_sch = scx_task_sched(prev);
3476 
3477 		if ((!(prev_sch->ops.flags & SCX_OPS_ENQ_LAST) ||
3478 		     scx_bypassing(prev_sch, cpu)) && scx_task_can_stay_on_cpu(rq, prev)) {
3479 			__scx_add_event(prev_sch, SCX_EV_DISPATCH_KEEP_LAST, 1);
3480 			verdict = SCX_DSP_PREV;
3481 			goto has_tasks;
3482 		}
3483 
3484 		/*
3485 		 * The scheduler preempts a rescuee like any other task by
3486 		 * zeroing its slice. The grant survives the preemption. The
3487 		 * rescuee gets the unserved remainder back and runs again
3488 		 * behind whatever the scheduler wanted to run first.
3489 		 *
3490 		 * Two sites restore the remainder. When another task won the
3491 		 * pick, put_prev_task_scx() restores it and queues the rescuee
3492 		 * at the tail of the local DSQ.
3493 		 *
3494 		 * When nothing else is runnable, the cpu must not go idle with
3495 		 * the rescuee queued. The keep above takes a rescuee whose
3496 		 * scheduler holds %SCX_CAP_BASE here and doesn't take the last
3497 		 * task through %SCX_OPS_ENQ_LAST.
3498 		 *
3499 		 * The pick then ends its zeroed slice, and the rescue with it,
3500 		 * and refills a default slice. The task continues as an
3501 		 * ordinary one, which is fine as its scheduler holds BASE here.
3502 		 *
3503 		 * For any other rescuee, a reinsert from put_prev_task_scx()
3504 		 * would come after the pick settled on idle. Keep it running on
3505 		 * the remainder here.
3506 		 */
3507 		if (unlikely(prev == scx_rescuee(rq)) && scx_rescue_keep(rq, prev)) {
3508 			verdict = SCX_DSP_PREV;
3509 			goto has_tasks;
3510 		}
3511 	}
3512 	rq->scx.flags &= ~SCX_RQ_IN_DISPATCH;
3513 	return SCX_DSP_NONE;
3514 
3515 has_tasks:
3516 	/*
3517 	 * @rq may have extra IMMED tasks without reenq scheduled:
3518 	 *
3519 	 * - rq_is_open() can't reliably tell when and how slice is going to be
3520 	 *   modified for $curr and allows IMMED tasks to be queued while
3521 	 *   dispatch is in progress.
3522 	 *
3523 	 * - A non-IMMED HEAD task can get queued in front of an IMMED task
3524 	 *   between the IMMED queueing and the subsequent scheduling event.
3525 	 *
3526 	 * - When dispatch keeps @prev, even a lone IMMED task queued during the
3527 	 *   dispatch can't run right away.
3528 	 */
3529 	if (unlikely((rq->scx.local_dsq.nr > 1 || verdict == SCX_DSP_PREV) &&
3530 		     rq->scx.nr_immed))
3531 		scx_schedule_reenq_local(rq, 0);
3532 
3533 	rq->scx.flags &= ~SCX_RQ_IN_DISPATCH;
3534 	return verdict;
3535 }
3536 
3537 static void scx_start_task_running(struct rq *rq, struct task_struct *p)
3538 {
3539 	struct scx_sched *sch = scx_task_sched(p);
3540 
3541 	if (p->scx.flags & SCX_TASK_RUN_TRACKED)
3542 		return;
3543 
3544 	scx_cid_sched_update(rq, sch);
3545 
3546 	if (SCX_HAS_OP(sch, running))
3547 		SCX_CALL_OP_TASK(sch, running, rq, p);
3548 
3549 	p->scx.flags |= SCX_TASK_RUN_TRACKED;
3550 }
3551 
3552 static void kick_sync_wait_bal_cb(struct rq *rq);
3553 
3554 static void set_next_task_scx(struct rq *rq, struct task_struct *p, enum snt_e type)
3555 {
3556 	bool first = type == SNT_PICK;
3557 	bool can_stop_tick;
3558 
3559 	/*
3560 	 * A blocked pick is provisional until proxy resolution completes, see
3561 	 * put_prev_task_scx(). A retry can repick the same donor, so
3562 	 * SNT_REPICK must set it again.
3563 	 */
3564 	rq->scx.flags &= ~SCX_RQ_PROXY_PENDING;
3565 	if (sched_proxy_exec() && p->is_blocked &&
3566 	    (type == SNT_PICK || type == SNT_REPICK))
3567 		rq->scx.flags |= SCX_RQ_PROXY_PENDING;
3568 
3569 	/*
3570 	 * Defer the kick_sync wait to a balance callback which can drop rq lock
3571 	 * and enable IRQs. Waiting directly in the pick path would deadlock
3572 	 * against CPUs sending us IPIs (e.g., TLB flushes) while we wait for
3573 	 * them.
3574 	 *
3575 	 * Queue it only once the pick is final, so that the rq lock can't be
3576 	 * released with the callback queued (e.g., by another dispatch during
3577 	 * a core-wide selection). If no SCX task gets picked, there's nothing
3578 	 * to wait for and kick_sync_pending stays set for the next SCX pick.
3579 	 */
3580 	if (unlikely(rq->scx.kick_sync_pending) && (type == SNT_PICK || type == SNT_REPICK))
3581 		queue_balance_callback(rq, &rq->scx.kick_sync_bal_cb, kick_sync_wait_bal_cb);
3582 
3583 	if (type == SNT_REPICK)
3584 		return;
3585 
3586 	if (p->scx.flags & SCX_TASK_QUEUED) {
3587 		/*
3588 		 * Core-sched might decide to execute @p before it is
3589 		 * dispatched. Call ops_dequeue() to notify the BPF scheduler.
3590 		 */
3591 		ops_dequeue(rq, p, SCX_DEQ_CORE_SCHED_EXEC);
3592 		scx_dispatch_dequeue(rq, p);
3593 		p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
3594 	}
3595 
3596 	p->se.exec_start = rq_clock_task(rq);
3597 
3598 	/*
3599 	 * See dequeue_task_scx() for why we skip when !QUEUED.
3600 	 *
3601 	 * During a normal switch (@first), a blocked task is only a provisional
3602 	 * donor. Proxy resolution may fail or migrate the donor to another CPU,
3603 	 * so defer ops.running() until scx_proxy_donor_start() confirms that
3604 	 * resolution succeeded.
3605 	 *
3606 	 * !@first denotes restoration after a SAVE/RESTORE cycle. The matching
3607 	 * dequeue already issued ops.stopping(), so restart the session here
3608 	 * regardless of the donor state.
3609 	 */
3610 	if ((p->scx.flags & SCX_TASK_QUEUED) && !(p->is_blocked && first))
3611 		scx_start_task_running(rq, p);
3612 
3613 	clr_task_runnable(p, true);
3614 
3615 	/* apply any pending out-of-band slice request before the tick decision */
3616 	apply_task_slice_oob(rq, p);
3617 	can_stop_tick = p->scx.slice == SCX_SLICE_INF && !p->is_blocked;
3618 
3619 	/*
3620 	 * @p is getting newly scheduled or got kicked after someone updated its
3621 	 * slice. Update SCX_RQ_CAN_STOP_TICK to reflect whether the tick can be
3622 	 * stopped. See scx_can_stop_tick().
3623 	 *
3624 	 * Moreover, refresh the load_avgs just when transitioning in and out of
3625 	 * nohz. In the future, we might want to add a mechanism to update
3626 	 * load_avgs periodically on tick-stopped CPUs.
3627 	 */
3628 	if (can_stop_tick) {
3629 		if (!(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) {
3630 			/*
3631 			 * Bypass mode always assigns finite slices, so @p
3632 			 * can't have an infinite slice while bypassing.
3633 			 * Therefore, sched_update_tick_dependency() can safely
3634 			 * evaluate the outgoing task.
3635 			 */
3636 			rq->scx.flags |= SCX_RQ_CAN_STOP_TICK;
3637 			sched_update_tick_dependency(rq);
3638 
3639 			update_other_load_avgs(rq);
3640 		}
3641 	} else {
3642 		if (rq->scx.flags & SCX_RQ_CAN_STOP_TICK) {
3643 			rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK;
3644 			update_other_load_avgs(rq);
3645 		}
3646 
3647 		/*
3648 		 * @rq still references the outgoing scheduling context. A finite
3649 		 * slice or a blocked proxy donor is sufficient by itself to require
3650 		 * the tick.
3651 		 */
3652 		if (tick_nohz_full_cpu(cpu_of(rq)))
3653 			tick_nohz_dep_set_cpu(cpu_of(rq), TICK_DEP_BIT_SCHED);
3654 	}
3655 }
3656 
3657 void scx_proxy_donor_start(struct rq *rq)
3658 {
3659 	struct task_struct *donor = rq->donor;
3660 
3661 	lockdep_assert_rq_held(rq);
3662 	rq->scx.flags &= ~SCX_RQ_PROXY_PENDING;
3663 
3664 	if (donor->sched_class == &ext_sched_class && (donor->scx.flags & SCX_TASK_QUEUED))
3665 		scx_start_task_running(rq, donor);
3666 }
3667 
3668 static enum scx_cpu_preempt_reason
3669 preempt_reason_from_class(const struct sched_class *class)
3670 {
3671 	if (class == &stop_sched_class)
3672 		return SCX_CPU_PREEMPT_STOP;
3673 	if (class == &dl_sched_class)
3674 		return SCX_CPU_PREEMPT_DL;
3675 	if (class == &rt_sched_class)
3676 		return SCX_CPU_PREEMPT_RT;
3677 	return SCX_CPU_PREEMPT_UNKNOWN;
3678 }
3679 
3680 static void switch_class(struct rq *rq, struct task_struct *next)
3681 {
3682 	struct scx_sched *sch = scx_root_protected_live();
3683 	const struct sched_class *next_class = next->sched_class;
3684 
3685 	if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT))
3686 		return;
3687 
3688 	/*
3689 	 * The callback is conceptually meant to convey that the CPU is no
3690 	 * longer under the control of SCX. Therefore, don't invoke the callback
3691 	 * if the next class is below SCX (in which case the BPF scheduler has
3692 	 * actively decided not to schedule any tasks on the CPU).
3693 	 */
3694 	if (sched_class_above(&ext_sched_class, next_class))
3695 		return;
3696 
3697 	/*
3698 	 * At this point we know that SCX was preempted by a higher priority
3699 	 * sched_class, so invoke the ->cpu_release() callback if we have not
3700 	 * done so already. We only send the callback once between SCX being
3701 	 * preempted, and it regaining control of the CPU.
3702 	 *
3703 	 * ->cpu_release() complements ->cpu_acquire(), which is emitted the
3704 	 *  next time that dispatch_one() is invoked.
3705 	 */
3706 	if (!rq->scx.cpu_released) {
3707 		if (sch->ops.cpu_release) {
3708 			struct scx_cpu_release_args args = {
3709 				.reason = preempt_reason_from_class(next_class),
3710 				.task = next,
3711 			};
3712 
3713 			SCX_CALL_OP(sch, cpu_release, rq, cpu_of(rq), &args);
3714 		}
3715 		rq->scx.cpu_released = true;
3716 	}
3717 }
3718 
3719 static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
3720 			      struct task_struct *next)
3721 {
3722 	struct scx_sched *sch = scx_task_sched(p);
3723 	bool proxy_put = p->is_blocked && next == rq->idle &&
3724 			 (rq->scx.flags & SCX_RQ_PROXY_PENDING);
3725 	bool proxy_block = rq->scx.flags & SCX_RQ_PROXY_BLOCKING;
3726 	bool rescue_keep = false;
3727 	bool going_idle = !proxy_put && next &&
3728 			  sched_class_above(&ext_sched_class, next->sched_class);
3729 
3730 	rq->scx.flags &= ~SCX_RQ_PROXY_PENDING;
3731 
3732 	/* see kick_sync_wait_bal_cb() */
3733 	smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
3734 
3735 	update_curr_scx(rq);
3736 
3737 	/*
3738 	 * Preserve the running session when proxy execution refreshes the same
3739 	 * donor around an execution-context switch on this rq.
3740 	 */
3741 	if (next != p && (p->scx.flags & SCX_TASK_QUEUED) &&
3742 	    (p->scx.flags & SCX_TASK_RUN_TRACKED)) {
3743 		if (SCX_HAS_OP(sch, stopping))
3744 			SCX_CALL_OP_TASK(sch, stopping, rq, p, !proxy_block);
3745 
3746 		p->scx.flags &= ~SCX_TASK_RUN_TRACKED;
3747 	}
3748 
3749 	/*
3750 	 * If the slice is consumed, protection ends with it.
3751 	 *
3752 	 * A rescuee keeps going when a preemption or ops.stopping() zeroed its
3753 	 * slice. Here another task won the pick. scx_rescue_keep() restores the
3754 	 * unserved remainder and the reinsert below queues the rescuee at the
3755 	 * tail of the local DSQ. When nothing else is runnable, dispatch_one()
3756 	 * keeps the rescuee running on the remainder instead.
3757 	 */
3758 	if (!p->scx.slice) {
3759 		if (unlikely(p == scx_rescuee(rq)))
3760 			rescue_keep = scx_rescue_keep(rq, p);
3761 		if (!rescue_keep)
3762 			scx_task_slice_ended(rq, p);
3763 	}
3764 
3765 	if (p->scx.flags & SCX_TASK_QUEUED) {
3766 		if (proxy_block)
3767 			goto switch_class;
3768 
3769 		set_task_runnable(rq, p);
3770 
3771 		/*
3772 		 * If the donor is the same and only the mutex owner changes,
3773 		 * avoid triggering another ops.enqueue(): the BPF scheduler has
3774 		 * already admitted the donor, so it can continue running.
3775 		 */
3776 		if (p->is_blocked && next == p)
3777 			goto switch_class;
3778 
3779 		/*
3780 		 * If @p has slice left and is being put, @p is getting
3781 		 * preempted by a higher priority scheduler class or core-sched
3782 		 * forcing a different task. Leave it at the head of the local
3783 		 * DSQ unless it was an IMMED task. IMMED tasks should not
3784 		 * linger on a busy CPU, reenqueue them to the BPF scheduler.
3785 		 *
3786 		 * The exception is an IMMED donor put by proxy_resched_idle():
3787 		 * the CPU isn't busy, proxy resolution is only retrying through
3788 		 * idle, so keep the donor where it can be picked again.
3789 		 *
3790 		 * A task with a kernel slice stays on the local DSQ even while
3791 		 * @sch bypasses. Under bypass, rescue runs @p when the host
3792 		 * lacks %SCX_CAP_BASE, see bypass_enq_target_dsq().
3793 		 */
3794 		if (p->scx.slice && (!scx_bypassing(sch, cpu_of(rq)) ||
3795 				     scx_task_has_kernel_slice(p))) {
3796 			if ((p->scx.flags & SCX_TASK_IMMED) && !proxy_put) {
3797 				p->scx.flags |= SCX_TASK_REENQ_PREEMPTED;
3798 				scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
3799 			} else {
3800 				u64 enq_flags = 0;
3801 
3802 				/*
3803 				 * The enqueue caps gate the scheduler's
3804 				 * placement. The kernel placed a kernel-slice
3805 				 * task here itself, so reinsert it without a
3806 				 * cap check, at the head like any preempted
3807 				 * task. When scx_rescue_keep() restored a slice
3808 				 * the scheduler zeroed, the scheduler wanted
3809 				 * something else to run first, so append.
3810 				 */
3811 				if (unlikely(scx_task_has_kernel_slice(p))) {
3812 					enq_flags |= SCX_ENQ_IGNORE_CAPS;
3813 					if (!rescue_keep)
3814 						enq_flags |= SCX_ENQ_HEAD;
3815 				} else {
3816 					enq_flags |= SCX_ENQ_HEAD;
3817 					/* only require SCX_CAP_ENQ_IMMED, see scx_caps_for_enq() */
3818 					if (proxy_put && (p->scx.flags & SCX_TASK_IMMED))
3819 						enq_flags |= SCX_ENQ_IMMED;
3820 				}
3821 
3822 				scx_dispatch_enqueue(sch, rq, &rq->scx.local_dsq, p, 0, 0,
3823 						     enq_flags);
3824 			}
3825 			goto switch_class;
3826 		}
3827 
3828 		/*
3829 		 * If @p is runnable but we're about to enter a lower
3830 		 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell
3831 		 * ops.enqueue() that @p is the only one available for this cpu.
3832 		 * This doesn't apply if the baseline access on the CPU is lost or
3833 		 * proxy resolution temporarily switches to idle.
3834 		 *
3835 		 * Under core scheduling, a pick dispatches only when nothing is
3836 		 * locally runnable and can legitimately go idle with @p still
3837 		 * runnable (see do_pick_task_scx()).
3838 		 */
3839 		if (going_idle && scx_task_can_stay_on_cpu(rq, p)) {
3840 			WARN_ON_ONCE(!sched_core_enabled(rq) &&
3841 				     !(sch->ops.flags & SCX_OPS_ENQ_LAST));
3842 			scx_do_enqueue_task(rq, p, SCX_ENQ_LAST, -1);
3843 		} else {
3844 			scx_do_enqueue_task(rq, p, 0, -1);
3845 		}
3846 
3847 		/*
3848 		 * @p may be on the local DSQ now. With %SCX_ENQ_LAST the
3849 		 * scheduler can put the last runnable task there. The plain
3850 		 * insert runs when @p cannot stay on this cpu, and rescue can
3851 		 * still admit it here.
3852 		 *
3853 		 * The cpu must not go idle with @p queued on its local DSQ. The
3854 		 * usual resched doesn't work: the pick has settled on @next and
3855 		 * @p is still curr, so resched_curr() would set need_resched on
3856 		 * @p, which __schedule() clears right after the pick. Set it on
3857 		 * @next instead.
3858 		 */
3859 		if (going_idle && p->scx.dsq == &rq->scx.local_dsq)
3860 			set_tsk_need_resched(next);
3861 	}
3862 
3863 switch_class:
3864 	if (next && next->sched_class != &ext_sched_class) {
3865 		scx_cid_sched_update(rq, NULL);
3866 		switch_class(rq, next);
3867 	}
3868 }
3869 
3870 static void kick_sync_wait_bal_cb(struct rq *rq)
3871 {
3872 	struct scx_kick_syncs __rcu *ks;
3873 	unsigned long *ksyncs;
3874 	bool waited;
3875 	s32 cpu;
3876 
3877 	/*
3878 	 * This callback is queued once the pick is final and flushed within
3879 	 * @rq's own scheduling pass. If a lock taker on a foreign CPU ever
3880 	 * flushes it, the snapshots are unrelated to that CPU. Don't get in the
3881 	 * way and leave the wait pending for @rq's next pick.
3882 	 */
3883 	if (unlikely(cpu_of(rq) != smp_processor_id()))
3884 		return;
3885 
3886 	/*
3887 	 * Clear only when the wait actually runs. The callback can be dropped
3888 	 * without running (e.g., proxy exec zaps the balance callbacks and
3889 	 * picks again when find_proxy_task() fails), in which case the next
3890 	 * pick must queue it again.
3891 	 */
3892 	rq->scx.kick_sync_pending = false;
3893 
3894 	ks = __this_cpu_read(scx_kick_syncs);
3895 	ksyncs = rcu_dereference_sched(ks)->syncs;
3896 
3897 	/*
3898 	 * Drop rq lock and enable IRQs while waiting. IRQs must be enabled
3899 	 * — a target CPU may be waiting for us to process an IPI (e.g. TLB
3900 	 * flush) while we wait for its kick_sync to advance.
3901 	 *
3902 	 * Also, keep advancing our own kick_sync so that new kick_sync waits
3903 	 * targeting us, which can start after we drop the lock, cannot form
3904 	 * cyclic dependencies.
3905 	 */
3906 retry:
3907 	waited = false;
3908 	for_each_cpu(cpu, rq->scx.cpus_to_sync) {
3909 		/*
3910 		 * smp_load_acquire() pairs with smp_store_release() on
3911 		 * kick_sync updates on the target CPUs.
3912 		 */
3913 		if (cpu == cpu_of(rq) ||
3914 		    smp_load_acquire(&cpu_rq(cpu)->scx.kick_sync) != ksyncs[cpu]) {
3915 			cpumask_clear_cpu(cpu, rq->scx.cpus_to_sync);
3916 			continue;
3917 		}
3918 
3919 		scx_rq_lock_drop(rq);
3920 		raw_spin_rq_unlock_irq(rq);
3921 		while (READ_ONCE(cpu_rq(cpu)->scx.kick_sync) == ksyncs[cpu]) {
3922 			smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
3923 			cpu_relax();
3924 		}
3925 		raw_spin_rq_lock_irq(rq);
3926 		waited = true;
3927 	}
3928 
3929 	if (waited)
3930 		goto retry;
3931 }
3932 
3933 static struct task_struct *first_local_task(struct rq *rq)
3934 {
3935 	return list_first_entry_or_null(&rq->scx.local_dsq.list,
3936 					struct task_struct, scx.dsq_list.node);
3937 }
3938 
3939 /*
3940  * Run dispatch for a pick. The follow-up work is queued by do_pick_task_scx()
3941  * once the pick is final.
3942  */
3943 static enum scx_dsp_verdict dispatch_pick(struct rq *rq, struct rq_flags *rf,
3944 					  struct task_struct *prev)
3945 {
3946 	enum scx_dsp_verdict verdict;
3947 
3948 	rq_unpin_lock(rq, rf);
3949 	verdict = dispatch_one(rq, prev);
3950 	rq_repin_lock(rq, rf);
3951 
3952 	return verdict;
3953 }
3954 
3955 #ifdef CONFIG_SCHED_CORE
3956 /*
3957  * Dispatch for a pick when core scheduling is enabled. The selection picks for
3958  * all SMT siblings and the rq_i->core_pick state it builds must stay atomic
3959  * throughout. If the dispatch released the rq lock, anything can have happened
3960  * in between - return %SCX_DSP_RETRY to restart the selection against current
3961  * state.
3962  */
3963 static enum scx_dsp_verdict dispatch_core_pick(struct rq *rq, struct rq_flags *rf,
3964 					       struct task_struct *prev)
3965 {
3966 	enum scx_dsp_verdict verdict;
3967 	u32 seq = rq->scx.lock_drop_seq;
3968 
3969 	/* another dispatch is in flight on @rq, let that handle it */
3970 	if (rq->scx.flags & SCX_RQ_IN_DISPATCH)
3971 		return SCX_DSP_NONE;
3972 
3973 	rq_unpin_lock(rq, rf);
3974 
3975 	verdict = dispatch_one(rq, prev);
3976 
3977 	/*
3978 	 * A pick that returns a task isn't final under core scheduling: the
3979 	 * selection goes on to pick the siblings, and their dispatch can
3980 	 * release the rq lock, which can't happen with balance callbacks
3981 	 * queued. Don't queue the deferred work as a balance callback, for this
3982 	 * CPU or a sibling, and run it from irq_work instead.
3983 	 *
3984 	 * do_pick_task_scx() leaves %SCX_RQ_BAL_CB_PENDING alone under core
3985 	 * scheduling, so that the early return above leaves it to the dispatch
3986 	 * in flight, which handles it here.
3987 	 */
3988 	if (unlikely(rq->scx.flags & SCX_RQ_BAL_CB_PENDING)) {
3989 		rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING;
3990 		schedule_deferred(rq);
3991 	}
3992 
3993 	rq_repin_lock(rq, rf);
3994 
3995 	/* if dispatch_one() released the rq lock, restart the selection */
3996 	if (rq->scx.lock_drop_seq != seq)
3997 		return SCX_DSP_RETRY;
3998 
3999 	return verdict;
4000 }
4001 #else	/* CONFIG_SCHED_CORE */
4002 static enum scx_dsp_verdict dispatch_core_pick(struct rq *rq, struct rq_flags *rf,
4003 					       struct task_struct *prev)
4004 {
4005 	return SCX_DSP_NONE;
4006 }
4007 #endif	/* CONFIG_SCHED_CORE */
4008 
4009 static struct task_struct *
4010 do_pick_task_scx(struct rq *rq, struct rq_flags *rf, bool force_scx)
4011 {
4012 	struct task_struct *prev = rq->donor;
4013 	bool core_sched = sched_core_enabled(rq);
4014 	enum scx_dsp_verdict verdict;
4015 	struct task_struct *p;
4016 
4017 	/* A retry can abandon a provisional blocked-donor pick. */
4018 	rq->scx.flags &= ~SCX_RQ_PROXY_PENDING;
4019 
4020 	/* see kick_sync_wait_bal_cb() */
4021 	smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
4022 
4023 	rq_modified_begin(rq, &ext_sched_class);
4024 
4025 	/*
4026 	 * Core scheduling can get enabled while dispatch_pick() has the rq lock
4027 	 * released. Stick to @core_sched, so that the follow-up work below
4028 	 * matches the dispatch that ran.
4029 	 */
4030 	if (core_sched)
4031 		verdict = dispatch_core_pick(rq, rf, prev);
4032 	else
4033 		verdict = dispatch_pick(rq, rf, prev);
4034 
4035 	if (verdict == SCX_DSP_RETRY) {
4036 		p = RETRY_TASK;
4037 		goto out;
4038 	}
4039 
4040 	/*
4041 	 * If any higher-priority sched class enqueued a runnable task on this
4042 	 * rq during dispatch_one(), abort and return RETRY_TASK, so that the
4043 	 * scheduler loop can restart.
4044 	 *
4045 	 * If @force_scx is true, always try to pick a SCHED_EXT task,
4046 	 * regardless of any higher-priority sched classes activity.
4047 	 */
4048 	if (!force_scx && rq_modified_above(rq, &ext_sched_class)) {
4049 		p = RETRY_TASK;
4050 		goto out;
4051 	}
4052 
4053 	/*
4054 	 * If we're keeping @prev, replenish slice if necessary and keep running
4055 	 * @prev. Otherwise, pop the first one from the local DSQ.
4056 	 */
4057 	if (verdict == SCX_DSP_PREV) {
4058 		p = prev;
4059 		if (!p->scx.slice) {
4060 			/* the slice is consumed, protection ends */
4061 			scx_task_slice_ended(rq, p);
4062 			refill_task_slice_dfl(scx_task_sched(p), p);
4063 		}
4064 	} else {
4065 		p = first_local_task(rq);
4066 		if (!p)
4067 			goto out;
4068 
4069 		if (unlikely(!p->scx.slice) && scx_task_can_stay_on_cpu(rq, p)) {
4070 			struct scx_sched *sch = scx_task_sched(p);
4071 
4072 			if (!scx_bypassing(sch, cpu_of(rq)) &&
4073 			    !sch->warned_zero_slice) {
4074 				printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in %s()\n",
4075 						p->comm, p->pid, __func__);
4076 				sch->warned_zero_slice = true;
4077 			}
4078 			refill_task_slice_dfl(sch, p);
4079 		}
4080 	}
4081 
4082 out:
4083 	if (cpu_of(rq) != smp_processor_id())
4084 		return p;
4085 
4086 	/*
4087 	 * Balance callbacks must be consumed before the rq lock is released, so
4088 	 * queue them only when the pick is final. On RETRY_TASK, or after a
4089 	 * NULL pick from the dl_server, the core continues picking and can
4090 	 * release the rq lock (e.g., prev_balance() or another dispatch). In
4091 	 * that case, run the deferred work from irq_work, which doesn't depend
4092 	 * on the current rq lock section.
4093 	 */
4094 	if (p != RETRY_TASK && (p || !force_scx)) {
4095 		/* under core scheduling, see dispatch_core_pick() */
4096 		if (!core_sched)
4097 			maybe_queue_balance_callback(rq);
4098 	} else if (!core_sched && (rq->scx.flags & SCX_RQ_BAL_CB_PENDING)) {
4099 		rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING;
4100 		schedule_deferred(rq);
4101 	}
4102 
4103 	return p;
4104 }
4105 
4106 static struct task_struct *pick_task_scx(struct rq *rq, struct rq_flags *rf)
4107 {
4108 	return do_pick_task_scx(rq, rf, false);
4109 }
4110 
4111 /*
4112  * Select the next task to run from the ext scheduling class.
4113  *
4114  * Use do_pick_task_scx() directly with @force_scx enabled, since the
4115  * dl_server must always select a sched_ext task.
4116  */
4117 static struct task_struct *
4118 ext_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
4119 {
4120 	if (!scx_enabled())
4121 		return NULL;
4122 
4123 	return do_pick_task_scx(dl_se->rq, rf, true);
4124 }
4125 
4126 /*
4127  * Initialize the ext server deadline entity.
4128  */
4129 void ext_server_init(struct rq *rq)
4130 {
4131 	struct sched_dl_entity *dl_se = &rq->ext_server;
4132 
4133 	init_dl_entity(dl_se);
4134 
4135 	dl_server_init(dl_se, rq, ext_server_pick_task);
4136 }
4137 
4138 #ifdef CONFIG_SCHED_CORE
4139 /**
4140  * scx_prio_less - Task ordering for core-sched
4141  * @a: task A
4142  * @b: task B
4143  * @in_fi: in forced idle state
4144  *
4145  * Core-sched is implemented as an additional scheduling layer on top of the
4146  * usual sched_class'es and needs to find out the expected task ordering. For
4147  * SCX, core-sched calls this function to interrogate the task ordering.
4148  *
4149  * A pair of tasks owned by one scheduler is ordered by the owner's
4150  * ops.core_sched_before(). A pair spanning two schedulers is ordered by their
4151  * nearest common ancestor which implements the op - the one case where the op
4152  * is called on tasks that the scheduler delegated to its sub-schedulers and may
4153  * not be scheduling anymore.
4154  *
4155  * When neither applies, or the deciding scheduler is bypassing on either task's
4156  * CPU, the default ordering runs the task which has been waiting longer first.
4157  * A running task counts as the most recently serviced and orders after every
4158  * waiting task. Waiting tasks are compared by @p->scx.runnable_at.
4159  *
4160  * Return: %true if @a should run after @b.
4161  */
4162 bool scx_prio_less(const struct task_struct *a, const struct task_struct *b,
4163 		   bool in_fi)
4164 {
4165 	struct scx_sched *sch_a = scx_task_sched(a);
4166 	struct scx_sched *sch_b = scx_task_sched(b);
4167 	struct scx_sched *sch = NULL;
4168 	bool a_running, b_running;
4169 
4170 	if (sch_a == sch_b) {
4171 		if (SCX_HAS_OP(sch_a, core_sched_before))
4172 			sch = sch_a;
4173 	} else {
4174 		s32 level;
4175 
4176 		for (level = min(sch_a->level, sch_b->level); level >= 0; level--) {
4177 			struct scx_sched *anc = sch_a->ancestors[level];
4178 
4179 			if (anc == sch_b->ancestors[level] &&
4180 			    SCX_HAS_OP(anc, core_sched_before)) {
4181 				sch = anc;
4182 				break;
4183 			}
4184 		}
4185 	}
4186 
4187 	/*
4188 	 * scx_prio_less() returns whether @a should run after @b while
4189 	 * ops.core_sched_before() returns whether its first argument should run
4190 	 * before the second. Swap the arguments.
4191 	 *
4192 	 * The const qualifiers are dropped from task_struct pointers when
4193 	 * calling ops.core_sched_before(). Accesses are controlled by the
4194 	 * verifier.
4195 	 */
4196 	if (sch && !scx_bypassing(sch, task_cpu(a)) && !scx_bypassing(sch, task_cpu(b)))
4197 		return SCX_CALL_OP_2TASKS_RET(sch, core_sched_before, task_rq(a),
4198 					      (struct task_struct *)b,
4199 					      (struct task_struct *)a);
4200 
4201 	/*
4202 	 * runnable_at is refreshed only on enqueue, so a task which keeps
4203 	 * occupying its CPU carries a stale stamp. A running task is the most
4204 	 * recently serviced whatever its stamp says. Order it after every
4205 	 * waiting task.
4206 	 */
4207 	a_running = a->on_cpu;
4208 	b_running = b->on_cpu;
4209 	if (a_running != b_running)
4210 		return a_running;
4211 
4212 	return time_after(a->scx.runnable_at, b->scx.runnable_at);
4213 }
4214 #endif	/* CONFIG_SCHED_CORE */
4215 
4216 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags)
4217 {
4218 	struct scx_sched *sch = scx_task_sched(p);
4219 	bool bypassing;
4220 
4221 	/*
4222 	 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it
4223 	 * can be a good migration opportunity with low cache and memory
4224 	 * footprint. Returning a CPU different than @prev_cpu triggers
4225 	 * immediate rq migration. However, for SCX, as the current rq
4226 	 * association doesn't dictate where the task is going to run, this
4227 	 * doesn't fit well. If necessary, we can later add a dedicated method
4228 	 * which can decide to preempt self to force it through the regular
4229 	 * scheduling path.
4230 	 */
4231 	if (unlikely(wake_flags & WF_EXEC))
4232 		return prev_cpu;
4233 
4234 	bypassing = scx_bypassing(sch, task_cpu(p));
4235 	if (likely(SCX_HAS_OP(sch, select_cpu)) && !bypassing) {
4236 		s32 cpu;
4237 		struct task_struct **ddsp_taskp;
4238 
4239 		ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
4240 		WARN_ON_ONCE(*ddsp_taskp);
4241 		*ddsp_taskp = p;
4242 
4243 		this_rq()->scx.in_select_cpu = true;
4244 		cpu = SCX_CALL_OP_TASK_RET(sch, select_cpu, NULL, p,
4245 					   scx_cpu_arg(prev_cpu), wake_flags);
4246 		cpu = scx_cpu_ret(sch, cpu);
4247 		this_rq()->scx.in_select_cpu = false;
4248 		p->scx.selected_cpu = cpu;
4249 		*ddsp_taskp = NULL;
4250 		if (scx_cpu_valid(sch, cpu, "from ops.select_cpu()"))
4251 			return cpu;
4252 		else
4253 			return prev_cpu;
4254 	} else {
4255 		s32 cpu;
4256 
4257 		/*
4258 		 * While bypassing, the enqueue path routes @p to a bypass DSQ
4259 		 * without consulting the direct-dispatch target, making the
4260 		 * default selection pointless. It doesn't work anyway when the
4261 		 * scheduler does its own idle tracking and the built-in idle
4262 		 * cpumasks are not updated. Leave @p on @prev_cpu.
4263 		 */
4264 		if (bypassing) {
4265 			__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
4266 			p->scx.selected_cpu = prev_cpu;
4267 			return prev_cpu;
4268 		}
4269 
4270 		cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, NULL, 0);
4271 		if (cpu >= 0) {
4272 			/*
4273 			 * Carry the slice refill and let the insertion commit
4274 			 * it under rq lock. See the write rules.
4275 			 */
4276 			__scx_add_event(sch, SCX_EV_REFILL_SLICE_DFL, 1);
4277 			p->scx.ddsp_slice = READ_ONCE(sch->slice_dfl);
4278 			p->scx.ddsp_enq_flags = SCX_ENQ_SLICE_DFL;
4279 			p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL;
4280 		} else {
4281 			cpu = prev_cpu;
4282 		}
4283 		p->scx.selected_cpu = cpu;
4284 
4285 		return cpu;
4286 	}
4287 }
4288 
4289 static void task_woken_scx(struct rq *rq, struct task_struct *p)
4290 {
4291 	run_deferred(rq);
4292 }
4293 
4294 static void set_cpus_allowed_scx(struct task_struct *p,
4295 				 struct affinity_context *ac)
4296 {
4297 	struct scx_sched *sch = scx_task_sched(p);
4298 
4299 	set_cpus_allowed_common(p, ac);
4300 
4301 	if (task_dead_and_done(p))
4302 		return;
4303 
4304 	/*
4305 	 * The effective cpumask is stored in @p->cpus_ptr which may temporarily
4306 	 * differ from the configured one in @p->cpus_mask. Always tell the bpf
4307 	 * scheduler the effective one.
4308 	 *
4309 	 * Fine-grained memory write control is enforced by BPF making the const
4310 	 * designation pointless. Cast it away when calling the operation.
4311 	 *
4312 	 * The cid form receives the initial mask when the task is enabled and
4313 	 * hears about changes only afterwards, see struct scx_enable_args.
4314 	 */
4315 	if (SCX_HAS_OP(sch, set_cpumask) &&
4316 	    (!scx_is_cid_type() || scx_get_task_state(p) == SCX_TASK_ENABLED))
4317 		scx_call_op_set_cpumask(sch, task_rq(p), p, (struct cpumask *)p->cpus_ptr);
4318 }
4319 
4320 static void drain_offline_rq(struct rq *rq)
4321 {
4322 	struct task_struct *p, *n;
4323 
4324 	scx_rescue_flush(rq);
4325 
4326 	/*
4327 	 * An offline CPU no longer calls ops.dispatch(). Re-enqueue its tasks
4328 	 * onto the local DSQ so that they run here and balance_push() moves
4329 	 * them off.
4330 	 */
4331 	list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list, scx.runnable_node) {
4332 		if (p->scx.dsq == &rq->scx.local_dsq)
4333 			continue;
4334 		guard(sched_change)(p, DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK);
4335 	}
4336 }
4337 
4338 static void handle_hotplug(struct rq *rq, bool online)
4339 {
4340 	struct scx_sched *sch = scx_root_protected();
4341 	s32 cpu = cpu_of(rq);
4342 	s32 cpu_or_cid = cpu;
4343 
4344 	if (!online) {
4345 		guard(rq_lock_irqsave)(rq);
4346 		update_rq_clock(rq);
4347 		rq->scx.flags &= ~SCX_RQ_ONLINE;
4348 		drain_offline_rq(rq);
4349 	}
4350 
4351 	atomic_long_inc(&scx_hotplug_seq);
4352 	scx_update_frozen_cpus(cpu, online);
4353 
4354 	/*
4355 	 * scx_root updates are protected by cpus_read_lock() and will stay
4356 	 * stable here. Note that we can't depend on scx_enabled() test as the
4357 	 * hotplug ops need to be enabled before __scx_enabled is set.
4358 	 */
4359 	if (unlikely(!sch)) {
4360 		/* no root to notify, set %SCX_RQ_ONLINE right away */
4361 		if (online) {
4362 			guard(rq_lock_irqsave)(rq);
4363 			rq->scx.flags |= SCX_RQ_ONLINE;
4364 		}
4365 		return;
4366 	}
4367 
4368 	if (scx_enabled())
4369 		scx_idle_update_selcpu_topology(&sch->ops);
4370 
4371 	/*
4372 	 * The tables can't be retired while this function is running as the
4373 	 * retirement is inside cpus_read_lock. However, scx_cpu_arg() is
4374 	 * awkward here as the tables can be NULL after root enable failure and
4375 	 * lockdep would trigger without surrounding rcu_read_lock(). Open code
4376 	 * the translation. If the table is NULL, the ops are also cleared and
4377 	 * @cpu_or_cid goes unused.
4378 	 */
4379 	if (scx_is_cid_type()) {
4380 		s16 *tbl = rcu_dereference_check(scx_cpu_to_cid_tbl,
4381 						 lockdep_is_cpus_held());
4382 
4383 		if (tbl) {
4384 			struct scx_sched *pos;
4385 
4386 			cpu_or_cid = tbl[cpu];
4387 
4388 			guard(raw_spinlock_irqsave)(&scx_sched_lock);
4389 			list_for_each_entry(pos, &scx_sched_all, all) {
4390 				struct scx_cmask *mask = pos->online_cmask;
4391 
4392 				if (mask)
4393 					__assign_bit(cpu_or_cid, (unsigned long *)mask->bits,
4394 						     online);
4395 			}
4396 		}
4397 	}
4398 
4399 	/*
4400 	 * ecaps are delivered for @cpu only after ops.cpu_online() and before
4401 	 * ops.cpu_offline(). The ecaps ops may read online_cmask, so
4402 	 * scx_offline_ecaps() and scx_online_ecaps() run after its update.
4403 	 */
4404 	if (!online)
4405 		scx_offline_ecaps(rq);
4406 
4407 	if (online && SCX_HAS_OP(sch, cpu_online))
4408 		SCX_CALL_OP(sch, cpu_online, NULL, cpu_or_cid);
4409 	else if (!online && SCX_HAS_OP(sch, cpu_offline))
4410 		SCX_CALL_OP(sch, cpu_offline, NULL, cpu_or_cid);
4411 	else
4412 		scx_exit(sch, SCX_EXIT_UNREG_KERN,
4413 			 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
4414 			 "cpu %d going %s, exiting scheduler", cpu,
4415 			 online ? "online" : "offline");
4416 
4417 	if (online) {
4418 		/*
4419 		 * The cpu must not call ops.enqueue() or ops.dispatch() before
4420 		 * the root's ops.cpu_online(). The core's rq online state can't
4421 		 * gate them, as the sched domain rebuild in
4422 		 * sched_cpu_activate() can put @rq online before this function
4423 		 * runs. Set %SCX_RQ_ONLINE here.
4424 		 *
4425 		 * scx_online_ecaps() queues a reseed whose ecaps ops run in
4426 		 * dispatch context on the cpu and can insert into its local
4427 		 * DSQ. Set the flag first.
4428 		 */
4429 		scoped_guard (rq_lock_irqsave, rq)
4430 			rq->scx.flags |= SCX_RQ_ONLINE;
4431 		scx_online_ecaps(rq);
4432 	}
4433 }
4434 
4435 void scx_rq_activate(struct rq *rq)
4436 {
4437 	handle_hotplug(rq, true);
4438 }
4439 
4440 void scx_rq_deactivate(struct rq *rq)
4441 {
4442 	handle_hotplug(rq, false);
4443 }
4444 
4445 static bool check_rq_for_timeouts(struct rq *rq)
4446 {
4447 	struct scx_sched *sch;
4448 	struct task_struct *p;
4449 	struct rq_flags rf;
4450 	bool timed_out = false;
4451 
4452 	rq_lock_irqsave(rq, &rf);
4453 	sch = rcu_dereference_bh(scx_root);
4454 	if (unlikely(!sch))
4455 		goto out_unlock;
4456 
4457 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) {
4458 		/*
4459 		 * @p's owner schedules @p, or its host while the owner is
4460 		 * bypassing. Test @p against that sched's timeout and blame it.
4461 		 */
4462 		struct scx_sched *sch = scx_exec_sched(scx_task_sched(p), cpu_of(rq));
4463 		unsigned long last_runnable = p->scx.runnable_at;
4464 
4465 		if (unlikely(time_after(jiffies,
4466 					last_runnable + READ_ONCE(sch->watchdog_timeout)))) {
4467 			u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable);
4468 
4469 			__scx_exit(sch, SCX_EXIT_ERROR_STALL, 0, cpu_of(rq),
4470 				   "%s[%d] failed to run for %u.%03us",
4471 				   p->comm, p->pid, dur_ms / 1000,
4472 				   dur_ms % 1000);
4473 			timed_out = true;
4474 			break;
4475 		}
4476 	}
4477 out_unlock:
4478 	rq_unlock_irqrestore(rq, &rf);
4479 	return timed_out;
4480 }
4481 
4482 static void scx_watchdog_workfn(struct work_struct *work)
4483 {
4484 	unsigned long intv;
4485 	int cpu;
4486 
4487 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
4488 
4489 	for_each_online_cpu(cpu) {
4490 		if (unlikely(check_rq_for_timeouts(cpu_rq(cpu))))
4491 			break;
4492 
4493 		cond_resched();
4494 	}
4495 
4496 	intv = READ_ONCE(scx_watchdog_interval);
4497 	if (intv < ULONG_MAX)
4498 		queue_delayed_work(system_dfl_wq, to_delayed_work(work), intv);
4499 }
4500 
4501 void scx_tick(struct rq *rq)
4502 {
4503 	struct scx_sched *root;
4504 	unsigned long last_check;
4505 
4506 	if (!scx_enabled())
4507 		return;
4508 
4509 	root = rcu_dereference_bh(scx_root);
4510 	if (unlikely(!root))
4511 		return;
4512 
4513 	last_check = READ_ONCE(scx_watchdog_timestamp);
4514 	if (unlikely(time_after(jiffies,
4515 				last_check + READ_ONCE(root->watchdog_timeout)))) {
4516 		u32 dur_ms = jiffies_to_msecs(jiffies - last_check);
4517 
4518 		scx_exit(root, SCX_EXIT_ERROR_STALL, 0,
4519 			 "watchdog failed to check in for %u.%03us",
4520 			 dur_ms / 1000, dur_ms % 1000);
4521 	}
4522 
4523 	update_other_load_avgs(rq);
4524 }
4525 
4526 static void task_tick_scx(struct rq *rq, struct task_struct *donor, int queued)
4527 {
4528 	struct scx_sched *sch = scx_task_sched(donor);
4529 
4530 	update_curr_scx(rq);
4531 
4532 	/*
4533 	 * While disabling, always resched as we can't trust the slice
4534 	 * management.
4535 	 */
4536 	if (scx_bypassing(sch, cpu_of(rq)))
4537 		expire_task_slice(donor);
4538 	else if (SCX_HAS_OP(sch, tick))
4539 		SCX_CALL_OP_TASK(sch, tick, rq, donor);
4540 
4541 	if (!donor->scx.slice) {
4542 		/* the slice can't be trusted while bypassing */
4543 		if (READ_ONCE(donor->scx.lazy_resched) &&
4544 		    !scx_bypassing(sch, cpu_of(rq)))
4545 			scx_resched_curr_lazy(rq);
4546 		else
4547 			resched_curr(rq);
4548 	}
4549 }
4550 
4551 #ifdef CONFIG_EXT_GROUP_SCHED
4552 static struct cgroup *tg_cgrp(struct task_group *tg)
4553 {
4554 	/*
4555 	 * If CGROUP_SCHED is disabled, @tg is NULL. If @tg is an autogroup,
4556 	 * @tg->css.cgroup is NULL. In both cases, @tg can be treated as the
4557 	 * root cgroup.
4558 	 */
4559 	if (tg && tg->css.cgroup)
4560 		return tg->css.cgroup;
4561 	else
4562 		return &cgrp_dfl_root.cgrp;
4563 }
4564 
4565 #define SCX_INIT_TASK_ARGS_CGROUP(cgrp)		.cgroup = (cgrp),
4566 
4567 #else	/* CONFIG_EXT_GROUP_SCHED */
4568 
4569 #define SCX_INIT_TASK_ARGS_CGROUP(cgrp)
4570 
4571 #endif	/* CONFIG_EXT_GROUP_SCHED */
4572 
4573 /**
4574  * __scx_init_task - Initialize a task for a sched
4575  * @sch: sched to initialize @p for
4576  * @p: task of interest
4577  * @cgrp: cgroup @p is joining, %NULL for @p's current task_group's cgroup
4578  * @fork: %true if @p is being forked
4579  *
4580  * Pre-commit cgroup migration passes @cgrp explicitly as @p's task_group
4581  * still reflects the source.
4582  *
4583  * Return 0 on success, -errno on failure.
4584  */
4585 int __scx_init_task(struct scx_sched *sch, struct task_struct *p,
4586 		    struct cgroup *cgrp, bool fork)
4587 {
4588 	int ret;
4589 
4590 	p->scx.disallow = false;
4591 
4592 	if (SCX_HAS_OP(sch, init_task)) {
4593 		struct scx_init_task_args args = {
4594 			SCX_INIT_TASK_ARGS_CGROUP(cgrp ?: tg_cgrp(task_group(p)))
4595 			.fork = fork,
4596 		};
4597 
4598 		ret = SCX_CALL_OP_RET(sch, init_task, NULL, p, &args);
4599 		if (unlikely(ret)) {
4600 			ret = scx_ops_sanitize_err(sch, "init_task", ret);
4601 			return ret;
4602 		}
4603 	}
4604 
4605 	if (p->scx.disallow) {
4606 		if (unlikely(scx_parent(sch))) {
4607 			scx_error(sch, "non-root ops.init_task() set task->scx.disallow for %s[%d]",
4608 				  p->comm, p->pid);
4609 		} else if (unlikely(fork)) {
4610 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] during fork",
4611 				  p->comm, p->pid);
4612 		} else if (unlikely(scx_enable_state() != SCX_ENABLING)) {
4613 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] outside the enable path",
4614 				  p->comm, p->pid);
4615 		} else {
4616 			struct rq *rq;
4617 			struct rq_flags rf;
4618 
4619 			rq = task_rq_lock(p, &rf);
4620 
4621 			/*
4622 			 * We're in the load path and @p->policy will be applied
4623 			 * right after. Reverting @p->policy here and rejecting
4624 			 * %SCHED_EXT transitions from scx_check_setscheduler()
4625 			 * guarantees that if ops.init_task() sets @p->disallow,
4626 			 * @p can never be in SCX.
4627 			 */
4628 			if (p->policy == SCHED_EXT) {
4629 				p->policy = SCHED_NORMAL;
4630 				atomic_long_inc(&scx_nr_rejected);
4631 			}
4632 
4633 			task_rq_unlock(rq, p, &rf);
4634 		}
4635 	}
4636 
4637 	return 0;
4638 }
4639 
4640 static void __scx_enable_task(struct scx_sched *sch, struct task_struct *p)
4641 {
4642 	struct rq *rq = task_rq(p);
4643 	u32 weight;
4644 
4645 	lockdep_assert_rq_held(rq);
4646 
4647 	/*
4648 	 * Verify the task is not in BPF scheduler's custody. If flag
4649 	 * transitions are consistent, the flag should always be clear
4650 	 * here.
4651 	 */
4652 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_IN_CUSTODY);
4653 
4654 	/*
4655 	 * Set the weight before calling ops.enable() so that the scheduler
4656 	 * doesn't see a stale value if they inspect the task struct.
4657 	 */
4658 	if (task_has_idle_policy(p))
4659 		weight = WEIGHT_IDLEPRIO;
4660 	else
4661 		weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO];
4662 
4663 	p->scx.weight = sched_weight_to_cgroup(weight);
4664 	p->scx.lazy_resched = sch->ops.flags & SCX_OPS_LAZY_RESCHED;
4665 
4666 	if (SCX_HAS_OP(sch, enable)) {
4667 		if (scx_is_cid_type()) {
4668 			struct scx_cmask *cmask = scx_fill_cmask_scratch(sch, p->cpus_ptr);
4669 			struct scx_enable_args args = {
4670 				.cmask_arena_addr = scx_kaddr_to_arena(sch, cmask),
4671 			};
4672 
4673 			SCX_CALL_CID_OP_TASK(sch, enable, rq, p, &args);
4674 		} else {
4675 			SCX_CALL_OP_TASK(sch, enable, rq, p);
4676 		}
4677 	}
4678 
4679 	/*
4680 	 * The initial mask also goes out through set_cmask() so a scheduler can
4681 	 * track affinity there alone, and before set_weight() so that the mask
4682 	 * is in place when weight-dependent state is derived, see struct
4683 	 * scx_enable_args.
4684 	 */
4685 	if (scx_is_cid_type() && SCX_HAS_OP(sch, set_cpumask))
4686 		scx_call_op_set_cpumask(sch, rq, p, p->cpus_ptr);
4687 
4688 	if (SCX_HAS_OP(sch, set_weight))
4689 		SCX_CALL_OP_TASK(sch, set_weight, rq, p, p->scx.weight);
4690 }
4691 
4692 void scx_enable_task(struct scx_sched *sch, struct task_struct *p)
4693 {
4694 	__scx_enable_task(sch, p);
4695 	scx_set_task_state(p, SCX_TASK_ENABLED);
4696 }
4697 
4698 /**
4699  * scx_reset_task_fields - Reset what @p carries from its sched's control
4700  * @rq: @p's rq, locked
4701  * @p: task leaving its sched's control
4702  *
4703  * The vtime, the slice and what rides on it, the reenqueue count and the
4704  * watchdog wait belong to the sched while it controls @p. The control ends when
4705  * @p is taken off the sched or leaves the ext class while staying on the sched.
4706  * Reset them so that @p starts clean wherever it goes.
4707  */
4708 static void scx_reset_task_fields(struct rq *rq, struct task_struct *p)
4709 {
4710 	lockdep_assert_rq_held(rq);
4711 
4712 	p->scx.dsq_vtime = 0;
4713 	scx_task_slice_ended(rq, p);
4714 	scx_set_task_slice(p, 0);
4715 	p->scx.reenq_cnt = 0;
4716 
4717 	/*
4718 	 * If @p is runnable but not running, its wait started at runnable_at,
4719 	 * which ops_dequeue() didn't reset. Leaving the sched's control ends
4720 	 * the wait. Reset runnable_at the next time @p is enqueued on SCX, so
4721 	 * that the watchdog doesn't count the time @p spends elsewhere.
4722 	 */
4723 	p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
4724 }
4725 
4726 static void scx_disable_task(struct scx_sched *sch, struct task_struct *p)
4727 {
4728 	struct rq *rq = task_rq(p);
4729 
4730 	lockdep_assert_rq_held(rq);
4731 	WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED);
4732 
4733 	clear_direct_dispatch(p);
4734 
4735 	if (SCX_HAS_OP(sch, disable))
4736 		SCX_CALL_OP_TASK(sch, disable, rq, p);
4737 	scx_set_task_state(p, SCX_TASK_READY);
4738 
4739 	/*
4740 	 * Verify the task is not in BPF scheduler's custody. If flag
4741 	 * transitions are consistent, the flag should always be clear
4742 	 * here.
4743 	 */
4744 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_IN_CUSTODY);
4745 }
4746 
4747 void __scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p)
4748 {
4749 	struct scx_exit_task_args args = {
4750 		.cancelled = false,
4751 	};
4752 
4753 	lockdep_assert_held(&p->pi_lock);
4754 	lockdep_assert_rq_held(task_rq(p));
4755 
4756 	switch (scx_get_task_state(p)) {
4757 	case SCX_TASK_NONE:
4758 		/*
4759 		 * No op to call, but @p may still carry @sch's state, e.g. a
4760 		 * task punted by scx_fail_parent() and being rescued.
4761 		 */
4762 		scx_reset_task_fields(task_rq(p), p);
4763 		return;
4764 	case SCX_TASK_INIT:
4765 		args.cancelled = true;
4766 		break;
4767 	case SCX_TASK_READY:
4768 		scx_reset_task_fields(task_rq(p), p);
4769 		break;
4770 	case SCX_TASK_ENABLED:
4771 		scx_disable_task(sch, p);
4772 		/* after ops.disable() has seen the final values */
4773 		scx_reset_task_fields(task_rq(p), p);
4774 		break;
4775 	default:
4776 		WARN_ON_ONCE(true);
4777 		return;
4778 	}
4779 
4780 	if (SCX_HAS_OP(sch, exit_task))
4781 		SCX_CALL_OP_TASK(sch, exit_task, task_rq(p), p, &args);
4782 }
4783 
4784 /*
4785  * Undo a completed __scx_init_task(sch, p, false) when scx_enable_task() never
4786  * ran. The task state has not been transitioned, so this mirrors the
4787  * SCX_TASK_INIT branch in __scx_disable_and_exit_task().
4788  */
4789 void scx_sub_init_cancel_task(struct scx_sched *sch, struct task_struct *p)
4790 {
4791 	struct scx_exit_task_args args = { .cancelled = true };
4792 
4793 	lockdep_assert_held(&p->pi_lock);
4794 	lockdep_assert_rq_held(task_rq(p));
4795 
4796 	/* @p was never associated with @sch, dispatch on the explicit @sch */
4797 	if (SCX_HAS_OP(sch, exit_task))
4798 		__SCX_CALL_OP_TASK(sch, ops, exit_task, task_rq(p), p, &args);
4799 }
4800 
4801 void scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p)
4802 {
4803 	__scx_disable_and_exit_task(sch, p);
4804 
4805 	/*
4806 	 * If set, @p exited between __scx_init_task() and scx_enable_task() in
4807 	 * scx_sub_enable() and is initialized for both the associated sched and
4808 	 * its parent. Exit for the child too - scx_enable_task() never ran for
4809 	 * it, so undo only init_task. The flag is only set on the sub-enable
4810 	 * path, so it's always clear when @p arrives here in %SCX_TASK_NONE.
4811 	 */
4812 	if (p->scx.flags & SCX_TASK_SUB_INIT) {
4813 		if (!WARN_ON_ONCE(!scx_enabling_sub_sched))
4814 			scx_sub_init_cancel_task(scx_enabling_sub_sched, p);
4815 		p->scx.flags &= ~SCX_TASK_SUB_INIT;
4816 	}
4817 
4818 	scx_set_task_sched(p, NULL);
4819 	scx_set_task_state(p, SCX_TASK_NONE);
4820 }
4821 
4822 void init_scx_entity(struct sched_ext_entity *scx)
4823 {
4824 	memset(scx, 0, sizeof(*scx));
4825 	INIT_LIST_HEAD(&scx->dsq_list.node);
4826 	RB_CLEAR_NODE(&scx->dsq_priq);
4827 	scx->sticky_cpu = -1;
4828 	scx->holding_cpu = -1;
4829 	scx->runnable_cpu = -1;
4830 	INIT_LIST_HEAD(&scx->runnable_node);
4831 	scx->runnable_at = jiffies;
4832 	scx->ddsp_dsq_id = SCX_DSQ_INVALID;
4833 	scx->slice = SCX_SLICE_DFL;
4834 }
4835 
4836 /* See scx_tid_alloc / scx_tid_cursor. */
4837 static u64 scx_alloc_tid(void)
4838 {
4839 	struct scx_tid_alloc *ta;
4840 
4841 	guard(preempt)();
4842 	ta = this_cpu_ptr(&scx_tid_alloc);
4843 
4844 	if (unlikely(ta->next >= ta->end)) {
4845 		ta->next = atomic64_fetch_add(SCX_TID_CHUNK, &scx_tid_cursor);
4846 		ta->end = ta->next + SCX_TID_CHUNK;
4847 	}
4848 	return ta->next++;
4849 }
4850 
4851 static void scx_tid_hash_insert(struct task_struct *p)
4852 {
4853 	int ret;
4854 
4855 	lockdep_assert_held(&scx_tasks_lock);
4856 
4857 	ret = rhashtable_lookup_insert_fast(&scx_tid_hash,
4858 					    &p->scx.tid_hash_node,
4859 					    scx_tid_hash_params);
4860 	WARN_ON_ONCE(ret);
4861 }
4862 
4863 void scx_pre_fork(struct task_struct *p)
4864 {
4865 	/*
4866 	 * BPF scheduler enable/disable paths want to be able to iterate and
4867 	 * update all tasks which can become complex when racing forks. As
4868 	 * enable/disable are very cold paths, let's use a percpu_rwsem to
4869 	 * exclude forks.
4870 	 */
4871 	percpu_down_read(&scx_fork_rwsem);
4872 }
4873 
4874 int scx_fork(struct task_struct *p, struct kernel_clone_args *kargs)
4875 {
4876 	s32 ret;
4877 
4878 	percpu_rwsem_assert_held(&scx_fork_rwsem);
4879 
4880 	p->scx.tid = scx_alloc_tid();
4881 
4882 	if (scx_init_task_enabled) {
4883 #ifdef CONFIG_EXT_SUB_SCHED
4884 		struct scx_sched *sch = scx_cgroup_sched(kargs->cset->dfl_cgrp);
4885 #else
4886 		struct scx_sched *sch = scx_root_protected_live();
4887 #endif
4888 		scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
4889 		ret = __scx_init_task(sch, p, NULL, true);
4890 		if (unlikely(ret)) {
4891 			scx_set_task_state(p, SCX_TASK_NONE);
4892 			return ret;
4893 		}
4894 		scx_set_task_state(p, SCX_TASK_INIT);
4895 		scx_set_task_sched(p, sch);
4896 	}
4897 
4898 	return 0;
4899 }
4900 
4901 void scx_post_fork(struct task_struct *p)
4902 {
4903 	if (scx_init_task_enabled) {
4904 		scx_set_task_state(p, SCX_TASK_READY);
4905 
4906 		/*
4907 		 * Enable the task immediately if it's running on sched_ext.
4908 		 * Otherwise, it'll be enabled in switching_to_scx() if and
4909 		 * when it's ever configured to run with a SCHED_EXT policy.
4910 		 */
4911 		if (p->sched_class == &ext_sched_class) {
4912 			struct rq_flags rf;
4913 			struct rq *rq;
4914 
4915 			rq = task_rq_lock(p, &rf);
4916 			scx_enable_task(scx_task_sched(p), p);
4917 			task_rq_unlock(rq, p, &rf);
4918 		}
4919 	}
4920 
4921 	scoped_guard(raw_spinlock_irq, &scx_tasks_lock) {
4922 		list_add_tail(&p->scx.tasks_node, &scx_tasks);
4923 		if (scx_tid_to_task_enabled())
4924 			scx_tid_hash_insert(p);
4925 	}
4926 
4927 	percpu_up_read(&scx_fork_rwsem);
4928 }
4929 
4930 void scx_cancel_fork(struct task_struct *p)
4931 {
4932 	if (scx_init_task_enabled) {
4933 		struct rq *rq;
4934 		struct rq_flags rf;
4935 
4936 		rq = task_rq_lock(p, &rf);
4937 		WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY);
4938 		scx_disable_and_exit_task(scx_task_sched(p), p);
4939 		task_rq_unlock(rq, p, &rf);
4940 	}
4941 
4942 	percpu_up_read(&scx_fork_rwsem);
4943 }
4944 
4945 /**
4946  * task_dead_and_done - Is a task dead and done running?
4947  * @p: target task
4948  *
4949  * Once sched_ext_dead() removes the dead task from scx_tasks and exits it, the
4950  * task no longer exists from SCX's POV. However, certain sched_class ops may be
4951  * invoked on these dead tasks leading to failures - e.g. sched_setscheduler()
4952  * may try to switch a task which finished sched_ext_dead() back into SCX
4953  * triggering invalid SCX task state transitions and worse.
4954  *
4955  * Once a task has finished the final switch, sched_ext_dead() is the only thing
4956  * that needs to happen on the task. Use this test to short-circuit sched_class
4957  * operations which may be called on dead tasks.
4958  */
4959 static bool task_dead_and_done(struct task_struct *p)
4960 {
4961 	struct rq *rq = task_rq(p);
4962 
4963 	lockdep_assert_rq_held(rq);
4964 
4965 	/*
4966 	 * In do_task_dead(), a dying task sets %TASK_DEAD with preemption
4967 	 * disabled and __schedule(). If @p has %TASK_DEAD set and off CPU, @p
4968 	 * won't ever run again.
4969 	 */
4970 	return unlikely(READ_ONCE(p->__state) == TASK_DEAD) &&
4971 		!task_on_cpu(rq, p);
4972 }
4973 
4974 void sched_ext_dead(struct task_struct *p)
4975 {
4976 	/*
4977 	 * By the time control reaches here, @p has %TASK_DEAD set, switched out
4978 	 * for the last time and then dropped the rq lock - task_dead_and_done()
4979 	 * should be returning %true nullifying the straggling sched_class ops.
4980 	 * Remove from scx_tasks and exit @p.
4981 	 */
4982 	scoped_guard(raw_spinlock_irqsave, &scx_tasks_lock) {
4983 		list_del_init(&p->scx.tasks_node);
4984 		if (scx_tid_to_task_enabled())
4985 			rhashtable_remove_fast(&scx_tid_hash,
4986 					       &p->scx.tid_hash_node,
4987 					       scx_tid_hash_params);
4988 	}
4989 
4990 	/*
4991 	 * @p is off scx_tasks and wholly ours. scx_root_enable()'s READY ->
4992 	 * ENABLED transitions can't race us. Disable ops for @p.
4993 	 *
4994 	 * %SCX_TASK_DEAD synchronizes against cgroup task iteration - see
4995 	 * scx_task_iter_next_locked(). NONE tasks need no marking: cgroup
4996 	 * iteration is only used from sub-sched paths, which require root
4997 	 * enabled. Root enable transitions every live task to at least READY.
4998 	 *
4999 	 * %INIT_BEGIN means ops.init_task() is running for @p. Don't call
5000 	 * into ops; transition to %DEAD so the post-init recheck unwinds
5001 	 * via scx_sub_init_cancel_task().
5002 	 */
5003 	if (scx_get_task_state(p) != SCX_TASK_NONE) {
5004 		struct rq_flags rf;
5005 		struct rq *rq;
5006 
5007 		rq = task_rq_lock(p, &rf);
5008 		if (scx_get_task_state(p) != SCX_TASK_INIT_BEGIN)
5009 			scx_disable_and_exit_task(scx_task_sched(p), p);
5010 		scx_set_task_state(p, SCX_TASK_DEAD);
5011 		task_rq_unlock(rq, p, &rf);
5012 	}
5013 }
5014 
5015 static void reweight_task_scx(struct rq *rq, struct task_struct *p,
5016 			      const struct load_weight *lw)
5017 {
5018 	struct scx_sched *sch = scx_task_sched(p);
5019 
5020 	lockdep_assert_rq_held(task_rq(p));
5021 
5022 	if (task_dead_and_done(p))
5023 		return;
5024 
5025 	/*
5026 	 * When switching sched_class away from SCX, reweight_task_scx()
5027 	 * is called _after_ scx_disable_task(). Skip calling ops.set_weight()
5028 	 * since the BPF scheduler may have already forgotten the task in
5029 	 * ops.disable().
5030 	 * p->scx.weight will be recalculated in scx_enable_task() if the task
5031 	 * ever returns to SCX class.
5032 	 */
5033 	if (scx_get_task_state(p) != SCX_TASK_ENABLED)
5034 		return;
5035 
5036 	p->scx.weight = sched_weight_to_cgroup(scale_load_down(lw->weight));
5037 	if (SCX_HAS_OP(sch, set_weight))
5038 		SCX_CALL_OP_TASK(sch, set_weight, rq, p, p->scx.weight);
5039 }
5040 
5041 static void prio_changed_scx(struct rq *rq, struct task_struct *p, u64 oldprio)
5042 {
5043 }
5044 
5045 static void switching_to_scx(struct rq *rq, struct task_struct *p)
5046 {
5047 	struct scx_sched *sch = scx_task_sched(p);
5048 
5049 	if (task_dead_and_done(p))
5050 		return;
5051 
5052 	scx_enable_task(sch, p);
5053 
5054 	/*
5055 	 * set_cpus_allowed_scx() is not called while @p is associated with a
5056 	 * different scheduler class. Keep the BPF scheduler up-to-date. The cid
5057 	 * form gets its mask from scx_enable_task().
5058 	 */
5059 	if (!scx_is_cid_type() && SCX_HAS_OP(sch, set_cpumask))
5060 		scx_call_op_set_cpumask(sch, rq, p, (struct cpumask *)p->cpus_ptr);
5061 }
5062 
5063 static void switched_from_scx(struct rq *rq, struct task_struct *p)
5064 {
5065 	/*
5066 	 * A class change of the running task: sched_change_begin() put @p with
5067 	 * no successor, which leaves rq->scx.sched set.
5068 	 */
5069 	if (task_current_donor(rq, p))
5070 		scx_cid_sched_update(rq, NULL);
5071 
5072 	if (task_dead_and_done(p))
5073 		return;
5074 
5075 	/*
5076 	 * %NONE means SCX is no longer tracking @p at the task level (e.g.
5077 	 * scx_fail_parent() handed @p back to the parent at NONE pending the
5078 	 * parent's own teardown). There is nothing to disable; calling
5079 	 * scx_disable_task() would WARN on the non-%ENABLED state and trigger a
5080 	 * NONE -> READY validation failure.
5081 	 *
5082 	 * Either way, reset @p after ops.disable() has seen the final values. A
5083 	 * %NONE @p can still be a rescuee under the parent.
5084 	 */
5085 	if (scx_get_task_state(p) != SCX_TASK_NONE)
5086 		scx_disable_task(scx_task_sched(p), p);
5087 	scx_reset_task_fields(rq, p);
5088 }
5089 
5090 static void switched_to_scx(struct rq *rq, struct task_struct *p) {}
5091 
5092 int scx_check_setscheduler(struct task_struct *p, int policy)
5093 {
5094 	lockdep_assert_rq_held(task_rq(p));
5095 
5096 	/* If disallow, reject transitioning into SCX. */
5097 	if (scx_enabled() && READ_ONCE(p->scx.disallow) &&
5098 	    p->policy != policy && policy == SCHED_EXT)
5099 		return -EACCES;
5100 
5101 	return 0;
5102 }
5103 
5104 /*
5105  * Don't carry a donor retained by another class into sched_ext. The caller
5106  * has updated the rq clock and invokes this immediately before
5107  * sched_change_begin() records the task's queued state.
5108  */
5109 void scx_prepare_setscheduler(struct task_struct *p, int policy)
5110 {
5111 	lockdep_assert_held(&p->pi_lock);
5112 	lockdep_assert_rq_held(task_rq(p));
5113 
5114 	if (scx_enabled() && p->policy != policy && policy == SCHED_EXT)
5115 		scx_block_proxy_donor(task_rq(p), p);
5116 }
5117 
5118 static void process_ddsp_deferred_locals(struct rq *rq)
5119 {
5120 	struct task_struct *p;
5121 
5122 	lockdep_assert_rq_held(rq);
5123 
5124 	/*
5125 	 * Now that @rq can be unlocked, execute the deferred enqueueing of
5126 	 * tasks directly dispatched to the local DSQs of other CPUs. See
5127 	 * direct_dispatch(). Keep popping from the head instead of using
5128 	 * list_for_each_entry_safe() as dispatch_local_dsq() may unlock @rq
5129 	 * temporarily.
5130 	 */
5131 	while ((p = list_first_entry_or_null(&rq->scx.ddsp_deferred_locals,
5132 				struct task_struct, scx.dsq_list.node))) {
5133 		struct scx_sched *sch = scx_task_sched(p);
5134 		struct scx_dispatch_q *dsq;
5135 		u64 dsq_id = p->scx.ddsp_dsq_id;
5136 		u64 enq_flags = p->scx.ddsp_enq_flags;
5137 		u64 slice = p->scx.ddsp_slice;
5138 		u64 vtime = p->scx.ddsp_vtime;
5139 
5140 		list_del_init(&p->scx.dsq_list.node);
5141 		clear_direct_dispatch(p);
5142 
5143 		dsq = find_dsq_for_dispatch(sch, rq, dsq_id, task_cpu(p));
5144 		if (!WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL))
5145 			dispatch_to_local_dsq(sch, rq, dsq, p, slice, vtime, enq_flags);
5146 	}
5147 }
5148 
5149 /*
5150  * Determine whether @p should be reenqueued from a local DSQ.
5151  *
5152  * @reenq_flags is mutable and accumulates state across the DSQ walk:
5153  *
5154  * - %SCX_REENQ_TSR_NOT_FIRST: Set after the first task is visited. "First"
5155  *   tracks position in the DSQ list, not among IMMED tasks. A non-IMMED task at
5156  *   the head consumes the first slot.
5157  *
5158  * - %SCX_REENQ_TSR_RQ_OPEN: Set by reenq_local() before the walk if
5159  *   rq_is_open() is true.
5160  *
5161  * An IMMED task is kept (returns %false) only if it's the first task in the DSQ
5162  * AND the current task is done — i.e. it will execute immediately. All other
5163  * IMMED tasks are reenqueued. This means if a non-IMMED task sits at the head,
5164  * every IMMED task behind it gets reenqueued.
5165  *
5166  * Reenqueued tasks go through ops.enqueue() with %SCX_ENQ_REENQ |
5167  * %SCX_TASK_REENQ_IMMED. If the BPF scheduler dispatches back to the same local
5168  * DSQ with %SCX_ENQ_IMMED while the CPU is still unavailable, this triggers
5169  * another reenq cycle. Repetitions are bounded by %SCX_REENQ_MAX_REPEAT in
5170  * scx_do_enqueue_task(), which ejects the task's owning scheduler. A bypassing
5171  * scheduler's tasks are placed by the kernel instead and are not counted.
5172  */
5173 static bool local_task_should_reenq(struct rq *rq, struct task_struct *p,
5174 				    u64 *reenq_flags, u32 *reason)
5175 {
5176 	bool first;
5177 
5178 	first = !(*reenq_flags & SCX_REENQ_TSR_NOT_FIRST);
5179 	*reenq_flags |= SCX_REENQ_TSR_NOT_FIRST;
5180 
5181 	if (unlikely((p->scx.flags & SCX_TASK_PROTECTED) || scx_task_has_kernel_slice(p)))
5182 		return false;
5183 
5184 	*reason = SCX_TASK_REENQ_KFUNC;
5185 
5186 	if ((p->scx.flags & SCX_TASK_IMMED) &&
5187 	    (!first || !(*reenq_flags & SCX_REENQ_TSR_RQ_OPEN))) {
5188 		__scx_add_event(scx_task_sched(p), SCX_EV_REENQ_IMMED, 1);
5189 		*reason = SCX_TASK_REENQ_IMMED;
5190 		return true;
5191 	}
5192 
5193 	if ((*reenq_flags & SCX_REENQ_CAP_REVOKE) &&
5194 	    scx_task_reenq_on_cap_revoke(rq, p)) {
5195 		*reason = SCX_TASK_REENQ_CAP;
5196 		return true;
5197 	}
5198 
5199 	return *reenq_flags & SCX_REENQ_ANY;
5200 }
5201 
5202 /*
5203  * The dispatcher runs ops.dequeue() and stores the final ops_state after
5204  * dropping the DSQ lock, so @p can be found on a DSQ while still
5205  * %SCX_OPSS_DISPATCHING. Wait for the dispatch to finish before operating on
5206  * @p.
5207  */
5208 void scx_wait_dispatching(struct task_struct *p)
5209 {
5210 	if (unlikely(atomic_long_read_acquire(&p->scx.ops_state) == SCX_OPSS_DISPATCHING))
5211 		wait_ops_state(p, SCX_OPSS_DISPATCHING);
5212 }
5213 
5214 static u32 reenq_local(struct scx_sched *sch, struct rq *rq, u64 reenq_flags)
5215 {
5216 	LIST_HEAD(tasks);
5217 	u32 nr_enqueued = 0;
5218 	struct task_struct *p, *n;
5219 
5220 	lockdep_assert_rq_held(rq);
5221 
5222 	if (WARN_ON_ONCE(reenq_flags & __SCX_REENQ_TSR_MASK))
5223 		reenq_flags &= ~__SCX_REENQ_TSR_MASK;
5224 	if (rq_is_open(rq, 0))
5225 		reenq_flags |= SCX_REENQ_TSR_RQ_OPEN;
5226 
5227 	/*
5228 	 * The BPF scheduler may choose to dispatch tasks back to
5229 	 * @rq->scx.local_dsq. Move all candidate tasks off to a private list
5230 	 * first to avoid processing the same tasks repeatedly.
5231 	 */
5232 	list_for_each_entry_safe(p, n, &rq->scx.local_dsq.list,
5233 				 scx.dsq_list.node) {
5234 		struct scx_sched *task_sch = scx_task_sched(p);
5235 		u32 reason;
5236 
5237 		/*
5238 		 * If @p is being migrated, @p's current CPU may not agree with
5239 		 * its allowed CPUs and the migration_cpu_stop is about to
5240 		 * deactivate and re-activate @p anyway. Skip re-enqueueing.
5241 		 *
5242 		 * While racing sched property changes may also dequeue and
5243 		 * re-enqueue a migrating task while its current CPU and allowed
5244 		 * CPUs disagree, they use %ENQUEUE_RESTORE which is bypassed to
5245 		 * the current local DSQ for running tasks and thus are not
5246 		 * visible to the BPF scheduler.
5247 		 */
5248 		if (p->migration_pending)
5249 			continue;
5250 
5251 		if (!scx_is_descendant(task_sch, sch))
5252 			continue;
5253 
5254 		if (!local_task_should_reenq(rq, p, &reenq_flags, &reason))
5255 			continue;
5256 
5257 		scx_wait_dispatching(p);
5258 		scx_dispatch_dequeue(rq, p);
5259 
5260 		WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK);
5261 		p->scx.flags |= reason;
5262 
5263 		list_add_tail(&p->scx.dsq_list.node, &tasks);
5264 	}
5265 
5266 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
5267 		list_del_init(&p->scx.dsq_list.node);
5268 
5269 		scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
5270 
5271 		nr_enqueued++;
5272 	}
5273 
5274 	/*
5275 	 * The revoke that scheduled this scan may have raced the pick: donor
5276 	 * may be a now-capless task, either one that kept running or one
5277 	 * promoted off the local DSQ between the ecaps sync and this scan.
5278 	 * Zero the slice to evict it. The enqueue gate blocks new capless
5279 	 * inserts, so no later pick can slip through after the scan.
5280 	 */
5281 	if ((reenq_flags & SCX_REENQ_CAP_REVOKE) &&
5282 	    rq->donor->sched_class == &ext_sched_class &&
5283 	    scx_task_reenq_on_cap_revoke(rq, rq->donor)) {
5284 		expire_task_slice(rq->donor);
5285 		resched_curr(rq);
5286 	}
5287 
5288 	return nr_enqueued;
5289 }
5290 
5291 static void process_deferred_reenq_locals(struct rq *rq)
5292 {
5293 	lockdep_assert_rq_held(rq);
5294 
5295 	/*
5296 	 * A task can be re-queued within this loop when a reenqueued task
5297 	 * bounces straight back to the local DSQ. That recursion is bounded by
5298 	 * the per-task reenqueue cap in scx_do_enqueue_task().
5299 	 */
5300 	while (true) {
5301 		struct scx_sched *sch;
5302 		u64 reenq_flags;
5303 
5304 		scoped_guard (raw_spinlock, &rq->scx.deferred_reenq_lock) {
5305 			struct scx_deferred_reenq_local *drl =
5306 				list_first_entry_or_null(&rq->scx.deferred_reenq_locals,
5307 							 struct scx_deferred_reenq_local,
5308 							 node);
5309 			struct scx_sched_pcpu *sch_pcpu;
5310 
5311 			if (!drl)
5312 				return;
5313 
5314 			sch_pcpu = container_of(drl, struct scx_sched_pcpu,
5315 						deferred_reenq_local);
5316 			sch = sch_pcpu->sch;
5317 
5318 			reenq_flags = drl->flags;
5319 			WRITE_ONCE(drl->flags, 0);
5320 			list_del_init(&drl->node);
5321 		}
5322 
5323 		/* see schedule_dsq_reenq() */
5324 		smp_mb();
5325 
5326 		reenq_local(sch, rq, reenq_flags);
5327 	}
5328 }
5329 
5330 static bool user_task_should_reenq(struct task_struct *p, u64 reenq_flags, u32 *reason)
5331 {
5332 	*reason = SCX_TASK_REENQ_KFUNC;
5333 	if (reenq_flags & SCX_REENQ_ANY)
5334 		return true;
5335 	return (reenq_flags & SCX_REENQ_MARKED) && (p->scx.dsq_flags & SCX_TASK_DSQ_REENQ);
5336 }
5337 
5338 static void reenq_user(struct rq *rq, struct scx_dispatch_q *dsq, u64 reenq_flags)
5339 {
5340 	struct rq *locked_rq = rq;
5341 	struct scx_sched *sch = dsq->sched;
5342 	struct scx_dsq_list_node cursor = INIT_DSQ_LIST_CURSOR(cursor, dsq, 0);
5343 	struct task_struct *p;
5344 	s32 nr_visited = 0;
5345 
5346 	lockdep_assert_rq_held(rq);
5347 
5348 	raw_spin_lock(&dsq->lock);
5349 
5350 	while (likely(!READ_ONCE(sch->bypass_depth))) {
5351 		struct rq *task_rq;
5352 		u32 reason;
5353 
5354 		/*
5355 		 * Count skipped tasks too so that a long walk doesn't hold the
5356 		 * locks throughout. The cursor keeps the position.
5357 		 */
5358 		if (!(++nr_visited % SCX_TASK_ITER_BATCH)) {
5359 			raw_spin_unlock(&dsq->lock);
5360 			if (locked_rq) {
5361 				scx_rq_lock_drop(locked_rq);
5362 				raw_spin_rq_unlock(locked_rq);
5363 				locked_rq = NULL;
5364 			}
5365 			cpu_relax();
5366 			raw_spin_lock(&dsq->lock);
5367 		}
5368 
5369 		p = nldsq_cursor_next_task(&cursor, dsq);
5370 		if (!p)
5371 			break;
5372 
5373 		if (!user_task_should_reenq(p, reenq_flags, &reason))
5374 			continue;
5375 
5376 		task_rq = task_rq(p);
5377 
5378 		if (locked_rq != task_rq) {
5379 			if (locked_rq) {
5380 				scx_rq_lock_drop(locked_rq);
5381 				raw_spin_rq_unlock(locked_rq);
5382 			}
5383 			if (unlikely(!raw_spin_rq_trylock(task_rq))) {
5384 				raw_spin_unlock(&dsq->lock);
5385 				raw_spin_rq_lock(task_rq);
5386 				raw_spin_lock(&dsq->lock);
5387 			}
5388 			locked_rq = task_rq;
5389 
5390 			/* did we lose @p while switching locks? */
5391 			if (nldsq_cursor_lost_task(&cursor, task_rq, dsq, p))
5392 				continue;
5393 		}
5394 
5395 		/* @p is on @dsq, its rq and @dsq are locked */
5396 		scx_wait_dispatching(p);
5397 		dispatch_dequeue_locked(p, dsq);
5398 		raw_spin_unlock(&dsq->lock);
5399 
5400 		WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK);
5401 		p->scx.flags |= reason;
5402 
5403 		scx_do_enqueue_task(task_rq, p, SCX_ENQ_REENQ, -1);
5404 
5405 		raw_spin_lock(&dsq->lock);
5406 	}
5407 
5408 	list_del_init(&cursor.node);
5409 	raw_spin_unlock(&dsq->lock);
5410 
5411 	if (locked_rq != rq) {
5412 		if (locked_rq) {
5413 			scx_rq_lock_drop(locked_rq);
5414 			raw_spin_rq_unlock(locked_rq);
5415 		}
5416 		raw_spin_rq_lock(rq);
5417 	}
5418 }
5419 
5420 static void process_deferred_reenq_users(struct rq *rq)
5421 {
5422 	lockdep_assert_rq_held(rq);
5423 
5424 	while (true) {
5425 		struct scx_dispatch_q *dsq;
5426 		u64 dsq_id, reenq_flags;
5427 
5428 		scoped_guard (raw_spinlock, &rq->scx.deferred_reenq_lock) {
5429 			struct scx_deferred_reenq_user *dru =
5430 				list_first_entry_or_null(&rq->scx.deferred_reenq_users,
5431 							 struct scx_deferred_reenq_user,
5432 							 node);
5433 			struct scx_dsq_pcpu *dsq_pcpu;
5434 
5435 			if (!dru)
5436 				return;
5437 
5438 			dsq_pcpu = container_of(dru, struct scx_dsq_pcpu,
5439 						deferred_reenq_user);
5440 			dsq = dsq_pcpu->dsq;
5441 			reenq_flags = dru->flags;
5442 			WRITE_ONCE(dru->flags, 0);
5443 			list_del_init(&dru->node);
5444 		}
5445 
5446 		/* see schedule_dsq_reenq() */
5447 		smp_mb();
5448 
5449 		/* destroy_dsq() may have raced and invalidated @dsq, nothing to reenq */
5450 		dsq_id = READ_ONCE(dsq->id);
5451 		if (unlikely(dsq_id == SCX_DSQ_INVALID))
5452 			continue;
5453 
5454 		BUG_ON(dsq_id & SCX_DSQ_FLAG_BUILTIN);
5455 		reenq_user(rq, dsq, reenq_flags);
5456 	}
5457 }
5458 
5459 /*
5460  * Drain ready tasks from @rq->scx.reject_dsq and reenqueue them so that their
5461  * owning BPF schedulers choose placement again. Proxy-active tasks remain
5462  * parked and rearm the retry notification for a later proxy resolution.
5463  *
5464  * A task can be re-rejected repeatedly. Reenqueues are bounded per task by
5465  * SCX_REENQ_MAX_REPEAT in scx_do_enqueue_task(), which ejects the owning
5466  * scheduler. A bypassing scheduler's tasks are placed by the kernel instead and
5467  * are not counted.
5468  */
5469 static void scx_reenq_reject(struct rq *rq)
5470 {
5471 	LIST_HEAD(tasks);
5472 	struct task_struct *p, *n;
5473 
5474 	lockdep_assert_rq_held(rq);
5475 
5476 	if (list_empty(&rq->scx.reject_dsq.list))
5477 		return;
5478 
5479 	/*
5480 	 * Move ready tasks to a private list so a task re-rejected by
5481 	 * scx_do_enqueue_task() below isn't revisited this round.
5482 	 */
5483 	list_for_each_entry_safe(p, n, &rq->scx.reject_dsq.list, scx.dsq_list.node) {
5484 		u32 reason = p->scx.flags & SCX_TASK_REENQ_REASON_MASK;
5485 
5486 		WARN_ON_ONCE(!reason);
5487 
5488 		if (sched_proxy_exec() && reason == SCX_TASK_REENQ_PROXY) {
5489 			/* Affinity machinery will dequeue and reactivate @p. */
5490 			if (p->migration_pending)
5491 				continue;
5492 
5493 			if (task_on_cpu(rq, p) || task_current_donor(rq, p)) {
5494 				rq->scx.flags |= SCX_RQ_PROXY_RETRY;
5495 				continue;
5496 			}
5497 		} else {
5498 			WARN_ON_ONCE(p->migration_pending);
5499 		}
5500 
5501 		scx_wait_dispatching(p);
5502 		scx_dispatch_dequeue(rq, p);
5503 
5504 		list_add_tail(&p->scx.dsq_list.node, &tasks);
5505 	}
5506 
5507 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
5508 		list_del_init(&p->scx.dsq_list.node);
5509 
5510 		scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
5511 	}
5512 }
5513 
5514 static void run_deferred(struct rq *rq)
5515 {
5516 	process_ddsp_deferred_locals(rq);
5517 
5518 	if (!list_empty(&rq->scx.deferred_reenq_locals))
5519 		process_deferred_reenq_locals(rq);
5520 
5521 	if (!list_empty(&rq->scx.deferred_reenq_users))
5522 		process_deferred_reenq_users(rq);
5523 
5524 	scx_reenq_reject(rq);
5525 }
5526 
5527 #ifdef CONFIG_NO_HZ_FULL
5528 bool scx_can_stop_tick(struct rq *rq)
5529 {
5530 	struct task_struct *p = rq->donor;
5531 	struct scx_sched *sch = scx_task_sched(p);
5532 
5533 	/* Proxy execution is conservatively tick-driven for now. */
5534 	if (rq->scx.flags & SCX_RQ_PROXY_TICK)
5535 		return false;
5536 
5537 	if (p->sched_class != &ext_sched_class)
5538 		return true;
5539 
5540 	/*
5541 	 * @rq->donor may still reference an outgoing EXT task after it has been
5542 	 * dequeued. If no EXT tasks are accounted on @rq, ignore its stale
5543 	 * slice state. If another task is dispatched from a DSQ,
5544 	 * set_next_task_scx() will update the dependency for the incoming task.
5545 	 */
5546 	if (!rq->scx.nr_running)
5547 		return true;
5548 
5549 	if (scx_bypassing(sch, cpu_of(rq)))
5550 		return false;
5551 
5552 	/*
5553 	 * A running rescuee's charging and expiry are tick-driven, see
5554 	 * scx_rescue_charge(). Keep the tick while rescue is in progress.
5555 	 */
5556 	if (unlikely(p == scx_rescuee(rq)))
5557 		return false;
5558 
5559 	/*
5560 	 * @rq can dispatch from different DSQs, so we can't tell whether it
5561 	 * needs the tick or not by looking at nr_running. Allow stopping ticks
5562 	 * iff set_next_task_scx() determined that the selected scheduling context
5563 	 * can run tickless.
5564 	 */
5565 	return rq->scx.flags & SCX_RQ_CAN_STOP_TICK;
5566 }
5567 #endif
5568 
5569 #ifdef CONFIG_EXT_GROUP_SCHED
5570 
5571 DEFINE_STATIC_PERCPU_RWSEM(scx_cgroup_ops_rwsem);
5572 
5573 void scx_tg_init(struct task_group *tg)
5574 {
5575 	tg->scx.weight = CGROUP_WEIGHT_DFL;
5576 	tg->scx.bw_period_us = default_bw_period_us();
5577 	tg->scx.bw_quota_us = RUNTIME_INF;
5578 	tg->scx.sched_idle = false;
5579 }
5580 
5581 /**
5582  * scx_tg_sched - Resolve a task_group's sched
5583  * @tg: task_group of interest
5584  *
5585  * Return the sched that @tg's ops.cgroup_init() succeeded on, %NULL if @tg
5586  * isn't inited. An autogroup tg has no cgroup of its own and resolves to the
5587  * root sched.
5588  *
5589  * When a child sched exits, its task_groups are moved to the parent and
5590  * re-inited on it. A failed re-init fails the parent in turn and leaves the
5591  * task_group without a sched it's inited on, resolving to %NULL. See
5592  * scx_cgroup_return_subtree().
5593  *
5594  * Safe for callers read-locking the ops rwsem. tg->scx.sched rewrites
5595  * write-lock it, and tg on/offline can't overlap such callers as a css's files
5596  * are created after online and drained before offline.
5597  */
5598 static struct scx_sched *scx_tg_sched(struct task_group *tg)
5599 {
5600 	lockdep_assert(lockdep_is_held(&cgroup_mutex) ||
5601 		       lockdep_is_held(&scx_cgroup_ops_rwsem));
5602 
5603 	if (!tg->css.cgroup)
5604 		tg = &root_task_group;
5605 	/* INITED means ops.cgroup_init() succeeded on @tg->scx.sched */
5606 	return (tg->scx.flags & SCX_TG_INITED) ? tg->scx.sched : NULL;
5607 }
5608 
5609 /**
5610  * scx_tg_knob_sched - Resolve the sched receiving a task_group's knob updates
5611  * @tg: task_group of interest
5612  *
5613  * Knobs of a cgroup belong to the parent. Deliver the set_* ops to the
5614  * parent task_group's sched, which equals @tg's own sched everywhere except
5615  * at a sub-scheduler attach point, where the sub's parent sched receives
5616  * them.
5617  *
5618  * Return %NULL if the parent task_group has no sched. That can happen when the
5619  * parent's ops.cgroup_init() fails while a sub-scheduler is being disabled.
5620  *
5621  * The callers sit in @tg's cgroup file writes holding the ops rwsem read
5622  * side. That extends scx_tg_sched()'s file-write argument to the parent's
5623  * sched read: a parent css outlives its children's files.
5624  */
5625 static struct scx_sched *scx_tg_knob_sched(struct task_group *tg)
5626 {
5627 	lockdep_assert(lockdep_is_held(&cgroup_mutex) ||
5628 		       lockdep_is_held(&scx_cgroup_ops_rwsem));
5629 
5630 	if (!tg->css.cgroup || !tg->css.parent)
5631 		return scx_tg_sched(&root_task_group);
5632 	return scx_tg_sched(css_tg(tg->css.parent));
5633 }
5634 
5635 int scx_tg_online(struct task_group *tg)
5636 {
5637 	int ret = 0;
5638 
5639 	WARN_ON_ONCE(tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED));
5640 
5641 	if (scx_cgroup_enabled) {
5642 		struct scx_sched *sch;
5643 
5644 		/*
5645 		 * The cgroup lifetime notifier populates cgrp->scx_sched before
5646 		 * css_online, but only on the default hierarchy. Sub-scheds are
5647 		 * attached to the cgroup2 hierarchy, so a cgroup1 task_group
5648 		 * always belongs to the root sched.
5649 		 */
5650 		if (cgroup_on_dfl(tg->css.cgroup))
5651 			sch = scx_cgroup_sched(tg->css.cgroup);
5652 		else
5653 			sch = scx_tg_sched(&root_task_group);
5654 
5655 		if (SCX_HAS_OP(sch, cgroup_init)) {
5656 			struct scx_cgroup_init_args args =
5657 				{ .weight = tg->scx.weight,
5658 				  .bw_period_us = tg->scx.bw_period_us,
5659 				  .bw_quota_us = tg->scx.bw_quota_us,
5660 				  .bw_burst_us = tg->scx.bw_burst_us,
5661 				  .sched_idle = tg->scx.sched_idle };
5662 
5663 			ret = SCX_CALL_OP_RET(sch, cgroup_init,
5664 					      NULL, tg->css.cgroup, &args);
5665 			if (ret)
5666 				ret = scx_ops_sanitize_err(sch, "cgroup_init", ret);
5667 		}
5668 		if (ret == 0) {
5669 			tg->scx.sched = sch;
5670 			tg->scx.flags |= SCX_TG_ONLINE | SCX_TG_INITED;
5671 		}
5672 	} else {
5673 		tg->scx.flags |= SCX_TG_ONLINE;
5674 	}
5675 
5676 	return ret;
5677 }
5678 
5679 void scx_tg_offline(struct task_group *tg)
5680 {
5681 	struct scx_sched *sch = tg->scx.sched;
5682 
5683 	WARN_ON_ONCE(!(tg->scx.flags & SCX_TG_ONLINE));
5684 
5685 	/* INITED implies non-NULL @sch, test before SCX_HAS_OP() derefs */
5686 	if (scx_cgroup_enabled && (tg->scx.flags & SCX_TG_INITED) &&
5687 	    SCX_HAS_OP(sch, cgroup_exit))
5688 		SCX_CALL_OP(sch, cgroup_exit, NULL, tg->css.cgroup);
5689 	tg->scx.sched = NULL;
5690 	tg->scx.flags &= ~(SCX_TG_ONLINE | SCX_TG_INITED);
5691 }
5692 
5693 /*
5694  * @p's sched for the cgroup migration paths. Stable as re-homes happen either
5695  * at CGROUP_TASK_MIGRATED of the same migration or under scx_cgroup_lock(),
5696  * both while holding cgroup_mutex.
5697  */
5698 static struct scx_sched *scx_cgroup_task_sched(struct task_struct *p)
5699 {
5700 	return rcu_dereference_protected(p->scx.sched, lockdep_is_held(&cgroup_mutex));
5701 }
5702 
5703 int scx_cgroup_can_attach(struct cgroup_taskset *tset)
5704 {
5705 	struct cgroup_subsys_state *css;
5706 	struct task_struct *p;
5707 	int ret;
5708 
5709 	if (!scx_cgroup_enabled)
5710 		return 0;
5711 
5712 	cgroup_taskset_for_each(p, css, tset) {
5713 		struct scx_sched *sch = scx_cgroup_task_sched(p);
5714 		struct cgroup *from = tg_cgrp(task_group(p));
5715 		struct cgroup *to = tg_cgrp(css_tg(css));
5716 
5717 		WARN_ON_ONCE(p->scx.cgrp_moving_from);
5718 
5719 		/*
5720 		 * sched_move_task() omits identity migrations. Let's match the
5721 		 * behavior so that ops.cgroup_prep_move() and ops.cgroup_move()
5722 		 * always match one-to-one.
5723 		 */
5724 		if (from == to)
5725 			continue;
5726 
5727 		/*
5728 		 * The cgroup_move ops are delivered to @p's sched, and only for
5729 		 * moves that don't re-home @p. A re-homing move changes the dfl
5730 		 * cgroup's sched and is reported through the
5731 		 * exit_task/init_task pair that the re-homing generates.
5732 		 */
5733 		if (!sch || sch != scx_cgroup_sched(task_css_set(p)->mg_dst_cset->dfl_cgrp))
5734 			continue;
5735 
5736 		if (SCX_HAS_OP(sch, cgroup_prep_move)) {
5737 			ret = SCX_CALL_OP_RET(sch, cgroup_prep_move, NULL,
5738 					      p, from, css->cgroup);
5739 			if (ret) {
5740 				ret = scx_ops_sanitize_err(sch, "cgroup_prep_move", ret);
5741 				goto err;
5742 			}
5743 		}
5744 
5745 		p->scx.cgrp_moving_from = from;
5746 	}
5747 
5748 	return 0;
5749 
5750 err:
5751 	cgroup_taskset_for_each(p, css, tset) {
5752 		struct scx_sched *sch = scx_cgroup_task_sched(p);
5753 
5754 		/* cgrp_moving_from implies non-NULL @sch, test it first */
5755 		if (p->scx.cgrp_moving_from && SCX_HAS_OP(sch, cgroup_cancel_move))
5756 			SCX_CALL_OP(sch, cgroup_cancel_move, NULL,
5757 				    p, p->scx.cgrp_moving_from, css->cgroup);
5758 		p->scx.cgrp_moving_from = NULL;
5759 	}
5760 
5761 	return ret;
5762 }
5763 
5764 void scx_cgroup_move_task(struct task_struct *p)
5765 {
5766 	struct scx_sched *sch;
5767 
5768 	if (!scx_cgroup_enabled)
5769 		return;
5770 
5771 	/*
5772 	 * Migration keys off css rather than cgroup identity, so it can hand an
5773 	 * unchanged-cgroup task here with cgrp_moving_from NULL. Nothing to
5774 	 * report to the BPF scheduler then, so skip it and keep prep_move and
5775 	 * move paired.
5776 	 */
5777 	sch = scx_cgroup_task_sched(p);
5778 	if (p->scx.cgrp_moving_from && SCX_HAS_OP(sch, cgroup_move))
5779 		SCX_CALL_OP_TASK(sch, cgroup_move, task_rq(p),
5780 				 p, p->scx.cgrp_moving_from,
5781 				 tg_cgrp(task_group(p)));
5782 	p->scx.cgrp_moving_from = NULL;
5783 }
5784 
5785 void scx_cgroup_cancel_attach(struct cgroup_taskset *tset)
5786 {
5787 	struct cgroup_subsys_state *css;
5788 	struct task_struct *p;
5789 
5790 	if (!scx_cgroup_enabled)
5791 		return;
5792 
5793 	cgroup_taskset_for_each(p, css, tset) {
5794 		struct scx_sched *sch = scx_cgroup_task_sched(p);
5795 
5796 		/* cgrp_moving_from implies non-NULL @sch, test it first */
5797 		if (p->scx.cgrp_moving_from && SCX_HAS_OP(sch, cgroup_cancel_move))
5798 			SCX_CALL_OP(sch, cgroup_cancel_move, NULL,
5799 				    p, p->scx.cgrp_moving_from, css->cgroup);
5800 		p->scx.cgrp_moving_from = NULL;
5801 	}
5802 }
5803 
5804 void scx_group_set_weight(struct task_group *tg, unsigned long weight)
5805 {
5806 	struct scx_sched *sch;
5807 
5808 	percpu_down_read(&scx_cgroup_ops_rwsem);
5809 	sch = scx_tg_knob_sched(tg);
5810 
5811 	if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_weight) &&
5812 	    tg->scx.weight != weight)
5813 		SCX_CALL_OP(sch, cgroup_set_weight, NULL, tg_cgrp(tg), weight);
5814 
5815 	tg->scx.weight = weight;
5816 
5817 	percpu_up_read(&scx_cgroup_ops_rwsem);
5818 }
5819 
5820 void scx_group_set_idle(struct task_group *tg, bool idle)
5821 {
5822 	struct scx_sched *sch;
5823 
5824 	percpu_down_read(&scx_cgroup_ops_rwsem);
5825 	sch = scx_tg_knob_sched(tg);
5826 
5827 	if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_idle) &&
5828 	    tg->scx.sched_idle != idle)
5829 		SCX_CALL_OP(sch, cgroup_set_idle, NULL, tg_cgrp(tg), idle);
5830 
5831 	/* Update the task group's idle state */
5832 	tg->scx.sched_idle = idle;
5833 
5834 	percpu_up_read(&scx_cgroup_ops_rwsem);
5835 }
5836 
5837 void scx_group_set_bandwidth(struct task_group *tg,
5838 			     u64 period_us, u64 quota_us, u64 burst_us)
5839 {
5840 	struct scx_sched *sch;
5841 
5842 	percpu_down_read(&scx_cgroup_ops_rwsem);
5843 	sch = scx_tg_knob_sched(tg);
5844 
5845 	if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_bandwidth) &&
5846 	    (tg->scx.bw_period_us != period_us ||
5847 	     tg->scx.bw_quota_us != quota_us ||
5848 	     tg->scx.bw_burst_us != burst_us))
5849 		SCX_CALL_OP(sch, cgroup_set_bandwidth, NULL,
5850 			    tg_cgrp(tg), period_us, quota_us, burst_us);
5851 
5852 	tg->scx.bw_period_us = period_us;
5853 	tg->scx.bw_quota_us = quota_us;
5854 	tg->scx.bw_burst_us = burst_us;
5855 
5856 	percpu_up_read(&scx_cgroup_ops_rwsem);
5857 }
5858 #endif	/* CONFIG_EXT_GROUP_SCHED */
5859 
5860 #if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED)
5861 static struct cgroup *root_cgroup(void)
5862 {
5863 	return &cgrp_dfl_root.cgrp;
5864 }
5865 
5866 /*
5867  * cgroup_lock() must nest outside the rwsem write side: a writer waiting
5868  * for cgroup_mutex deadlocks with cgroup teardown, which holds it while
5869  * draining a set_* file write blocked on the rwsem behind the writer.
5870  */
5871 void scx_cgroup_lock(void)
5872 {
5873 	cgroup_lock();
5874 #ifdef CONFIG_EXT_GROUP_SCHED
5875 	percpu_down_write(&scx_cgroup_ops_rwsem);
5876 #endif
5877 }
5878 
5879 void scx_cgroup_unlock(void)
5880 {
5881 #ifdef CONFIG_EXT_GROUP_SCHED
5882 	percpu_up_write(&scx_cgroup_ops_rwsem);
5883 #endif
5884 	cgroup_unlock();
5885 }
5886 #else	/* CONFIG_EXT_GROUP_SCHED || CONFIG_EXT_SUB_SCHED */
5887 static inline struct cgroup *root_cgroup(void) { return NULL; }
5888 static inline void scx_cgroup_lock(void) {}
5889 static inline void scx_cgroup_unlock(void) {}
5890 #endif	/* CONFIG_EXT_GROUP_SCHED || CONFIG_EXT_SUB_SCHED */
5891 
5892 /*
5893  * Omitted operations:
5894  *
5895  * - migrate_task_rq: Unnecessary as task to cpu mapping is transient.
5896  *
5897  * - task_fork/dead: We need fork/dead notifications for all tasks regardless of
5898  *   their current sched_class. Call them directly from sched core instead.
5899  */
5900 DEFINE_SCHED_CLASS(ext) = {
5901 	.enqueue_task		= enqueue_task_scx,
5902 	.dequeue_task		= dequeue_task_scx,
5903 	.yield_task		= yield_task_scx,
5904 	.yield_to_task		= yield_to_task_scx,
5905 
5906 	.wakeup_preempt		= wakeup_preempt_scx,
5907 
5908 	.pick_task		= pick_task_scx,
5909 
5910 	.put_prev_task		= put_prev_task_scx,
5911 	.set_next_task		= set_next_task_scx,
5912 
5913 	.select_task_rq		= select_task_rq_scx,
5914 	.task_woken		= task_woken_scx,
5915 	.set_cpus_allowed	= set_cpus_allowed_scx,
5916 
5917 	.task_tick		= task_tick_scx,
5918 
5919 	.switching_to		= switching_to_scx,
5920 	.switched_from		= switched_from_scx,
5921 	.switched_to		= switched_to_scx,
5922 	.reweight_task		= reweight_task_scx,
5923 	.prio_changed		= prio_changed_scx,
5924 
5925 	.update_curr		= update_curr_scx,
5926 
5927 #ifdef CONFIG_UCLAMP_TASK
5928 	.uclamp_enabled		= 1,
5929 #endif
5930 };
5931 
5932 s32 scx_init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id, struct scx_sched *sch)
5933 {
5934 	s32 cpu;
5935 
5936 	memset(dsq, 0, sizeof(*dsq));
5937 
5938 	raw_spin_lock_init(&dsq->lock);
5939 	INIT_LIST_HEAD(&dsq->list);
5940 	dsq->id = dsq_id;
5941 	dsq->sched = sch;
5942 
5943 	/* per-DSQ deferred reenq state is only needed for user DSQs */
5944 	if (dsq_id & SCX_DSQ_FLAG_BUILTIN)
5945 		return 0;
5946 
5947 	dsq->pcpu_user = alloc_percpu(struct scx_dsq_pcpu);
5948 	if (!dsq->pcpu_user)
5949 		return -ENOMEM;
5950 
5951 	for_each_possible_cpu(cpu) {
5952 		struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu_user, cpu);
5953 
5954 		pcpu->dsq = dsq;
5955 		INIT_LIST_HEAD(&pcpu->deferred_reenq_user.node);
5956 	}
5957 
5958 	return 0;
5959 }
5960 
5961 static void exit_dsq(struct scx_dispatch_q *dsq)
5962 {
5963 	s32 cpu;
5964 
5965 	if (!dsq->pcpu_user)
5966 		return;
5967 
5968 	for_each_possible_cpu(cpu) {
5969 		struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu_user, cpu);
5970 		struct scx_deferred_reenq_user *dru = &pcpu->deferred_reenq_user;
5971 		struct rq *rq = cpu_rq(cpu);
5972 
5973 		/*
5974 		 * free_dsq_irq_workfn() cancelled the reenqs before the grace
5975 		 * period and schedule_dsq_reenq() queues nothing after that.
5976 		 */
5977 		if (WARN_ON_ONCE(!list_empty(&dru->node))) {
5978 			guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
5979 			list_del_init(&dru->node);
5980 		}
5981 	}
5982 
5983 	free_percpu(dsq->pcpu_user);
5984 }
5985 
5986 static void free_dsq_rcufn(struct rcu_head *rcu)
5987 {
5988 	struct scx_dispatch_q *dsq = container_of(rcu, struct scx_dispatch_q, rcu);
5989 
5990 	exit_dsq(dsq);
5991 	kfree(dsq);
5992 }
5993 
5994 static void free_dsq_irq_workfn(struct irq_work *irq_work)
5995 {
5996 	struct llist_node *to_free = llist_del_all(&dsqs_to_free);
5997 	struct scx_dispatch_q *dsq, *tmp_dsq;
5998 
5999 	llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node) {
6000 		s32 cpu;
6001 
6002 		/*
6003 		 * Cancel pending reenqs. Only a run_deferred() that started
6004 		 * before the grace period can hold one, and it keeps IRQs off,
6005 		 * so the grace period waits for it. After this sweep,
6006 		 * schedule_dsq_reenq() sees the invalid id under the same lock
6007 		 * and queues nothing.
6008 		 */
6009 		for_each_possible_cpu(cpu) {
6010 			struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu_user, cpu);
6011 			struct rq *rq = cpu_rq(cpu);
6012 
6013 			guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
6014 			list_del_init(&pcpu->deferred_reenq_user.node);
6015 		}
6016 
6017 		call_rcu(&dsq->rcu, free_dsq_rcufn);
6018 	}
6019 }
6020 
6021 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn);
6022 
6023 static void destroy_dsq(struct scx_sched *sch, u64 dsq_id)
6024 {
6025 	struct scx_dispatch_q *dsq;
6026 	unsigned long flags;
6027 
6028 	rcu_read_lock();
6029 
6030 	dsq = find_user_dsq(sch, dsq_id);
6031 	if (!dsq)
6032 		goto out_unlock_rcu;
6033 
6034 	raw_spin_lock_irqsave(&dsq->lock, flags);
6035 
6036 	if (dsq->nr) {
6037 		scx_error(sch, "attempting to destroy in-use dsq 0x%016llx (nr=%u)",
6038 			  dsq->id, dsq->nr);
6039 		goto out_unlock_dsq;
6040 	}
6041 
6042 	if (rhashtable_remove_fast(&sch->dsq_hash, &dsq->hash_node,
6043 				   dsq_hash_params))
6044 		goto out_unlock_dsq;
6045 
6046 	/*
6047 	 * Mark dead by invalidating ->id to prevent scx_dispatch_enqueue() from
6048 	 * queueing more tasks. As this function can be called from anywhere,
6049 	 * freeing is bounced through an irq work to avoid nesting RCU
6050 	 * operations inside scheduler locks.
6051 	 */
6052 	dsq->id = SCX_DSQ_INVALID;
6053 	if (llist_add(&dsq->free_node, &dsqs_to_free))
6054 		irq_work_queue(&free_dsq_irq_work);
6055 
6056 out_unlock_dsq:
6057 	raw_spin_unlock_irqrestore(&dsq->lock, flags);
6058 out_unlock_rcu:
6059 	rcu_read_unlock();
6060 }
6061 
6062 #ifdef CONFIG_EXT_GROUP_SCHED
6063 static void scx_cgroup_exit(struct scx_sched *sch)
6064 {
6065 	struct cgroup_subsys_state *css;
6066 
6067 	/*
6068 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
6069 	 * cgroups and exit all the inited ones, all online cgroups are exited.
6070 	 */
6071 	css_for_each_descendant_post(css, &root_task_group.css) {
6072 		struct task_group *tg = css_tg(css);
6073 
6074 		/* also clear the sched of tgs whose ops.cgroup_init() failed */
6075 		tg->scx.sched = NULL;
6076 		if (tg->scx.flags & SCX_TG_INITED) {
6077 			tg->scx.flags &= ~SCX_TG_INITED;
6078 			if (sch->ops.cgroup_exit)
6079 				SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup);
6080 		}
6081 	}
6082 }
6083 
6084 static int scx_cgroup_init(struct scx_sched *sch)
6085 {
6086 	struct cgroup_subsys_state *css;
6087 	int ret;
6088 
6089 	/*
6090 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
6091 	 * cgroups and init, all online cgroups are initialized.
6092 	 */
6093 	css_for_each_descendant_pre(css, &root_task_group.css) {
6094 		struct task_group *tg = css_tg(css);
6095 
6096 		if ((tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED)) != SCX_TG_ONLINE)
6097 			continue;
6098 
6099 		if (sch->ops.cgroup_init) {
6100 			struct scx_cgroup_init_args args = {
6101 				.weight = tg->scx.weight,
6102 				.bw_period_us = tg->scx.bw_period_us,
6103 				.bw_quota_us = tg->scx.bw_quota_us,
6104 				.bw_burst_us = tg->scx.bw_burst_us,
6105 				.sched_idle = tg->scx.sched_idle,
6106 			};
6107 
6108 			ret = SCX_CALL_OP_RET(sch, cgroup_init, NULL, css->cgroup, &args);
6109 			if (ret) {
6110 				scx_error(sch, "ops.cgroup_init() failed (%d)", ret);
6111 				return ret;
6112 			}
6113 		}
6114 
6115 		tg->scx.sched = sch;
6116 		tg->scx.flags |= SCX_TG_INITED;
6117 	}
6118 
6119 	return 0;
6120 }
6121 
6122 #else
6123 static void scx_cgroup_exit(struct scx_sched *sch) {}
6124 static int scx_cgroup_init(struct scx_sched *sch) { return 0; }
6125 #endif
6126 
6127 
6128 /********************************************************************************
6129  * Sysfs interface and ops enable/disable.
6130  */
6131 
6132 #define SCX_ATTR(_name)								\
6133 	static struct kobj_attribute scx_attr_##_name = {			\
6134 		.attr = { .name = __stringify(_name), .mode = 0444 },		\
6135 		.show = scx_attr_##_name##_show,				\
6136 	}
6137 
6138 static ssize_t scx_attr_state_show(struct kobject *kobj,
6139 				   struct kobj_attribute *ka, char *buf)
6140 {
6141 	return sysfs_emit(buf, "%s\n", scx_enable_state_str[scx_enable_state()]);
6142 }
6143 SCX_ATTR(state);
6144 
6145 static ssize_t scx_attr_switch_all_show(struct kobject *kobj,
6146 					struct kobj_attribute *ka, char *buf)
6147 {
6148 	return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all));
6149 }
6150 SCX_ATTR(switch_all);
6151 
6152 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj,
6153 					 struct kobj_attribute *ka, char *buf)
6154 {
6155 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected));
6156 }
6157 SCX_ATTR(nr_rejected);
6158 
6159 static ssize_t scx_attr_hotplug_seq_show(struct kobject *kobj,
6160 					 struct kobj_attribute *ka, char *buf)
6161 {
6162 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_hotplug_seq));
6163 }
6164 SCX_ATTR(hotplug_seq);
6165 
6166 static ssize_t scx_attr_enable_seq_show(struct kobject *kobj,
6167 					struct kobj_attribute *ka, char *buf)
6168 {
6169 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_enable_seq));
6170 }
6171 SCX_ATTR(enable_seq);
6172 
6173 static struct attribute *scx_global_attrs[] = {
6174 	&scx_attr_state.attr,
6175 	&scx_attr_switch_all.attr,
6176 	&scx_attr_nr_rejected.attr,
6177 	&scx_attr_hotplug_seq.attr,
6178 	&scx_attr_enable_seq.attr,
6179 	NULL,
6180 };
6181 
6182 static const struct attribute_group scx_global_attr_group = {
6183 	.attrs = scx_global_attrs,
6184 };
6185 
6186 static void free_pnode(struct scx_sched_pnode *pnode);
6187 static void free_exit_info(struct scx_exit_info *ei);
6188 static const char *scx_exit_reason(enum scx_exit_kind kind);
6189 static bool scx_claim_exit(struct scx_sched *sch, enum scx_exit_kind kind);
6190 
6191 s32 scx_alloc_kern_arena_objs(struct scx_sched *sch)
6192 {
6193 	size_t size = struct_size_t(struct scx_cmask, bits,
6194 				    SCX_CMASK_NR_WORDS(num_possible_cpus()));
6195 	struct scx_cmask *online;
6196 	struct scx_cmask_ref ref;
6197 	int cpu;
6198 
6199 	/* hotplug stays excluded until the online mask is published */
6200 	lockdep_assert_cpus_held();
6201 
6202 	if (!sch->is_cid_type || !sch->arena_pool)
6203 		return 0;
6204 
6205 	sch->set_cmask_scratch = alloc_percpu(struct scx_cmask *);
6206 	if (!sch->set_cmask_scratch)
6207 		return -ENOMEM;
6208 
6209 	for_each_possible_cpu(cpu) {
6210 		struct scx_cmask **slot = per_cpu_ptr(sch->set_cmask_scratch, cpu);
6211 
6212 		*slot = scx_arena_alloc(sch, size);
6213 		if (!*slot)
6214 			return -ENOMEM;
6215 		scx_cmask_init(*slot, 0, num_possible_cpus());
6216 	}
6217 
6218 	/* pack the online mask alongside the scratch masks */
6219 	online = scx_arena_alloc(sch, size);
6220 	if (!online)
6221 		return -ENOMEM;
6222 
6223 	scoped_guard(rcu) {
6224 		scx_cmask_ref_init_kern(sch, online, 0, num_possible_cpus(), &ref);
6225 		scx_cmask_ref_from_cpumask(&ref, cpu_active_mask);
6226 	}
6227 	sch->online_cmask = online;
6228 
6229 	return 0;
6230 }
6231 
6232 static void scx_free_kern_arena_objs(struct scx_sched *sch)
6233 {
6234 	size_t size = struct_size_t(struct scx_cmask, bits,
6235 				    SCX_CMASK_NR_WORDS(num_possible_cpus()));
6236 	int cpu;
6237 
6238 	scx_arena_free(sch, sch->online_cmask, size);
6239 	if (!sch->set_cmask_scratch)
6240 		return;
6241 
6242 	for_each_possible_cpu(cpu) {
6243 		struct scx_cmask **slot = per_cpu_ptr(sch->set_cmask_scratch, cpu);
6244 
6245 		scx_arena_free(sch, *slot, size);
6246 	}
6247 	free_percpu(sch->set_cmask_scratch);
6248 	sch->set_cmask_scratch = NULL;
6249 }
6250 
6251 static void scx_sched_free_rcu_work(struct work_struct *work)
6252 {
6253 	struct rcu_work *rcu_work = to_rcu_work(work);
6254 	struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work);
6255 	struct rhashtable_iter rht_iter;
6256 	struct scx_dispatch_q *dsq;
6257 	int cpu, node;
6258 
6259 	free_cpumask_var(sch->bypass_lb_donee_cpumask);
6260 	free_cpumask_var(sch->bypass_lb_resched_cpumask);
6261 	free_cpumask_var(sch->stall_cpus);
6262 
6263 #ifdef CONFIG_EXT_SUB_SCHED
6264 	kfree(sch->cgrp_path);
6265 	if (sch_cgroup(sch))
6266 		cgroup_put(sch_cgroup(sch));
6267 	if (sch->sub_kset)
6268 		kobject_put(&sch->sub_kset->kobj);
6269 	if (scx_parent(sch))
6270 		kobject_put(&scx_parent(sch)->kobj);
6271 #endif	/* CONFIG_EXT_SUB_SCHED */
6272 
6273 	for_each_possible_cpu(cpu) {
6274 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
6275 
6276 		free_cpumask_var(pcpu->cpus_to_kick);
6277 		free_cpumask_var(pcpu->cpus_to_kick_if_idle);
6278 		free_cpumask_var(pcpu->cpus_to_preempt);
6279 		free_cpumask_var(pcpu->cpus_to_preempt_lazy);
6280 		free_cpumask_var(pcpu->cpus_to_wait);
6281 
6282 		exit_dsq(scx_bypass_dsq(sch, cpu));
6283 	}
6284 
6285 	free_percpu(sch->pcpu);
6286 
6287 	for_each_node_state(node, N_POSSIBLE)
6288 		free_pnode(sch->pnode[node]);
6289 	kfree(sch->pnode);
6290 
6291 	scx_free_pshards(sch);
6292 
6293 	rhashtable_walk_enter(&sch->dsq_hash, &rht_iter);
6294 	do {
6295 		rhashtable_walk_start(&rht_iter);
6296 
6297 		while (!IS_ERR_OR_NULL((dsq = rhashtable_walk_next(&rht_iter))))
6298 			destroy_dsq(sch, dsq->id);
6299 
6300 		rhashtable_walk_stop(&rht_iter);
6301 	} while (dsq == ERR_PTR(-EAGAIN));
6302 	rhashtable_walk_exit(&rht_iter);
6303 
6304 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
6305 	free_exit_info(sch->exit_info);
6306 	scx_free_kern_arena_objs(sch);
6307 	scx_arena_pool_destroy(sch);
6308 	if (sch->arena_map)
6309 		bpf_map_put(sch->arena_map);
6310 
6311 	/* @sch is completely inactive by now */
6312 	scx_dec_has_subs(sch);
6313 
6314 	kfree(sch);
6315 }
6316 
6317 /**
6318  * scx_sched_quiesce_rcu_work - Quiesce a sched and queue its free
6319  * @work: &scx_sched.rcu_work
6320  *
6321  * $sch is freed after two RCU grace periods because of its ecaps sync nodes.
6322  *
6323  * The first grace period runs between scx_kobj_release() and this function. It
6324  * waits for the paths that found $sch before scx_unlink_sched(), such as the
6325  * sub-cap kfuncs and the cpu hotplug hooks. Until they finish, they can queue
6326  * $sch's syncs, and a cpu can take a queued node into a sync batch. The first
6327  * grace period doesn't wait for a batch that started after it began.
6328  *
6329  * Nothing queues $sch's syncs now. Remove the nodes still on the cpus' lists. A
6330  * batch that took a node can still write $sch's pcpu, and a delivery in the
6331  * batch can drop the rq lock before that write. The batch keeps irqs off from
6332  * taking the node to its last pcpu write, so the second grace period waits for
6333  * it before scx_sched_free_rcu_work() frees $sch.
6334  */
6335 static void scx_sched_quiesce_rcu_work(struct work_struct *work)
6336 {
6337 	struct rcu_work *rcu_work = to_rcu_work(work);
6338 	struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work);
6339 	s32 cpu;
6340 
6341 	irq_work_sync(&sch->propagate_exit_irq_work);
6342 	irq_work_sync(&sch->disable_irq_work);
6343 	kthread_destroy_worker(sch->helper);
6344 	timer_shutdown_sync(&sch->bypass_lb_timer);
6345 
6346 	for_each_possible_cpu(cpu) {
6347 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
6348 
6349 		/*
6350 		 * $sch would have entered bypass mode before the first RCU
6351 		 * grace period. As that blocks new deferrals, all
6352 		 * deferred_reenq_local_node's must be off-list by now.
6353 		 */
6354 		WARN_ON_ONCE(!list_empty(&pcpu->deferred_reenq_local.node));
6355 
6356 		/* remove the queued ecaps sync so the pcpu can be freed */
6357 		scx_discard_ecaps_to_sync(cpu, pcpu);
6358 
6359 		/*
6360 		 * Bypass blocks new kicks. Flush the kick irq_work so this
6361 		 * pcpu's to_kick_node is off the list before it is freed.
6362 		 */
6363 		irq_work_sync(&cpu_rq(cpu)->scx.kick_cpus_irq_work);
6364 		WARN_ON_ONCE(!list_empty(&pcpu->to_kick_node));
6365 	}
6366 
6367 	INIT_RCU_WORK(&sch->rcu_work, scx_sched_free_rcu_work);
6368 	queue_rcu_work(system_dfl_wq, &sch->rcu_work);
6369 }
6370 
6371 static void scx_kobj_release(struct kobject *kobj)
6372 {
6373 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
6374 
6375 	INIT_RCU_WORK(&sch->rcu_work, scx_sched_quiesce_rcu_work);
6376 	queue_rcu_work(system_dfl_wq, &sch->rcu_work);
6377 }
6378 
6379 static ssize_t scx_attr_ops_show(struct kobject *kobj,
6380 				 struct kobj_attribute *ka, char *buf)
6381 {
6382 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
6383 
6384 	return sysfs_emit(buf, "%s\n", sch->ops.name);
6385 }
6386 SCX_ATTR(ops);
6387 
6388 #define scx_attr_event_show(buf, at, events, kind) ({				\
6389 	sysfs_emit_at(buf, at, "%s %llu\n", #kind, (events)->kind);		\
6390 })
6391 
6392 static ssize_t scx_attr_events_show(struct kobject *kobj,
6393 				    struct kobj_attribute *ka, char *buf)
6394 {
6395 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
6396 	struct scx_event_stats events;
6397 	int at = 0;
6398 
6399 	scx_read_events(sch, &events);
6400 #define SCX_EVENT(name)	(at += scx_attr_event_show(buf, at, &events, name))
6401 	SCX_EVENTS_LIST(SCX_EVENT);
6402 #undef SCX_EVENT
6403 	return at;
6404 }
6405 SCX_ATTR(events);
6406 
6407 #ifdef CONFIG_EXT_SUB_SCHED
6408 static const char *scx_cap_names[__SCX_NR_CAPS] = {
6409 	[__SCX_CAP_ENQ_IMMED]	= "enq_immed",
6410 	[__SCX_CAP_ENQ]		= "enq",
6411 	[__SCX_CAP_PREEMPT]	= "preempt",
6412 	[__SCX_CAP_PERF]	= "perf",
6413 };
6414 
6415 static ssize_t scx_attr_caps_show(struct kobject *kobj,
6416 				  struct kobj_attribute *ka, char *buf)
6417 {
6418 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
6419 	u32 npossible = num_possible_cpus();
6420 	struct scx_cmask *agg __free(kfree) =
6421 		kzalloc_flex(*agg, bits, SCX_CMASK_NR_WORDS(npossible));
6422 	unsigned long *agg_bm __free(bitmap) = bitmap_zalloc(npossible, GFP_KERNEL);
6423 	ssize_t count = 0;
6424 	s32 cap, si;
6425 
6426 	if (!agg || !agg_bm)
6427 		return -ENOMEM;
6428 
6429 	for (cap = 0; cap < __SCX_NR_CAPS; cap++) {
6430 		SCX_CMASK_DEFINE(snap, 0, SCX_CID_SHARD_MAX_CPUS);
6431 
6432 		scx_cmask_init(agg, 0, npossible);
6433 		for (si = 0; si < sch->nr_pshards; si++) {
6434 			struct scx_cmask *cm = &sch->pshard[si]->caps[cap].cmask;
6435 
6436 			scx_cmask_reframe(snap, cm->base, cm->nr_cids);
6437 			scx_cmask_copy(snap, cm);
6438 			scx_cmask_or(agg, snap);
6439 		}
6440 		/* %*pbl takes unsigned long bitmap layout, convert from u64 */
6441 		bitmap_from_arr64(agg_bm, agg->bits, npossible);
6442 		count += sysfs_emit_at(buf, count, "%s: %*pbl\n",
6443 				       scx_cap_names[cap], npossible, agg_bm);
6444 	}
6445 	return count;
6446 }
6447 SCX_ATTR(caps);
6448 #endif	/* CONFIG_EXT_SUB_SCHED */
6449 
6450 static struct attribute *scx_sched_attrs[] = {
6451 	&scx_attr_ops.attr,
6452 	&scx_attr_events.attr,
6453 #ifdef CONFIG_EXT_SUB_SCHED
6454 	&scx_attr_caps.attr,
6455 #endif
6456 	NULL,
6457 };
6458 ATTRIBUTE_GROUPS(scx_sched);
6459 
6460 static const struct kobj_type scx_ktype = {
6461 	.release = scx_kobj_release,
6462 	.sysfs_ops = &kobj_sysfs_ops,
6463 	.default_groups = scx_sched_groups,
6464 };
6465 
6466 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
6467 {
6468 	const struct scx_sched *sch;
6469 
6470 	/*
6471 	 * scx_uevent() can be reached by both scx_sched kobjects (scx_ktype)
6472 	 * and sub-scheduler kset kobjects (kset_ktype) through the parent
6473 	 * chain walk. Filter out the latter to avoid invalid casts.
6474 	 */
6475 	if (kobj->ktype != &scx_ktype)
6476 		return 0;
6477 
6478 	sch = container_of(kobj, struct scx_sched, kobj);
6479 
6480 	return add_uevent_var(env, "SCXOPS=%s", sch->ops.name);
6481 }
6482 
6483 static const struct kset_uevent_ops scx_uevent_ops = {
6484 	.uevent = scx_uevent,
6485 };
6486 
6487 /*
6488  * Used by sched_fork() and __setscheduler_class() to pick the matching
6489  * sched_class. dl/rt are already handled.
6490  */
6491 bool task_should_scx(int policy)
6492 {
6493 	/* if disabled, nothing should be on it */
6494 	if (!scx_enabled())
6495 		return false;
6496 
6497 	/*
6498 	 * static_branch_enable(&__scx_enabled) patches call sites one by one.
6499 	 * Wait until all sites are patched before routing tasks to SCX, so
6500 	 * __schedule() never sees !scx_enabled() when a task is on SCX. Pairs
6501 	 * with smp_store_release() in scx_root_enable_workfn().
6502 	 */
6503 	if (unlikely(!smp_load_acquire(&scx_task_switch_enabled)))
6504 		return false;
6505 
6506 	/* scx is taking over all SCHED_OTHER and SCHED_EXT tasks */
6507 	if (READ_ONCE(scx_switching_all))
6508 		return true;
6509 
6510 	/*
6511 	 * scx is tearing down - keep new SCHED_EXT tasks out.
6512 	 *
6513 	 * Must come after scx_switching_all test, which serves as a proxy
6514 	 * for __scx_switched_all. While __scx_switched_all is set, we must
6515 	 * return true via the branch above: a fork routed to fair would
6516 	 * stall because next_active_class() skips fair.
6517 	 *
6518 	 * This can develop into a deadlock - scx holds scx_enable_mutex across
6519 	 * kthread_create() in scx_alloc_and_add_sched(); if the new kthread is
6520 	 * the stalled task, the disable path can never grab the mutex to clear
6521 	 * scx_switching_all.
6522 	 */
6523 	if (unlikely(scx_enable_state() == SCX_DISABLING))
6524 		return false;
6525 
6526 	return policy == SCHED_EXT;
6527 }
6528 
6529 bool scx_allow_ttwu_queue(const struct task_struct *p)
6530 {
6531 	struct scx_sched *sch;
6532 
6533 	if (!scx_enabled())
6534 		return true;
6535 
6536 	sch = scx_task_sched(p);
6537 	if (unlikely(!sch))
6538 		return true;
6539 
6540 	if (sch->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP)
6541 		return true;
6542 
6543 	if (unlikely(p->sched_class != &ext_sched_class))
6544 		return true;
6545 
6546 	return false;
6547 }
6548 
6549 /**
6550  * handle_lockup - sched_ext common lockup handler
6551  * @exit_cpu: CPU to record in exit_info. Pass the stalled/hung CPU, not current.
6552  * @fmt: format string
6553  *
6554  * Called on system stall or lockup condition and initiates abort of sched_ext
6555  * if enabled, which may resolve the reported lockup.
6556  *
6557  * Returns %true if sched_ext is enabled and abort was initiated, which may
6558  * resolve the lockup. %false if sched_ext is not enabled or abort was already
6559  * initiated by someone else.
6560  */
6561 static __printf(2, 3) bool handle_lockup(int exit_cpu, const char *fmt, ...)
6562 {
6563 	struct scx_sched *sch;
6564 	va_list args;
6565 	bool ret;
6566 
6567 	guard(rcu)();
6568 
6569 	sch = rcu_dereference(scx_root);
6570 	if (unlikely(!sch))
6571 		return false;
6572 
6573 	switch (scx_enable_state()) {
6574 	case SCX_ENABLING:
6575 	case SCX_ENABLED:
6576 		va_start(args, fmt);
6577 		ret = scx_vexit(sch, SCX_EXIT_ERROR, 0, exit_cpu, fmt, args);
6578 		va_end(args);
6579 		return ret;
6580 	default:
6581 		return false;
6582 	}
6583 }
6584 
6585 /**
6586  * scx_rcu_cpu_stall - sched_ext RCU CPU stall handler
6587  * @stalled_mask: bit mask of stalled CPUs
6588  *
6589  * While there are various reasons why RCU CPU stalls can occur on a system
6590  * that may not be caused by the current BPF scheduler, try kicking out the
6591  * current scheduler in an attempt to recover the system to a good state before
6592  * issuing panics.
6593  *
6594  * Returns %true if sched_ext is enabled and abort was initiated, which may
6595  * resolve the reported RCU stall. %false if sched_ext is not enabled or someone
6596  * else already initiated abort.
6597  */
6598 bool scx_rcu_cpu_stall(const struct cpumask *stalled_mask)
6599 {
6600 	struct scx_sched *sch;
6601 	struct scx_exit_info *ei;
6602 	int exit_cpu;
6603 
6604 	guard(rcu)();
6605 
6606 	sch = rcu_dereference(scx_root);
6607 	if (unlikely(!sch))
6608 		return false;
6609 
6610 	switch (scx_enable_state()) {
6611 	case SCX_ENABLING:
6612 	case SCX_ENABLED:
6613 		break;
6614 	default:
6615 		return false;
6616 	}
6617 
6618 	exit_cpu = cpumask_empty(stalled_mask) ? -1 : (int)cpumask_first(stalled_mask);
6619 	ei = sch->exit_info;
6620 
6621 	guard(preempt)();
6622 
6623 	if (!scx_claim_exit(sch, SCX_EXIT_ERROR))
6624 		return false;
6625 
6626 #ifdef CONFIG_STACKTRACE
6627 	ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
6628 #endif
6629 	scnprintf(ei->msg, SCX_EXIT_MSG_LEN, "RCU CPU stall on CPUs (%*pbl)",
6630 		  cpumask_pr_args(stalled_mask));
6631 	ei->kind = SCX_EXIT_ERROR;
6632 	ei->reason = scx_exit_reason(SCX_EXIT_ERROR);
6633 	ei->exit_cpu = exit_cpu;
6634 	cpumask_copy(sch->stall_cpus, stalled_mask);
6635 
6636 	irq_work_queue(&sch->disable_irq_work);
6637 	return true;
6638 }
6639 
6640 /**
6641  * scx_softlockup - sched_ext softlockup handler
6642  * @dur_s: number of seconds of CPU stuck due to soft lockup
6643  *
6644  * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can
6645  * live-lock the system by making many CPUs target the same DSQ to the point
6646  * where soft-lockup detection triggers. This function is called from
6647  * soft-lockup watchdog when the triggering point is close and tries to unjam
6648  * the system and aborting the BPF scheduler.
6649  */
6650 void scx_softlockup(u32 dur_s)
6651 {
6652 	int cpu = smp_processor_id();
6653 
6654 	if (!handle_lockup(cpu, "soft lockup - CPU %d stuck for %us", cpu, dur_s))
6655 		return;
6656 
6657 	printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU %d stuck for %us, disabling BPF scheduler\n",
6658 			cpu, dur_s);
6659 }
6660 
6661 /**
6662  * scx_hardlockup - sched_ext hardlockup handler
6663  * @cpu: the target CPU
6664  *
6665  * A poorly behaving BPF scheduler can trigger hard lockup by e.g. putting
6666  * numerous affinitized tasks in a single queue and directing all CPUs at it.
6667  * Try kicking out the current scheduler in an attempt to recover the system to
6668  * a good state before taking more drastic actions.
6669  *
6670  * Called from NMI. Aborting the scheduler sets ->aborting throughout the
6671  * hierarchy before returning, which is what breaks the dispatch-path live-locks
6672  * that can hard-lock CPUs.
6673  *
6674  * Returns %true if sched_ext is enabled and abort was initiated, which may
6675  * resolve the lockup. %false if sched_ext is not enabled or abort was already
6676  * initiated by someone else.
6677  */
6678 bool scx_hardlockup(int cpu)
6679 {
6680 	if (!handle_lockup(cpu, "hard lockup - CPU %d", cpu))
6681 		return false;
6682 
6683 	printk_deferred(KERN_ERR "sched_ext: Hard lockup - CPU %d, disabling BPF scheduler\n",
6684 			cpu);
6685 	return true;
6686 }
6687 
6688 /**
6689  * bypass_lb_reenq_home - Reenqueue a task at its home from the balancer
6690  * @rq: @p's home rq, locked
6691  * @p: task off any DSQ, taken from the bypass DSQ of @dsq_cpu
6692  * @dsq_cpu: cpu whose bypass DSQ gave up @p
6693  *
6694  * @p came off the bypass DSQ of @dsq_cpu with no donee able to take it. A drain
6695  * sends a migration-disabled @p here unless the donee picked for it is its
6696  * home, as every other cpu refuses it. The enqueue sends @p to rescue when the
6697  * host lacks %SCX_CAP_BASE at home and rescue is enabled, and to the home's
6698  * bypass DSQ otherwise. When @p must run at home, migration-disabled or with a
6699  * migration pending, and the host lacks BASE there, it is admitted to the
6700  * home's local DSQ in either case, see bypass_enq_target_dsq(). No DSQ lock may
6701  * be held, as the enqueue takes one.
6702  */
6703 static void bypass_lb_reenq_home(struct rq *rq, struct task_struct *p, s32 dsq_cpu)
6704 {
6705 	lockdep_assert_rq_held(rq);
6706 
6707 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK);
6708 	p->scx.flags |= SCX_TASK_REENQ_CAP;
6709 	p->scx.reenq_reason_caps = SCX_CAP_BASE;
6710 	p->scx.reenq_reason_cid = __scx_cpu_to_cid(dsq_cpu);
6711 	scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
6712 }
6713 
6714 /**
6715  * bypass_lb_can_move - Test whether @p can move to the bypass DSQ of @donee
6716  * @sch: host sched whose bypass DSQs are balanced
6717  * @p: task on a bypass DSQ of @sch, homed anywhere
6718  * @donee: cpu whose bypass DSQ would receive @p, -1 for none
6719  *
6720  * @p's rq lock pins @p's affinity. Without it the answer is a hint. A task
6721  * whose donee is its own cpu can always run there, and
6722  * task_can_run_on_remote_rq() warns when asked about a task's own cpu.
6723  */
6724 static bool bypass_lb_can_move(struct scx_sched *sch, struct task_struct *p, s32 donee)
6725 {
6726 	return donee >= 0 && (donee == task_cpu(p) ||
6727 			      task_can_run_on_remote_rq(sch, p, cpu_rq(donee), false));
6728 }
6729 
6730 /**
6731  * bypass_lb_move - Move one task off a bypass DSQ for the balancer
6732  * @sch: host sched whose bypass DSQs are balanced
6733  * @donor_rq: rq of the cpu whose bypass DSQ gives up @p, locked
6734  * @donor_dsq: @sch's bypass DSQ on @donor_rq's cpu, locked
6735  * @p: task on @donor_dsq, homed anywhere
6736  * @donee: cpu whose bypass DSQ receives @p, -1 for none
6737  *
6738  * Take @p off @donor_dsq and insert it into the bypass DSQ of @donee. The
6739  * caller tests bypass_lb_can_move() without @p's rq lock for a task homed
6740  * elsewhere, and not at all for a drain, so the test is repeated here under
6741  * @p's rq lock. A task that fails it is not put back, as the host may no longer
6742  * consume @donor_dsq. bypass_lb_reenq_home() reenqueues it at its home instead.
6743  *
6744  * The insert and the reenqueue run under @p's rq lock. A task homed on
6745  * @donor_rq is dequeued in place. unlink_dsq_and_switch_rq_lock() takes one
6746  * homed elsewhere off and switches the rq lock from @donor_rq to its own. The
6747  * switch can lose to a dequeue, and @p then belongs to the dequeuer.
6748  *
6749  * @donor_rq and @donor_dsq are locked on entry and on return. @donor_dsq is
6750  * unlocked in between, and @donor_rq too while the lock is switched, so the
6751  * caller's walk must find its place in @donor_dsq again after the call.
6752  *
6753  * Return the cpu that received @p, or -1 if @p was lost to a dequeue.
6754  */
6755 static s32 bypass_lb_move(struct scx_sched *sch, struct rq *donor_rq,
6756 			  struct scx_dispatch_q *donor_dsq, struct task_struct *p, s32 donee)
6757 {
6758 	struct rq *rq = task_rq(p);
6759 	s32 ret;
6760 
6761 	lockdep_assert_rq_held(donor_rq);
6762 	lockdep_assert_held(&donor_dsq->lock);
6763 
6764 	if (rq == donor_rq) {
6765 		scx_wait_dispatching(p);
6766 		dispatch_dequeue_locked(p, donor_dsq);
6767 		raw_spin_unlock(&donor_dsq->lock);
6768 	} else if (!unlink_dsq_and_switch_rq_lock(p, donor_dsq, donor_rq, rq)) {
6769 		/* lost to a dequeue, @p is the dequeuer's now */
6770 		ret = -1;
6771 		goto out;
6772 	}
6773 
6774 	if (bypass_lb_can_move(sch, p, donee)) {
6775 		scx_dispatch_enqueue(sch, rq, scx_bypass_dsq(sch, donee), p, 0, 0, 0);
6776 		ret = donee;
6777 	} else {
6778 		/*
6779 		 * No donee, or @p can't run on it. Reenqueue @p at home
6780 		 * instead, see bypass_lb_reenq_home().
6781 		 */
6782 		bypass_lb_reenq_home(rq, p, cpu_of(donor_rq));
6783 		ret = cpu_of(rq);
6784 	}
6785 out:
6786 	if (rq != donor_rq)
6787 		switch_rq_lock(rq, donor_rq);
6788 	raw_spin_lock(&donor_dsq->lock);
6789 	return ret;
6790 }
6791 
6792 static u32 bypass_lb_cpu(struct scx_sched *sch, s32 donor,
6793 			 struct cpumask *donee_mask, struct cpumask *resched_mask,
6794 			 u32 nr_donor_target, u32 nr_donee_target)
6795 {
6796 	struct rq *donor_rq = cpu_rq(donor);
6797 	struct scx_dispatch_q *donor_dsq = scx_bypass_dsq(sch, donor);
6798 	struct task_struct *p, *n;
6799 	struct scx_dsq_list_node cursor = INIT_DSQ_LIST_CURSOR(cursor, donor_dsq, 0);
6800 	s32 delta = READ_ONCE(donor_dsq->nr) - nr_donor_target;
6801 	u32 nr_balanced = 0, min_delta_us;
6802 
6803 	/*
6804 	 * All we want to guarantee is reasonable forward progress. No reason to
6805 	 * fine tune. Assuming every task on @donor_dsq runs their full slice,
6806 	 * consider offloading iff the total queued duration is over the
6807 	 * threshold. A zero target is a drain and empties the DSQ regardless.
6808 	 */
6809 	min_delta_us = READ_ONCE(scx_bypass_lb_intv_us) / SCX_BYPASS_LB_MIN_DELTA_DIV;
6810 	if (nr_donor_target &&
6811 	    delta < DIV_ROUND_UP(min_delta_us, READ_ONCE(scx_slice_bypass_us)))
6812 		return 0;
6813 
6814 	raw_spin_rq_lock_irq(donor_rq);
6815 	raw_spin_lock(&donor_dsq->lock);
6816 	/* bound the walk to the tasks queued now, see the seq test below */
6817 	cursor.priv = donor_dsq->seq;
6818 	list_add(&cursor.node, &donor_dsq->list);
6819 resume:
6820 	n = container_of(&cursor, struct task_struct, scx.dsq_list);
6821 	n = nldsq_next_task(donor_dsq, n, false);
6822 
6823 	while ((p = n)) {
6824 		s32 donee, cpu;
6825 
6826 		n = nldsq_next_task(donor_dsq, n, false);
6827 
6828 		if (donor_dsq->nr <= nr_donor_target)
6829 			break;
6830 
6831 		/*
6832 		 * Without a donee, a balancing donor has nothing to do. A drain
6833 		 * still sends its tasks home.
6834 		 */
6835 		if (cpumask_empty(donee_mask) && nr_donor_target)
6836 			break;
6837 
6838 		/*
6839 		 * A task queued after the walk began, including one the walk
6840 		 * itself reenqueued, is left for the next pass.
6841 		 */
6842 		if (u32_before(cursor.priv, p->scx.dsq_seq))
6843 			continue;
6844 
6845 		/*
6846 		 * A balancing donor leaves a task that can't move where it is.
6847 		 * A home reenqueue would push one homed on the donor to the
6848 		 * back of @donor_dsq on every pass. A drain sends it home.
6849 		 */
6850 		donee = cpumask_any_and_distribute(donee_mask, p->cpus_ptr);
6851 		if (donee >= nr_cpu_ids)
6852 			donee = -1;
6853 		if (nr_donor_target && !bypass_lb_can_move(sch, p, donee))
6854 			continue;
6855 
6856 		/*
6857 		 * The move drops @donor_dsq's lock, and the rq lock too when
6858 		 * @p is homed elsewhere. The donor cpu's dispatch and its
6859 		 * enqueuers can reach @donor_dsq then. Park the cursor behind
6860 		 * @p and resume from it afterwards. The seq test above keeps a
6861 		 * task enqueued meanwhile out of the pass.
6862 		 */
6863 		list_move(&cursor.node, &p->scx.dsq_list.node);
6864 		cpu = bypass_lb_move(sch, donor_rq, donor_dsq, p, donee);
6865 		if (cpu >= 0) {
6866 			/*
6867 			 * @cpu might have been idle and need to be woken up.
6868 			 * No need to be clever. Reschedule every cpu that
6869 			 * receives tasks.
6870 			 */
6871 			cpumask_set_cpu(cpu, resched_mask);
6872 
6873 			if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) >= nr_donee_target)
6874 				cpumask_clear_cpu(cpu, donee_mask);
6875 
6876 			/*
6877 			 * The rq lock is held across the walk, not cycled per
6878 			 * move. @donor_dsq can be very long and contended, and
6879 			 * the rq lock is what keeps its consumer and enqueuers
6880 			 * away while the walk cycles the DSQ lock. The rare
6881 			 * move of a task homed elsewhere does switch it away,
6882 			 * see the cursor comment above. The walk can still take
6883 			 * a while, so let the cpu breathe every so often.
6884 			 */
6885 			if (!(++nr_balanced % SCX_BYPASS_LB_BATCH)) {
6886 				raw_spin_unlock(&donor_dsq->lock);
6887 				scx_rq_lock_drop(donor_rq);
6888 				raw_spin_rq_unlock_irq(donor_rq);
6889 				cpu_relax();
6890 				raw_spin_rq_lock_irq(donor_rq);
6891 				raw_spin_lock(&donor_dsq->lock);
6892 			}
6893 		}
6894 		goto resume;
6895 	}
6896 
6897 	list_del_init(&cursor.node);
6898 	raw_spin_unlock(&donor_dsq->lock);
6899 	scx_rq_lock_drop(donor_rq);
6900 	raw_spin_rq_unlock_irq(donor_rq);
6901 
6902 	return nr_balanced;
6903 }
6904 
6905 static void bypass_lb_node(struct scx_sched *sch, int node)
6906 {
6907 	const struct cpumask *node_mask = cpumask_of_node(node);
6908 	struct cpumask *donee_mask = sch->bypass_lb_donee_cpumask;
6909 	struct cpumask *resched_mask = sch->bypass_lb_resched_cpumask;
6910 	u32 intv_us = READ_ONCE(scx_bypass_lb_intv_us);
6911 	u32 nr_tasks = 0, nr_cpus = 0, nr_balanced = 0;
6912 	u32 nr_target, nr_donor_target;
6913 	u32 before_min = U32_MAX, before_max = 0;
6914 	u32 after_min = U32_MAX, after_max = 0;
6915 	int cpu;
6916 
6917 	/* count the target tasks and CPUs */
6918 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
6919 		u32 nr = READ_ONCE(scx_bypass_dsq(sch, cpu)->nr);
6920 
6921 		nr_tasks += nr;
6922 		/* only a cpu whose dispatch consumes its DSQ is capacity */
6923 		if (!scx_missing_caps(sch, cpu, SCX_CAP_BASE))
6924 			nr_cpus++;
6925 
6926 		before_min = min(nr, before_min);
6927 		before_max = max(nr, before_max);
6928 	}
6929 
6930 	if (!nr_tasks)
6931 		return;
6932 
6933 	/*
6934 	 * We don't want CPUs to have more than $nr_donor_target tasks and
6935 	 * balancing to fill donee CPUs up to $nr_target. Once targets are
6936 	 * calculated, find the donee CPUs.
6937 	 */
6938 	nr_target = nr_cpus ? DIV_ROUND_UP(nr_tasks, nr_cpus) : 0;
6939 	nr_donor_target = DIV_ROUND_UP(nr_target * SCX_BYPASS_LB_DONOR_PCT, 100);
6940 
6941 	cpumask_clear(donee_mask);
6942 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
6943 		/* a donee's DSQ is consumed only if @sch holds %SCX_CAP_BASE */
6944 		if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) < nr_target &&
6945 		    !scx_missing_caps(sch, cpu, SCX_CAP_BASE))
6946 			cpumask_set_cpu(cpu, donee_mask);
6947 	}
6948 
6949 	/*
6950 	 * Offload the !donee cpus. A cpu where the host lost %SCX_CAP_BASE no
6951 	 * longer consumes its DSQ. Drain it as a donor with a target of zero. A
6952 	 * zero interval disables the balancing, not the drain.
6953 	 */
6954 	cpumask_clear(resched_mask);
6955 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
6956 		u32 target = nr_donor_target;
6957 
6958 		if (unlikely(scx_missing_caps(sch, cpu, SCX_CAP_BASE))) {
6959 			/* the mask may predate the loss, keep this cpu out */
6960 			cpumask_clear_cpu(cpu, donee_mask);
6961 			target = 0;
6962 		} else if (!intv_us || cpumask_empty(donee_mask) ||
6963 			   cpumask_test_cpu(cpu, donee_mask)) {
6964 			continue;
6965 		}
6966 		if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) <= target)
6967 			continue;
6968 
6969 		nr_balanced += bypass_lb_cpu(sch, cpu, donee_mask, resched_mask,
6970 					     target, nr_target);
6971 	}
6972 
6973 	for_each_cpu(cpu, resched_mask)
6974 		resched_cpu(cpu);
6975 
6976 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
6977 		u32 nr = READ_ONCE(scx_bypass_dsq(sch, cpu)->nr);
6978 
6979 		after_min = min(nr, after_min);
6980 		after_max = max(nr, after_max);
6981 
6982 	}
6983 
6984 	trace_sched_ext_bypass_lb(node, nr_cpus, nr_tasks, nr_balanced,
6985 				  before_min, before_max, after_min, after_max);
6986 }
6987 
6988 /*
6989  * In bypass mode, all tasks are put on the per-CPU bypass DSQs. If the machine
6990  * is over-saturated and the BPF scheduler skewed tasks into few CPUs, some
6991  * bypass DSQs can be overloaded. If there are enough tasks to saturate other
6992  * lightly loaded CPUs, such imbalance can lead to very high execution latency
6993  * on the overloaded CPUs and thus to hung tasks and RCU stalls. To avoid such
6994  * outcomes, a simple load balancing mechanism is implemented by the following
6995  * timer which runs periodically while bypass mode is in effect.
6996  */
6997 static void scx_bypass_lb_timerfn(struct timer_list *timer)
6998 {
6999 	struct scx_sched *sch = container_of(timer, struct scx_sched, bypass_lb_timer);
7000 	int node;
7001 	u32 intv_us;
7002 
7003 	if (!scx_bypass_dsp_enabled(sch))
7004 		return;
7005 
7006 	for_each_node_with_cpus(node)
7007 		bypass_lb_node(sch, node);
7008 
7009 	/*
7010 	 * A kick during this run can leave the timer pending at now, see
7011 	 * scx_bypass_lb_kick(). timer_reduce() only brings the expiry forward,
7012 	 * so that kick is kept.
7013 	 */
7014 	intv_us = READ_ONCE(scx_bypass_lb_intv_us);
7015 	if (intv_us)
7016 		timer_reduce(timer, jiffies + usecs_to_jiffies(intv_us));
7017 }
7018 
7019 /**
7020  * scx_bypass_lb_kick - Run the bypass load balancer now
7021  * @sch: sched that lost %SCX_CAP_BASE on a cpu
7022  *
7023  * @sch no longer consumes its bypass DSQ on that cpu. Have the balancer drain
7024  * it without waiting for the next interval, see bypass_lb_node(). A loss during
7025  * a run leaves the timer pending at now, and the run that follows sees it.
7026  */
7027 void scx_bypass_lb_kick(struct scx_sched *sch)
7028 {
7029 	if (scx_bypass_dsp_enabled(sch))
7030 		mod_timer(&sch->bypass_lb_timer, jiffies);
7031 }
7032 
7033 static bool inc_bypass_depth(struct scx_sched *sch)
7034 {
7035 	lockdep_assert_held(&scx_bypass_lock);
7036 
7037 	WARN_ON_ONCE(sch->bypass_depth < 0);
7038 	WRITE_ONCE(sch->bypass_depth, sch->bypass_depth + 1);
7039 	if (sch->bypass_depth != 1)
7040 		return false;
7041 
7042 	WRITE_ONCE(sch->slice_dfl, READ_ONCE(scx_slice_bypass_us) * NSEC_PER_USEC);
7043 	sch->bypass_timestamp = ktime_get_ns();
7044 	scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1);
7045 	return true;
7046 }
7047 
7048 static bool dec_bypass_depth(struct scx_sched *sch)
7049 {
7050 	lockdep_assert_held(&scx_bypass_lock);
7051 
7052 	WARN_ON_ONCE(sch->bypass_depth < 1);
7053 	WRITE_ONCE(sch->bypass_depth, sch->bypass_depth - 1);
7054 	if (sch->bypass_depth != 0)
7055 		return false;
7056 
7057 	WRITE_ONCE(sch->slice_dfl, SCX_SLICE_DFL);
7058 	scx_add_event(sch, SCX_EV_BYPASS_DURATION,
7059 		      ktime_get_ns() - sch->bypass_timestamp);
7060 	return true;
7061 }
7062 
7063 static void enable_bypass_dsp(struct scx_sched *sch)
7064 {
7065 	struct scx_sched *host = scx_parent(sch) ?: sch;
7066 	u32 intv_us = READ_ONCE(scx_bypass_lb_intv_us);
7067 	s32 ret;
7068 
7069 	/*
7070 	 * @sch->bypass_depth transitioning from 0 to 1 triggers enabling.
7071 	 * Shouldn't stagger.
7072 	 */
7073 	if (WARN_ON_ONCE(test_and_set_bit(0, &sch->bypass_dsp_claim)))
7074 		return;
7075 
7076 	/*
7077 	 * When a sub-sched bypasses, its tasks are queued on the bypass DSQs of
7078 	 * the nearest non-bypassing ancestor or root. The parent hosts them
7079 	 * unless it is bypassing too. Then they sit further up and the parent
7080 	 * consumes only its own bypass DSQs, empty until it leaves bypass and
7081 	 * becomes the host. Either way the nearest non-bypassing ancestor or
7082 	 * root has bypass dispatch enabled while a descendant is bypassing,
7083 	 * which is all that's required.
7084 	 *
7085 	 * scx_bypass_dsp_enabled() test is used to determine whether to enter
7086 	 * the bypass dispatch handling path from both bypassing and hosting
7087 	 * scheds. Bump enable depth on both @sch and bypass dispatch host.
7088 	 */
7089 	ret = atomic_inc_return(&sch->bypass_dsp_enable_depth);
7090 	WARN_ON_ONCE(ret <= 0);
7091 
7092 	if (host != sch) {
7093 		ret = atomic_inc_return(&host->bypass_dsp_enable_depth);
7094 		WARN_ON_ONCE(ret <= 0);
7095 	}
7096 
7097 	/*
7098 	 * The LB timer will stop running if bypass dispatch is disabled. Start
7099 	 * after enabling bypass dispatch. A kick from a BASE loss can have set
7100 	 * the timer to expire now in the meantime, see scx_bypass_lb_kick().
7101 	 * timer_reduce() keeps that expiry.
7102 	 */
7103 	if (intv_us)
7104 		timer_reduce(&host->bypass_lb_timer, jiffies + usecs_to_jiffies(intv_us));
7105 }
7106 
7107 /* may be called without holding scx_bypass_lock */
7108 void scx_disable_bypass_dsp(struct scx_sched *sch)
7109 {
7110 	s32 ret;
7111 
7112 	if (!test_and_clear_bit(0, &sch->bypass_dsp_claim))
7113 		return;
7114 
7115 	ret = atomic_dec_return(&sch->bypass_dsp_enable_depth);
7116 	WARN_ON_ONCE(ret < 0);
7117 
7118 	if (scx_parent(sch)) {
7119 		ret = atomic_dec_return(&scx_parent(sch)->bypass_dsp_enable_depth);
7120 		WARN_ON_ONCE(ret < 0);
7121 	}
7122 }
7123 
7124 /**
7125  * unbypass_renotify_idle - Arm an idle re-notify for a sched leaving bypass
7126  * @rq: rq of the cpu leaving bypass
7127  * @pos: scheduler that just left bypass on @rq's cpu
7128  * @pcpu: @pos's per-cpu state for @rq's cpu
7129  *
7130  * A sched leaving bypass is owed the ops.update_idle() calls suppressed while
7131  * bypassing. A cpu that goes idle during the bypass window and stays idle won't
7132  * produce a notification. Arm a re-notify that scx_bypass()'s resched flushes
7133  * on the next idle pick.
7134  *
7135  * An acute case is ops.sub_attach(). If the parent grants the child cids while
7136  * attaching, when attach is complete and bypass is lifted, the child may hold
7137  * idle cids it never saw go idle.
7138  *
7139  * The root is no exception as bypass suppresses its notifications the same way.
7140  * However, the root uses a separate per-rq flag so its re-notify keeps working
7141  * even when !CONFIG_EXT_SUB_SCHED.
7142  */
7143 static void unbypass_renotify_idle(struct rq *rq, struct scx_sched *pos,
7144 				   struct scx_sched_pcpu *pcpu)
7145 {
7146 	if (!pos->level) {
7147 		rq->scx.flags |= SCX_RQ_ROOT_IDLE_RENOTIFY;
7148 		return;
7149 	}
7150 #ifdef CONFIG_EXT_SUB_SCHED
7151 	pcpu->idle_renotify = true;
7152 	rq->scx.flags |= SCX_RQ_SUB_IDLE_RENOTIFY;
7153 #endif
7154 }
7155 
7156 /**
7157  * scx_bypass - [Un]bypass scx_ops and guarantee forward progress
7158  * @sch: sched to bypass
7159  * @bypass: true for bypass, false for unbypass
7160  *
7161  * Bypassing guarantees that all runnable tasks make forward progress without
7162  * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might
7163  * be held by tasks that the BPF scheduler is forgetting to run, which
7164  * unfortunately also excludes toggling the static branches.
7165  *
7166  * Let's work around by overriding a couple ops and modifying behaviors based on
7167  * the DISABLING state and then cycling the queued tasks through dequeue/enqueue
7168  * to force global FIFO scheduling.
7169  *
7170  * - ops.select_cpu() is ignored and the default select_cpu() is used.
7171  *
7172  * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order.
7173  *   %SCX_OPS_ENQ_LAST is also ignored.
7174  *
7175  * - ops.dispatch() is ignored.
7176  *
7177  * - ops.sub_ecaps_updated() and ops.sub_child_ecaps_updated() are still called.
7178  *   The bypassed tasks are on the bypass DSQs, under rescue or admitted to a
7179  *   local DSQ, out of their reach.
7180  *
7181  * - dispatch_one() expires prev's slice before its keep test as the slice can't
7182  *   be trusted. Each tick does the same and rotates the running task to the
7183  *   tail of the queue. A kernel slice is left alone, see
7184  *   %SCX_TASK_KERNEL_SLICE.
7185  *
7186  * - pick_next_task() suppresses zero slice warning.
7187  *
7188  * - scx_kick_cpu() is disabled to avoid irq_work malfunction during PM
7189  *   operations.
7190  *
7191  * - scx_prio_less() reverts to the default runnable_at order.
7192  */
7193 void scx_bypass(struct scx_sched *sch, bool bypass)
7194 {
7195 	struct scx_sched *pos;
7196 	unsigned long flags;
7197 	int cpu;
7198 	bool changed;
7199 
7200 	raw_spin_lock_irqsave(&scx_bypass_lock, flags);
7201 
7202 	if (bypass) {
7203 		changed = inc_bypass_depth(sch);
7204 		if (changed)
7205 			enable_bypass_dsp(sch);
7206 	} else {
7207 		changed = dec_bypass_depth(sch);
7208 	}
7209 
7210 	/*
7211 	 * Bypass state is propagated to all descendants - an scx_sched bypasses
7212 	 * if itself or any of its ancestors are in bypass mode. A descendant's
7213 	 * depth is the sum of its own bypasses and its ancestors', so every
7214 	 * call propagates whether or not @sch changed state. The descendants'
7215 	 * claims are released below with @sch's, after their tasks have moved.
7216 	 */
7217 	raw_spin_lock(&scx_sched_lock);
7218 	scx_for_each_descendant_pre(pos, sch) {
7219 		if (pos == sch)
7220 			continue;
7221 		if (bypass) {
7222 			if (inc_bypass_depth(pos))
7223 				enable_bypass_dsp(pos);
7224 		} else {
7225 			dec_bypass_depth(pos);
7226 		}
7227 	}
7228 	raw_spin_unlock(&scx_sched_lock);
7229 
7230 	/*
7231 	 * A descendant's depth is at least @sch's, so no bypass state changed
7232 	 * unless @sch's did.
7233 	 */
7234 	if (!changed)
7235 		goto unlock;
7236 
7237 	/*
7238 	 * No task property is changing. We just need to make sure all currently
7239 	 * queued tasks are re-queued according to the new scx_bypassing()
7240 	 * state. As an optimization, walk each rq's runnable_list instead of
7241 	 * the scx_tasks list.
7242 	 *
7243 	 * This function can't trust the scheduler and thus can't use
7244 	 * cpus_read_lock(). Walk all possible CPUs instead of online.
7245 	 */
7246 	for_each_possible_cpu(cpu) {
7247 		struct rq *rq = cpu_rq(cpu);
7248 		struct task_struct *p, *n;
7249 
7250 		raw_spin_rq_lock(rq);
7251 		raw_spin_lock(&scx_sched_lock);
7252 
7253 		scx_for_each_descendant_pre(pos, sch) {
7254 			struct scx_sched_pcpu *pcpu = per_cpu_ptr(pos->pcpu, cpu);
7255 			bool was_bypassing = pcpu->flags & SCX_SCHED_PCPU_BYPASSING;
7256 
7257 			if (pos->bypass_depth) {
7258 				pcpu->flags |= SCX_SCHED_PCPU_BYPASSING;
7259 			} else {
7260 				pcpu->flags &= ~SCX_SCHED_PCPU_BYPASSING;
7261 				if (was_bypassing)
7262 					unbypass_renotify_idle(rq, pos, pcpu);
7263 			}
7264 		}
7265 
7266 		raw_spin_unlock(&scx_sched_lock);
7267 
7268 		/*
7269 		 * We need to guarantee that no tasks are on the BPF scheduler
7270 		 * while bypassing. Either we see enabled or the enable path
7271 		 * sees scx_bypassing() before moving tasks to SCX.
7272 		 */
7273 		if (!scx_enabled()) {
7274 			scx_rq_lock_drop(rq);
7275 			raw_spin_rq_unlock(rq);
7276 			continue;
7277 		}
7278 
7279 		/*
7280 		 * Bypass trumps protection. Cycling the queued tasks below
7281 		 * clears theirs. The current donor isn't on the runnable list,
7282 		 * so strip its protection here.
7283 		 *
7284 		 * When bypass lifts, the current donor keeps running on its
7285 		 * slice without a cap check. Evict it if it can't stay on the
7286 		 * cpu.
7287 		 */
7288 		p = rq->donor;
7289 		if (p->sched_class == &ext_sched_class &&
7290 		    scx_is_descendant(scx_task_sched(p), sch)) {
7291 			if (bypass)
7292 				scx_task_slice_ended(rq, p);
7293 			else if (!scx_task_can_stay_on_cpu(rq, p))
7294 				expire_task_slice(p);
7295 		}
7296 
7297 		/*
7298 		 * The use of list_for_each_entry_safe_reverse() is required
7299 		 * because each task is going to be removed from and added back
7300 		 * to the runnable_list during iteration. Because they're added
7301 		 * to the tail of the list, safe reverse iteration can still
7302 		 * visit all nodes.
7303 		 */
7304 		list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list,
7305 						 scx.runnable_node) {
7306 			struct scx_sched *owner = scx_task_sched(p);
7307 
7308 			if (!scx_is_descendant(owner, sch))
7309 				continue;
7310 
7311 			/* cycling deq/enq is enough, see the function comment */
7312 			scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
7313 				/*
7314 				 * The requeue can change the sched running @p,
7315 				 * and the watchdog counts @p's wait against
7316 				 * that sched. Restart the wait unless @owner is
7317 				 * the root, which runs its own tasks bypassing
7318 				 * or not.
7319 				 *
7320 				 * A dispatch in flight writes p->scx.flags
7321 				 * without @p's rq lock. The dequeue waits it
7322 				 * out, so set the flag after it.
7323 				 */
7324 				if (scx_parent(owner))
7325 					p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
7326 			}
7327 		}
7328 
7329 		/* resched to restore ticks and idle state */
7330 		if (cpu_online(cpu) || cpu == smp_processor_id())
7331 			resched_curr(rq);
7332 
7333 		scx_rq_lock_drop(rq);
7334 		raw_spin_rq_unlock(rq);
7335 	}
7336 
7337 	/* disarming must come after moving all tasks out of the bypass DSQs */
7338 	if (!bypass) {
7339 		guard(raw_spinlock)(&scx_sched_lock);
7340 		scx_for_each_descendant_pre(pos, sch)
7341 			if (!pos->bypass_depth)
7342 				scx_disable_bypass_dsp(pos);
7343 	}
7344 unlock:
7345 	raw_spin_unlock_irqrestore(&scx_bypass_lock, flags);
7346 }
7347 
7348 static void free_exit_info(struct scx_exit_info *ei)
7349 {
7350 	kvfree(ei->dump);
7351 	kfree(ei->msg);
7352 	kfree(ei->bt);
7353 	kfree(ei);
7354 }
7355 
7356 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
7357 {
7358 	struct scx_exit_info *ei;
7359 
7360 	ei = kzalloc_obj(*ei);
7361 	if (!ei)
7362 		return NULL;
7363 
7364 	ei->exit_cpu = -1;
7365 	ei->bt = kzalloc_objs(ei->bt[0], SCX_EXIT_BT_LEN);
7366 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
7367 	ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL);
7368 
7369 	if (!ei->bt || !ei->msg || !ei->dump) {
7370 		free_exit_info(ei);
7371 		return NULL;
7372 	}
7373 
7374 	return ei;
7375 }
7376 
7377 static const char *scx_exit_reason(enum scx_exit_kind kind)
7378 {
7379 	switch (kind) {
7380 	case SCX_EXIT_UNREG:
7381 		return "unregistered from user space";
7382 	case SCX_EXIT_UNREG_BPF:
7383 		return "unregistered from BPF";
7384 	case SCX_EXIT_UNREG_KERN:
7385 		return "unregistered from the main kernel";
7386 	case SCX_EXIT_SYSRQ:
7387 		return "disabled by sysrq-S";
7388 	case SCX_EXIT_PARENT:
7389 		return "parent exiting";
7390 	case SCX_EXIT_PARENT_KILL:
7391 		return "killed by parent scheduler";
7392 	case SCX_EXIT_ERROR:
7393 		return "runtime error";
7394 	case SCX_EXIT_ERROR_BPF:
7395 		return "scx_bpf_error";
7396 	case SCX_EXIT_ERROR_STALL:
7397 		return "runnable task stall";
7398 	case SCX_EXIT_ERROR_REENQ:
7399 		return "reenqueue limit";
7400 	case SCX_EXIT_ERROR_RESCUE:
7401 		return "rescue bandwidth overload";
7402 	default:
7403 		return "<UNKNOWN>";
7404 	}
7405 }
7406 
7407 static void free_kick_syncs(void)
7408 {
7409 	int cpu;
7410 
7411 	for_each_possible_cpu(cpu) {
7412 		struct scx_kick_syncs __rcu **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
7413 		struct scx_kick_syncs *to_free;
7414 
7415 		/* flush the pending kick before freeing @ksyncs */
7416 		irq_work_sync(&cpu_rq(cpu)->scx.kick_cpus_irq_work);
7417 		to_free = rcu_replace_pointer(*ksyncs, NULL, true);
7418 		if (to_free)
7419 			kvfree_rcu(to_free, rcu);
7420 	}
7421 }
7422 
7423 static void refresh_watchdog(void)
7424 {
7425 	struct scx_sched *sch;
7426 	unsigned long intv = ULONG_MAX;
7427 
7428 	/* take the shortest timeout and use its half for watchdog interval */
7429 	rcu_read_lock();
7430 	list_for_each_entry_rcu(sch, &scx_sched_all, all)
7431 		intv = max(min(intv, sch->watchdog_timeout / 2), 1);
7432 	rcu_read_unlock();
7433 
7434 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
7435 	WRITE_ONCE(scx_watchdog_interval, intv);
7436 
7437 	if (intv < ULONG_MAX)
7438 		mod_delayed_work(system_dfl_wq, &scx_watchdog_work, intv);
7439 	else
7440 		cancel_delayed_work_sync(&scx_watchdog_work);
7441 }
7442 
7443 s32 scx_link_sched(struct scx_sched *sch)
7444 {
7445 	scoped_guard(raw_spinlock_irqsave, &scx_bypass_lock)	/* for the parent bypass check */
7446 	scoped_guard(raw_spinlock, &scx_sched_lock) {
7447 #ifdef CONFIG_EXT_SUB_SCHED
7448 		struct scx_sched *parent = scx_parent(sch);
7449 
7450 		if (parent) {
7451 			s32 ret;
7452 
7453 			/*
7454 			 * Bypass state is spread across per-cpu flags and a
7455 			 * depth count, so inheriting it is tricky and has no
7456 			 * valid use case. Refuse it.
7457 			 */
7458 			if (READ_ONCE(parent->bypass_depth)) {
7459 				scx_error(sch, "parent bypassing (%d)", -EBUSY);
7460 				return -EBUSY;
7461 			}
7462 
7463 			ret = rhashtable_lookup_insert_fast(&scx_sched_hash,
7464 					&sch->hash_node, scx_sched_hash_params);
7465 			if (ret) {
7466 				scx_error(sch, "failed to insert into scx_sched_hash (%d)",
7467 					  ret);
7468 				return ret;
7469 			}
7470 
7471 			list_add_tail_rcu(&sch->sibling, &parent->children);
7472 
7473 			/*
7474 			 * Pairs with the mb after the ->aborting assertion in
7475 			 * scx_claim_exit(). Either we see ->aborting and back
7476 			 * out, or the exit path sees us and exits us.
7477 			 */
7478 			smp_mb();
7479 			if (unlikely(READ_ONCE(parent->aborting))) {
7480 				rhashtable_remove_fast(&scx_sched_hash, &sch->hash_node,
7481 						       scx_sched_hash_params);
7482 				list_del_rcu(&sch->sibling);
7483 				scx_error(sch, "parent disabled (%d)", -ENOENT);
7484 				return -ENOENT;
7485 			}
7486 
7487 			sch->linked = true;
7488 		}
7489 #endif	/* CONFIG_EXT_SUB_SCHED */
7490 
7491 		list_add_tail_rcu(&sch->all, &scx_sched_all);
7492 	}
7493 
7494 	refresh_watchdog();
7495 	return 0;
7496 }
7497 
7498 void scx_unlink_sched(struct scx_sched *sch)
7499 {
7500 	scoped_guard(raw_spinlock_irq, &scx_sched_lock) {
7501 #ifdef CONFIG_EXT_SUB_SCHED
7502 		if (sch->linked) {
7503 			rhashtable_remove_fast(&scx_sched_hash, &sch->hash_node,
7504 					       scx_sched_hash_params);
7505 			list_del_rcu(&sch->sibling);
7506 			sch->linked = false;
7507 		}
7508 #endif	/* CONFIG_EXT_SUB_SCHED */
7509 		list_del_rcu(&sch->all);
7510 	}
7511 
7512 	refresh_watchdog();
7513 }
7514 
7515 /*
7516  * Called to disable future dumps and wait for in-progress one while disabling
7517  * @sch. Once @sch becomes empty during disable, there's no point in dumping it.
7518  * This prevents calling dump ops on a dead sch.
7519  */
7520 void scx_disable_dump(struct scx_sched *sch)
7521 {
7522 	guard(raw_spinlock_irqsave)(&scx_dump_lock);
7523 	sch->dump_disabled = true;
7524 }
7525 
7526 void scx_log_sched_disable(struct scx_sched *sch)
7527 {
7528 	struct scx_exit_info *ei = sch->exit_info;
7529 	const char *type = scx_parent(sch) ? "sub-scheduler" : "scheduler";
7530 
7531 	if (ei->kind >= SCX_EXIT_ERROR) {
7532 		pr_err("sched_ext: BPF %s \"%s\" disabled (%s)\n", type,
7533 		       sch->ops.name, ei->reason);
7534 
7535 		if (ei->msg[0] != '\0')
7536 			pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg);
7537 #ifdef CONFIG_STACKTRACE
7538 		stack_trace_print(ei->bt, ei->bt_len, 2);
7539 #endif
7540 	} else {
7541 		pr_info("sched_ext: BPF %s \"%s\" disabled (%s)\n", type,
7542 			sch->ops.name, ei->reason);
7543 	}
7544 }
7545 
7546 static void scx_root_disable(struct scx_sched *sch)
7547 {
7548 	struct scx_task_iter sti;
7549 	struct task_struct *p;
7550 	bool was_switched_all;
7551 	int cpu;
7552 
7553 	/* guarantee forward progress and wait for descendants to be disabled */
7554 	scx_bypass(sch, true);
7555 	drain_descendants(sch);
7556 
7557 	switch (scx_set_enable_state(SCX_DISABLING)) {
7558 	case SCX_DISABLING:
7559 		WARN_ONCE(true, "sched_ext: duplicate disabling instance?");
7560 		break;
7561 	case SCX_DISABLED:
7562 		pr_warn("sched_ext: ops error detected without ops (%s)\n",
7563 			sch->exit_info->msg);
7564 		WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
7565 		goto done;
7566 	default:
7567 		break;
7568 	}
7569 
7570 	/*
7571 	 * Here, every runnable task is guaranteed to make forward progress and
7572 	 * we can safely use blocking synchronization constructs. Actually
7573 	 * disable ops.
7574 	 */
7575 	mutex_lock(&scx_enable_mutex);
7576 
7577 	was_switched_all = scx_switched_all();
7578 
7579 	/*
7580 	 * Tasks fall back to fair from here on. Attach fair_server now, or an
7581 	 * RT task can starve them while we wait for RCU grace periods below.
7582 	 * If its bandwidth doesn't fit, the swap at the end attaches it.
7583 	 */
7584 	if (was_switched_all) {
7585 		for_each_possible_cpu(cpu) {
7586 			struct rq *rq = cpu_rq(cpu);
7587 
7588 			guard(rq_lock_irqsave)(rq);
7589 			update_rq_clock(rq);
7590 			dl_server_attach_bw(&rq->fair_server);
7591 		}
7592 	}
7593 
7594 	static_branch_disable(&__scx_switched_all);
7595 	WRITE_ONCE(scx_switching_all, false);
7596 	WRITE_ONCE(scx_task_switch_enabled, false);
7597 
7598 	/*
7599 	 * Shut down cgroup support before tasks so that the cgroup attach and
7600 	 * migration paths don't race against scx_disable_and_exit_task().
7601 	 */
7602 	scx_cgroup_lock();
7603 	scx_cgroup_enabled = false;
7604 	scx_cgroup_exit(sch);
7605 	scx_cgroup_unlock();
7606 
7607 	/*
7608 	 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones
7609 	 * must be switched out and exited synchronously.
7610 	 */
7611 	percpu_down_write(&scx_fork_rwsem);
7612 
7613 	scx_init_task_enabled = false;
7614 
7615 	scx_task_iter_start(&sti, NULL);
7616 	while ((p = scx_task_iter_next_locked(&sti))) {
7617 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
7618 		const struct sched_class *old_class = p->sched_class;
7619 		const struct sched_class *new_class = scx_setscheduler_class(p);
7620 
7621 		update_rq_clock(task_rq(p));
7622 
7623 		if (old_class != new_class)
7624 			queue_flags |= DEQUEUE_CLASS;
7625 
7626 		scoped_guard (sched_change, p, queue_flags) {
7627 			p->sched_class = new_class;
7628 		}
7629 
7630 		scx_disable_and_exit_task(scx_task_sched(p), p);
7631 	}
7632 	scx_task_iter_stop(&sti);
7633 
7634 	scx_disable_dump(sch);
7635 
7636 	scx_cgroup_lock();
7637 	set_cgroup_sched(sch_cgroup(sch), NULL);
7638 	scx_cgroup_unlock();
7639 
7640 	percpu_up_write(&scx_fork_rwsem);
7641 
7642 	/*
7643 	 * Re-balance the dl_server bandwidth reservations: detach ext_server
7644 	 * (no more sched_ext tasks) and attach fair_server if the attach
7645 	 * above failed.
7646 	 *
7647 	 * Unlike the enable path, this runs on a recovery path that cannot
7648 	 * fail, so we use dl_server_swap_bw() to atomically free ext_server's
7649 	 * bandwidth and reclaim it for fair_server under the same dl_b lock.
7650 	 *
7651 	 * The swap can still fail with -EBUSY if someone bumped ext_server's
7652 	 * runtime via debugfs between enable and disable; in that narrow case
7653 	 * both servers end up detached and we just WARN.
7654 	 */
7655 	for_each_possible_cpu(cpu) {
7656 		struct rq *rq = cpu_rq(cpu);
7657 
7658 		scoped_guard(rq_lock_irqsave, rq) {
7659 			update_rq_clock(rq);
7660 			if (was_switched_all) {
7661 				if (WARN_ON_ONCE(dl_server_swap_bw(&rq->ext_server,
7662 								   &rq->fair_server)))
7663 					pr_warn("failed to re-attach fair_server on CPU %d\n", cpu);
7664 			} else {
7665 				dl_server_detach_bw(&rq->ext_server);
7666 			}
7667 		}
7668 	}
7669 
7670 	scx_ops_cid_sched_updated_disable(sch);
7671 
7672 	/* no task is on scx, turn off all the switches and flush in-progress calls */
7673 	static_branch_disable(&__scx_enabled);
7674 	static_branch_disable(&__scx_is_cid_type);
7675 	if (sch->ops.flags & SCX_OPS_TID_TO_TASK)
7676 		static_branch_disable(&__scx_tid_to_task_enabled);
7677 	bitmap_zero(sch->has_op, SCX_OPI_END);
7678 	scx_idle_disable();
7679 	synchronize_rcu();
7680 	if (sch->ops.flags & SCX_OPS_TID_TO_TASK)
7681 		rhashtable_free_and_destroy(&scx_tid_hash, NULL, NULL);
7682 
7683 	scx_log_sched_disable(sch);
7684 
7685 	if (sch->ops.exit)
7686 		SCX_CALL_OP(sch, exit, NULL, sch->exit_info);
7687 
7688 	/*
7689 	 * @sch's non-ops programs such as timers and tracers can fire after
7690 	 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from
7691 	 * resolving to @sch and drain in-flight resolvers.
7692 	 */
7693 	WRITE_ONCE(sch->dead, true);
7694 	synchronize_rcu();
7695 
7696 	scx_unlink_sched(sch);
7697 
7698 	/*
7699 	 * scx_root clearing and cid table retirement must be inside
7700 	 * cpus_read_lock(). See handle_hotplug().
7701 	 */
7702 	cpus_read_lock();
7703 	RCU_INIT_POINTER(scx_root, NULL);
7704 	scx_cid_retire_tables();
7705 	cpus_read_unlock();
7706 
7707 	/*
7708 	 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs
7709 	 * could observe an object of the same name still in the hierarchy when
7710 	 * the next scheduler is loaded.
7711 	 */
7712 #ifdef CONFIG_EXT_SUB_SCHED
7713 	if (sch->sub_kset)
7714 		kobject_del(&sch->sub_kset->kobj);
7715 #endif
7716 	/* not added if enable failed before scx_sched_sysfs_add() */
7717 	if (sch->kobj.state_in_sysfs)
7718 		kobject_del(&sch->kobj);
7719 
7720 	free_kick_syncs();
7721 
7722 	mutex_unlock(&scx_enable_mutex);
7723 
7724 	WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
7725 done:
7726 	scx_bypass(sch, false);
7727 }
7728 
7729 /**
7730  * scx_propagate_exit_irq_workfn - Claim SCX_EXIT_PARENT on the exiting subtree
7731  * @irq_work: &scx_sched.propagate_exit_irq_work
7732  *
7733  * Queued by scx_claim_exit() after a non-PARENT claim. Claims SCX_EXIT_PARENT
7734  * on each descendant, giving every one its own disable work - most of disabling
7735  * is serialized but ops.exit() can take arbitrarily long and running them in
7736  * separate helper kthreads parallelizes it. No recursion as only non-PARENT
7737  * claims propagate.
7738  */
7739 static void scx_propagate_exit_irq_workfn(struct irq_work *irq_work)
7740 {
7741 	struct scx_sched *sch = container_of(irq_work, struct scx_sched,
7742 					     propagate_exit_irq_work);
7743 	struct scx_sched *pos;
7744 
7745 	scoped_guard (raw_spinlock_irqsave, &scx_sched_lock) {
7746 		scx_for_each_descendant_pre(pos, sch)
7747 			scx_disable(pos, SCX_EXIT_PARENT);
7748 	}
7749 }
7750 
7751 /*
7752  * Claim the exit on @sch. The caller must ensure that the helper kthread work
7753  * is kicked before the current task can be preempted. Once exit_kind is
7754  * claimed, scx_error() can no longer trigger, so if the current task gets
7755  * preempted and the BPF scheduler fails to schedule it back, the helper work
7756  * will never be kicked and the whole system can wedge.
7757  *
7758  * Lock-free and safe to call from any context including NMI.
7759  */
7760 static bool scx_claim_exit(struct scx_sched *sch, enum scx_exit_kind kind)
7761 {
7762 	int none = SCX_EXIT_NONE;
7763 
7764 	lockdep_assert_preemption_disabled();
7765 
7766 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
7767 		kind = SCX_EXIT_ERROR;
7768 
7769 	if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind))
7770 		return false;
7771 
7772 	if (kind == SCX_EXIT_PARENT) {
7773 		/* an ancestor is already sweeping the subtree */
7774 		WRITE_ONCE(sch->aborting, true);
7775 	} else {
7776 		struct scx_sched *pos;
7777 
7778 		/*
7779 		 * CPUs may be live-locked in the dispatch paths of @sch or its
7780 		 * descendants, which ->aborting breaks. Sweep the subtree
7781 		 * locklessly so that this works from NMI. smp_store_mb() orders
7782 		 * each node's ->aborting store before its children are walked -
7783 		 * either we see a racing scx_link_sched() on ->children or it
7784 		 * sees ->aborting.
7785 		 */
7786 		scoped_guard (rcu) {
7787 			scx_for_each_descendant_pre(pos, sch)
7788 				smp_store_mb(pos->aborting, true);
7789 		}
7790 
7791 		irq_work_queue(&sch->propagate_exit_irq_work);
7792 	}
7793 
7794 	/* fired after ->aborting is set so callbacks can't delay recovery */
7795 	trace_sched_ext_exit(sch, kind);
7796 
7797 	return true;
7798 }
7799 
7800 static void scx_disable_workfn(struct kthread_work *work)
7801 {
7802 	struct scx_sched *sch = container_of(work, struct scx_sched, disable_work);
7803 	struct scx_exit_info *ei = sch->exit_info;
7804 	int kind;
7805 
7806 	kind = atomic_read(&sch->exit_kind);
7807 	while (true) {
7808 		if (kind == SCX_EXIT_DONE)	/* already disabled? */
7809 			return;
7810 		WARN_ON_ONCE(kind == SCX_EXIT_NONE);
7811 		if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE))
7812 			break;
7813 	}
7814 	ei->kind = kind;
7815 	ei->reason = scx_exit_reason(ei->kind);
7816 
7817 	if (scx_parent(sch))
7818 		scx_sub_disable(sch);
7819 	else
7820 		scx_root_disable(sch);
7821 }
7822 
7823 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind)
7824 {
7825 	guard(preempt)();
7826 	if (scx_claim_exit(sch, kind))
7827 		irq_work_queue(&sch->disable_irq_work);
7828 }
7829 
7830 /**
7831  * scx_flush_disable_work - flush the disable work and wait for it to finish
7832  * @sch: the scheduler
7833  *
7834  * sch->disable_work might still not queued, causing kthread_flush_work()
7835  * as a noop. Syncing the irq_work first is required to guarantee the
7836  * kthread work has been queued before waiting for it.
7837  */
7838 void scx_flush_disable_work(struct scx_sched *sch)
7839 {
7840 	int kind;
7841 
7842 	/*
7843 	 * scx_disable_workfn() sets SCX_EXIT_DONE before tearing down. Read
7844 	 * exit_kind with acquire ordering (paired with atomic_try_cmpxchg() in
7845 	 * scx_disable_workfn()) before syncing and flushing so that, once DONE
7846 	 * is seen, the following flush observes the queued work and waits for
7847 	 * the teardown to finish.
7848 	 */
7849 	do {
7850 		kind = atomic_read_acquire(&sch->exit_kind);
7851 		irq_work_sync(&sch->disable_irq_work);
7852 		kthread_flush_work(&sch->disable_work);
7853 	} while (kind != SCX_EXIT_NONE && kind != SCX_EXIT_DONE);
7854 }
7855 
7856 static void dump_newline(struct seq_buf *s)
7857 {
7858 	trace_sched_ext_dump("");
7859 
7860 	/* @s may be zero sized and seq_buf triggers WARN if so */
7861 	if (s->size)
7862 		seq_buf_putc(s, '\n');
7863 }
7864 
7865 __printf(2, 3) void scx_dump_line(struct seq_buf *s, const char *fmt, ...)
7866 {
7867 	va_list args;
7868 
7869 #ifdef CONFIG_TRACEPOINTS
7870 	if (trace_sched_ext_dump_enabled()) {
7871 		/* protected by scx_dump_lock */
7872 		static char line_buf[SCX_EXIT_MSG_LEN];
7873 
7874 		va_start(args, fmt);
7875 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
7876 		va_end(args);
7877 
7878 		trace_call__sched_ext_dump(line_buf);
7879 	}
7880 #endif
7881 	/* @s may be zero sized and seq_buf triggers WARN if so */
7882 	if (s->size) {
7883 		va_start(args, fmt);
7884 		seq_buf_vprintf(s, fmt, args);
7885 		va_end(args);
7886 
7887 		seq_buf_putc(s, '\n');
7888 	}
7889 }
7890 
7891 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
7892 			     const unsigned long *bt, unsigned int len)
7893 {
7894 	unsigned int i;
7895 
7896 	for (i = 0; i < len; i++)
7897 		scx_dump_line(s, "%s%pS", prefix, (void *)bt[i]);
7898 }
7899 
7900 static void ops_dump_init(struct seq_buf *s, const char *prefix)
7901 {
7902 	struct scx_dump_data *dd = &scx_dump_data;
7903 
7904 	lockdep_assert_irqs_disabled();
7905 
7906 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
7907 	dd->first = true;
7908 	dd->cursor = 0;
7909 	dd->s = s;
7910 	dd->prefix = prefix;
7911 }
7912 
7913 static void ops_dump_flush(void)
7914 {
7915 	struct scx_dump_data *dd = &scx_dump_data;
7916 	char *line = dd->buf.line;
7917 
7918 	if (!dd->cursor)
7919 		return;
7920 
7921 	/*
7922 	 * There's something to flush and this is the first line. Insert a blank
7923 	 * line to distinguish ops dump.
7924 	 */
7925 	if (dd->first) {
7926 		dump_newline(dd->s);
7927 		dd->first = false;
7928 	}
7929 
7930 	/*
7931 	 * There may be multiple lines in $line. Scan and emit each line
7932 	 * separately.
7933 	 */
7934 	while (true) {
7935 		char *end = line;
7936 		char c;
7937 
7938 		while (*end != '\n' && *end != '\0')
7939 			end++;
7940 
7941 		/*
7942 		 * If $line overflowed, it may not have newline at the end.
7943 		 * Always emit with a newline.
7944 		 */
7945 		c = *end;
7946 		*end = '\0';
7947 		scx_dump_line(dd->s, "%s%s", dd->prefix, line);
7948 		if (c == '\0')
7949 			break;
7950 
7951 		/* move to the next line */
7952 		end++;
7953 		if (*end == '\0')
7954 			break;
7955 		line = end;
7956 	}
7957 
7958 	dd->cursor = 0;
7959 }
7960 
7961 static void ops_dump_exit(void)
7962 {
7963 	ops_dump_flush();
7964 	scx_dump_data.cpu = -1;
7965 }
7966 
7967 static void scx_dump_task(struct scx_sched *sch, struct seq_buf *s, struct scx_dump_ctx *dctx,
7968 			  struct rq *rq, struct task_struct *p, char marker)
7969 {
7970 	static unsigned long bt[SCX_EXIT_BT_LEN];
7971 	struct scx_sched *task_sch = scx_task_sched(p);
7972 	const char *own_marker;
7973 	char sch_id_buf[32];
7974 	char dsq_id_buf[19] = "(n/a)";
7975 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
7976 	unsigned int bt_len = 0;
7977 
7978 	own_marker = task_sch == sch ? "*" : "";
7979 
7980 	if (task_sch->level == 0)
7981 		scnprintf(sch_id_buf, sizeof(sch_id_buf), "root");
7982 	else
7983 		scnprintf(sch_id_buf, sizeof(sch_id_buf), "sub%d-%llu",
7984 			  task_sch->level, task_sch->ops.sub_cgroup_id);
7985 
7986 	if (p->scx.dsq)
7987 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
7988 			  (unsigned long long)p->scx.dsq->id);
7989 
7990 	dump_newline(s);
7991 	scx_dump_line(s, " %c%c %s[%d] %s%s %+ldms",
7992 		      marker, task_state_to_char(p), p->comm, p->pid, own_marker, sch_id_buf,
7993 		      jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
7994 	scx_dump_line(s, "      scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu",
7995 		      scx_get_task_state(p) >> SCX_TASK_STATE_SHIFT,
7996 		      p->scx.flags & ~SCX_TASK_STATE_MASK, p->scx.dsq_flags,
7997 		      ops_state & SCX_OPSS_STATE_MASK, ops_state >> SCX_OPSS_QSEQ_SHIFT);
7998 	scx_dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
7999 		      p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
8000 	scx_dump_line(s, "      dsq_vtime=%llu slice=%llu weight=%u",
8001 		      p->scx.dsq_vtime, p->scx.slice, p->scx.weight);
8002 	scx_dump_line(s, "      cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr),
8003 		      p->migration_disabled);
8004 
8005 	if (SCX_HAS_OP(sch, dump_task)) {
8006 		ops_dump_init(s, "    ");
8007 		SCX_CALL_OP(sch, dump_task, rq, dctx, p);
8008 		ops_dump_exit();
8009 	}
8010 
8011 #ifdef CONFIG_STACKTRACE
8012 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
8013 #endif
8014 	if (bt_len) {
8015 		dump_newline(s);
8016 		dump_stack_trace(s, "    ", bt, bt_len);
8017 	}
8018 }
8019 
8020 static void scx_dump_cpu(struct scx_sched *sch, struct seq_buf *s,
8021 			 struct scx_dump_ctx *dctx, int cpu,
8022 			 bool dump_all_tasks)
8023 {
8024 	struct rq *rq = cpu_rq(cpu);
8025 	struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
8026 	struct rq_flags rf;
8027 	struct task_struct *p;
8028 	struct seq_buf ns;
8029 	size_t avail, used;
8030 	char *buf;
8031 	bool idle;
8032 
8033 	rq_lock_irqsave(rq, &rf);
8034 
8035 	idle = list_empty(&rq->scx.runnable_list) &&
8036 		rq->curr->sched_class == &idle_sched_class;
8037 
8038 	if (idle && !SCX_HAS_OP(sch, dump_cpu))
8039 		goto next;
8040 
8041 	/*
8042 	 * We don't yet know whether ops.dump_cpu() will produce output
8043 	 * and we may want to skip the default CPU dump if it doesn't.
8044 	 * Use a nested seq_buf to generate the standard dump so that we
8045 	 * can decide whether to commit later.
8046 	 */
8047 	avail = seq_buf_get_buf(s, &buf);
8048 	seq_buf_init(&ns, buf, avail);
8049 
8050 	dump_newline(&ns);
8051 	scx_dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ksync=%lu",
8052 		      cpu, rq->scx.nr_running, rq->scx.flags, rq->scx.cpu_released,
8053 		      rq->scx.kick_sync);
8054 	scx_rescue_dump(&ns, rq);
8055 	scx_dump_line(&ns, "          curr=%s[%d] class=%ps",
8056 		      rq->curr->comm, rq->curr->pid, rq->curr->sched_class);
8057 	scx_dump_line(&ns, "          donor=%s[%d] class=%ps",
8058 		      rq->donor->comm, rq->donor->pid, rq->donor->sched_class);
8059 	if (!cpumask_empty(pcpu->cpus_to_kick))
8060 		scx_dump_line(&ns, "  cpus_to_kick   : %*pb",
8061 			      cpumask_pr_args(pcpu->cpus_to_kick));
8062 	if (!cpumask_empty(pcpu->cpus_to_kick_if_idle))
8063 		scx_dump_line(&ns, "  idle_to_kick   : %*pb",
8064 			      cpumask_pr_args(pcpu->cpus_to_kick_if_idle));
8065 	if (!cpumask_empty(pcpu->cpus_to_preempt))
8066 		scx_dump_line(&ns, "  cpus_to_preempt: %*pb",
8067 			      cpumask_pr_args(pcpu->cpus_to_preempt));
8068 	if (!cpumask_empty(pcpu->cpus_to_preempt_lazy))
8069 		scx_dump_line(&ns, "  preempt_lazy   : %*pb",
8070 			      cpumask_pr_args(pcpu->cpus_to_preempt_lazy));
8071 	if (!cpumask_empty(pcpu->cpus_to_wait))
8072 		scx_dump_line(&ns, "  cpus_to_wait   : %*pb",
8073 			      cpumask_pr_args(pcpu->cpus_to_wait));
8074 	if (!cpumask_empty(rq->scx.cpus_to_sync))
8075 		scx_dump_line(&ns, "  cpus_to_sync   : %*pb",
8076 			      cpumask_pr_args(rq->scx.cpus_to_sync));
8077 
8078 	used = seq_buf_used(&ns);
8079 	if (SCX_HAS_OP(sch, dump_cpu)) {
8080 		ops_dump_init(&ns, "  ");
8081 		SCX_CALL_OP(sch, dump_cpu, rq, dctx, scx_cpu_arg(cpu), idle);
8082 		ops_dump_exit();
8083 	}
8084 
8085 	/*
8086 	 * If idle && nothing generated by ops.dump_cpu(), there's
8087 	 * nothing interesting. Skip.
8088 	 */
8089 	if (idle && used == seq_buf_used(&ns))
8090 		goto next;
8091 
8092 	/*
8093 	 * $s may already have overflowed when $ns was created. If so,
8094 	 * calling commit on it will trigger BUG.
8095 	 */
8096 	if (avail) {
8097 		seq_buf_commit(s, seq_buf_used(&ns));
8098 		if (seq_buf_has_overflowed(&ns))
8099 			seq_buf_set_overflow(s);
8100 	}
8101 
8102 	if (rq->curr->sched_class == &ext_sched_class &&
8103 	    (dump_all_tasks || scx_task_on_sched(sch, rq->curr)))
8104 		scx_dump_task(sch, s, dctx, rq, rq->curr, '*');
8105 	if (rq->donor != rq->curr &&
8106 	    rq->donor->sched_class == &ext_sched_class &&
8107 	    (dump_all_tasks || scx_task_on_sched(sch, rq->donor)))
8108 		scx_dump_task(sch, s, dctx, rq, rq->donor, ' ');
8109 
8110 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
8111 		if (dump_all_tasks || scx_task_on_sched(sch, p))
8112 			scx_dump_task(sch, s, dctx, rq, p, ' ');
8113 next:
8114 	rq_unlock_irqrestore(rq, &rf);
8115 }
8116 
8117 /*
8118  * Dump scheduler state. If @dump_all_tasks is true, dump all tasks regardless
8119  * of which scheduler they belong to. If false, only dump tasks owned by @sch.
8120  * For SysRq-D dumps, @dump_all_tasks=false since all schedulers are dumped
8121  * separately. For error dumps, @dump_all_tasks=true since only the failing
8122  * scheduler is dumped.
8123  */
8124 static void scx_dump_state(struct scx_sched *sch, struct scx_exit_info *ei,
8125 			   size_t dump_len, bool dump_all_tasks)
8126 {
8127 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
8128 	struct scx_dump_ctx dctx = {
8129 		.kind = ei->kind,
8130 		.exit_code = ei->exit_code,
8131 		.reason = ei->reason,
8132 		.at_ns = ktime_get_ns(),
8133 		.at_jiffies = jiffies,
8134 	};
8135 	struct seq_buf s;
8136 	struct scx_event_stats events;
8137 	int cpu;
8138 
8139 	guard(raw_spinlock_irqsave)(&scx_dump_lock);
8140 
8141 	if (sch->dump_disabled)
8142 		return;
8143 
8144 	seq_buf_init(&s, ei->dump, dump_len);
8145 
8146 #ifdef CONFIG_EXT_SUB_SCHED
8147 	if (sch->level == 0)
8148 		scx_dump_line(&s, "%s: root", sch->ops.name);
8149 	else
8150 		scx_dump_line(&s, "%s: sub%d-%llu %s",
8151 			      sch->ops.name, sch->level, sch->ops.sub_cgroup_id,
8152 			      sch->cgrp_path);
8153 #endif
8154 	if (ei->kind == SCX_EXIT_NONE) {
8155 		scx_dump_line(&s, "Debug dump triggered by %s", ei->reason);
8156 	} else {
8157 		if (ei->exit_cpu >= 0)
8158 			scx_dump_line(&s, "%s[%d] triggered exit kind %d on CPU %d:",
8159 				      current->comm, current->pid, ei->kind,
8160 				      ei->exit_cpu);
8161 		else
8162 			scx_dump_line(&s, "%s[%d] triggered exit kind %d:",
8163 				      current->comm, current->pid, ei->kind);
8164 		scx_dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
8165 		dump_newline(&s);
8166 		scx_dump_line(&s, "Backtrace:");
8167 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
8168 	}
8169 
8170 	if (SCX_HAS_OP(sch, dump)) {
8171 		ops_dump_init(&s, "");
8172 		SCX_CALL_OP(sch, dump, NULL, &dctx);
8173 		ops_dump_exit();
8174 	}
8175 
8176 	dump_newline(&s);
8177 	scx_dump_line(&s, "CPU states");
8178 	scx_dump_line(&s, "----------");
8179 
8180 	/*
8181 	 * Dump stalled CPUs first so they aren't lost to dump truncation, then
8182 	 * walk the rest in order. Fall back to exit_cpu if no stall mask set.
8183 	 */
8184 	if (!cpumask_empty(sch->stall_cpus)) {
8185 		for_each_cpu(cpu, sch->stall_cpus)
8186 			scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks);
8187 		for_each_possible_cpu(cpu) {
8188 			if (!cpumask_test_cpu(cpu, sch->stall_cpus))
8189 				scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks);
8190 		}
8191 	} else {
8192 		if (ei->exit_cpu >= 0)
8193 			scx_dump_cpu(sch, &s, &dctx, ei->exit_cpu, dump_all_tasks);
8194 		for_each_possible_cpu(cpu) {
8195 			if (cpu != ei->exit_cpu)
8196 				scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks);
8197 		}
8198 	}
8199 
8200 	dump_newline(&s);
8201 	scx_dump_line(&s, "Event counters");
8202 	scx_dump_line(&s, "--------------");
8203 
8204 	scx_read_events(sch, &events);
8205 #define SCX_EVENT(name)	scx_dump_event(s, &events, name)
8206 	SCX_EVENTS_LIST(SCX_EVENT);
8207 #undef SCX_EVENT
8208 
8209 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
8210 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
8211 		       trunc_marker, sizeof(trunc_marker));
8212 }
8213 
8214 static void scx_disable_irq_workfn(struct irq_work *irq_work)
8215 {
8216 	struct scx_sched *sch = container_of(irq_work, struct scx_sched, disable_irq_work);
8217 	struct scx_exit_info *ei = sch->exit_info;
8218 
8219 	if (ei->kind >= SCX_EXIT_ERROR)
8220 		scx_dump_state(sch, ei, sch->ops.exit_dump_len, true);
8221 
8222 	kthread_queue_work(sch->helper, &sch->disable_work);
8223 }
8224 
8225 /* finish exit_info and kick the disable work, ei->msg must already be set */
8226 static void scx_finish_exit(struct scx_sched *sch, enum scx_exit_kind kind,
8227 			    s64 exit_code, s32 exit_cpu)
8228 {
8229 	struct scx_exit_info *ei = sch->exit_info;
8230 
8231 	ei->exit_code = exit_code;
8232 #ifdef CONFIG_STACKTRACE
8233 	/*
8234 	 * stack_trace_save()'s NMI-safety is arch-dependent and undocumented.
8235 	 * Skip the backtrace when exiting from NMI.
8236 	 */
8237 	if (kind >= SCX_EXIT_ERROR && !in_nmi())
8238 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
8239 #endif
8240 	/*
8241 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
8242 	 * in scx_disable_workfn().
8243 	 */
8244 	ei->kind = kind;
8245 	ei->reason = scx_exit_reason(ei->kind);
8246 	ei->exit_cpu = exit_cpu;
8247 
8248 	irq_work_queue(&sch->disable_irq_work);
8249 }
8250 
8251 bool scx_vexit(struct scx_sched *sch,
8252 	       enum scx_exit_kind kind, s64 exit_code, s32 exit_cpu,
8253 	       const char *fmt, va_list args)
8254 {
8255 	struct scx_exit_info *ei = sch->exit_info;
8256 
8257 	guard(preempt)();
8258 
8259 	if (!scx_claim_exit(sch, kind))
8260 		return false;
8261 
8262 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
8263 
8264 	scx_finish_exit(sch, kind, exit_code, exit_cpu);
8265 	return true;
8266 }
8267 
8268 static int alloc_kick_syncs(void)
8269 {
8270 	int cpu;
8271 
8272 	/*
8273 	 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size
8274 	 * can exceed percpu allocator limits on large machines.
8275 	 */
8276 	for_each_possible_cpu(cpu) {
8277 		struct scx_kick_syncs __rcu **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
8278 		struct scx_kick_syncs *new_ksyncs;
8279 
8280 		WARN_ON_ONCE(rcu_access_pointer(*ksyncs));
8281 
8282 		new_ksyncs = kvzalloc_node(struct_size(new_ksyncs, syncs, nr_cpu_ids),
8283 					   GFP_KERNEL, cpu_to_node(cpu));
8284 		if (!new_ksyncs) {
8285 			free_kick_syncs();
8286 			return -ENOMEM;
8287 		}
8288 
8289 		rcu_assign_pointer(*ksyncs, new_ksyncs);
8290 	}
8291 
8292 	return 0;
8293 }
8294 
8295 static void free_pnode(struct scx_sched_pnode *pnode)
8296 {
8297 	if (!pnode)
8298 		return;
8299 	exit_dsq(&pnode->global_dsq);
8300 	kfree(pnode);
8301 }
8302 
8303 static struct scx_sched_pnode *alloc_pnode(struct scx_sched *sch, int node)
8304 {
8305 	struct scx_sched_pnode *pnode;
8306 
8307 	pnode = kzalloc_node(sizeof(*pnode), GFP_KERNEL, node);
8308 	if (!pnode)
8309 		return NULL;
8310 
8311 	if (scx_init_dsq(&pnode->global_dsq, SCX_DSQ_GLOBAL, sch)) {
8312 		kfree(pnode);
8313 		return NULL;
8314 	}
8315 
8316 	return pnode;
8317 }
8318 
8319 /*
8320  * Allocate and initialize a new scx_sched. @cgrp's reference is always
8321  * consumed whether the function succeeds or fails.
8322  */
8323 struct scx_sched *scx_alloc_and_add_sched(struct scx_enable_cmd *cmd,
8324 					  struct cgroup *cgrp,
8325 					  struct scx_sched *parent)
8326 {
8327 	struct sched_ext_ops *ops = cmd->ops;
8328 	struct scx_sched *sch;
8329 	s32 level = parent ? parent->level + 1 : 0;
8330 	s32 node, cpu, ret, bypass_fail_cpu = nr_cpu_ids;
8331 
8332 	sch = kzalloc_flex(*sch, ancestors, level + 1);
8333 	if (!sch) {
8334 		ret = -ENOMEM;
8335 		goto err_put_cgrp;
8336 	}
8337 
8338 	sch->exit_info = alloc_exit_info(ops->exit_dump_len);
8339 	if (!sch->exit_info) {
8340 		ret = -ENOMEM;
8341 		goto err_free_sch;
8342 	}
8343 
8344 	ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params);
8345 	if (ret < 0)
8346 		goto err_free_ei;
8347 
8348 	sch->pnode = kzalloc_objs(sch->pnode[0], nr_node_ids);
8349 	if (!sch->pnode) {
8350 		ret = -ENOMEM;
8351 		goto err_free_hash;
8352 	}
8353 
8354 	for_each_node_state(node, N_POSSIBLE) {
8355 		sch->pnode[node] = alloc_pnode(sch, node);
8356 		if (!sch->pnode[node]) {
8357 			ret = -ENOMEM;
8358 			goto err_free_pnode;
8359 		}
8360 	}
8361 
8362 	sch->dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
8363 	sch->pcpu = __alloc_percpu(struct_size_t(struct scx_sched_pcpu,
8364 						 dsp_ctx.buf, sch->dsp_max_batch),
8365 				   __alignof__(struct scx_sched_pcpu));
8366 	if (!sch->pcpu) {
8367 		ret = -ENOMEM;
8368 		goto err_free_pnode;
8369 	}
8370 
8371 	for_each_possible_cpu(cpu) {
8372 		ret = scx_init_dsq(scx_bypass_dsq(sch, cpu), SCX_DSQ_BYPASS, sch);
8373 		if (ret) {
8374 			bypass_fail_cpu = cpu;
8375 			goto err_free_pcpu;
8376 		}
8377 	}
8378 
8379 	for_each_possible_cpu(cpu) {
8380 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
8381 
8382 		node = cpu_to_node(cpu);
8383 		pcpu->sch = sch;
8384 		INIT_LIST_HEAD(&pcpu->deferred_reenq_local.node);
8385 #ifdef CONFIG_EXT_SUB_SCHED
8386 		init_llist_node(&pcpu->ecaps_to_sync_node);
8387 #endif
8388 		INIT_LIST_HEAD(&pcpu->to_kick_node);
8389 		if (!zalloc_cpumask_var_node(&pcpu->cpus_to_kick, GFP_KERNEL, node) ||
8390 		    !zalloc_cpumask_var_node(&pcpu->cpus_to_kick_if_idle, GFP_KERNEL, node) ||
8391 		    !zalloc_cpumask_var_node(&pcpu->cpus_to_preempt, GFP_KERNEL, node) ||
8392 		    !zalloc_cpumask_var_node(&pcpu->cpus_to_preempt_lazy, GFP_KERNEL, node) ||
8393 		    !zalloc_cpumask_var_node(&pcpu->cpus_to_wait, GFP_KERNEL, node)) {
8394 			ret = -ENOMEM;
8395 			goto err_free_pcpu;
8396 		}
8397 	}
8398 
8399 	sch->helper = kthread_run_worker(0, "sched_ext_helper");
8400 	if (IS_ERR(sch->helper)) {
8401 		ret = PTR_ERR(sch->helper);
8402 		goto err_free_pcpu;
8403 	}
8404 
8405 	sched_set_fifo(sch->helper->task);
8406 
8407 	if (parent)
8408 		memcpy(sch->ancestors, parent->ancestors,
8409 		       level * sizeof(parent->ancestors[0]));
8410 	sch->ancestors[level] = sch;
8411 	sch->level = level;
8412 	sch->id = atomic64_inc_return(&scx_sched_id_cursor);
8413 
8414 	if (ops->timeout_ms)
8415 		sch->watchdog_timeout = msecs_to_jiffies(ops->timeout_ms);
8416 	else
8417 		sch->watchdog_timeout = SCX_WATCHDOG_MAX_TIMEOUT;
8418 
8419 	sch->slice_dfl = SCX_SLICE_DFL;
8420 	atomic_set(&sch->exit_kind, SCX_EXIT_NONE);
8421 	sch->disable_irq_work = IRQ_WORK_INIT_HARD(scx_disable_irq_workfn);
8422 	sch->propagate_exit_irq_work = IRQ_WORK_INIT_HARD(scx_propagate_exit_irq_workfn);
8423 	kthread_init_work(&sch->disable_work, scx_disable_workfn);
8424 	timer_setup(&sch->bypass_lb_timer, scx_bypass_lb_timerfn, 0);
8425 
8426 	if (!alloc_cpumask_var(&sch->bypass_lb_donee_cpumask, GFP_KERNEL)) {
8427 		ret = -ENOMEM;
8428 		goto err_stop_helper;
8429 	}
8430 	if (!alloc_cpumask_var(&sch->bypass_lb_resched_cpumask, GFP_KERNEL)) {
8431 		ret = -ENOMEM;
8432 		goto err_free_lb_cpumask;
8433 	}
8434 	if (!zalloc_cpumask_var(&sch->stall_cpus, GFP_KERNEL)) {
8435 		ret = -ENOMEM;
8436 		goto err_free_lb_resched_cpumask;
8437 	}
8438 	/*
8439 	 * Copy ops through the right union view. For cid-form the source is
8440 	 * struct sched_ext_ops_cid which lacks the trailing cpu_acquire/
8441 	 * cpu_release; those stay zero from kzalloc.
8442 	 */
8443 	if (cmd->is_cid_type) {
8444 		sch->ops_cid = *cmd->ops_cid;
8445 		sch->is_cid_type = true;
8446 	} else {
8447 		sch->ops = *cmd->ops;
8448 	}
8449 
8450 #ifdef CONFIG_EXT_SUB_SCHED
8451 	char *buf = kzalloc(PATH_MAX, GFP_KERNEL);
8452 	if (!buf) {
8453 		ret = -ENOMEM;
8454 		goto err_free_lb_resched;
8455 	}
8456 	cgroup_path(cgrp, buf, PATH_MAX);
8457 	sch->cgrp_path = kstrdup(buf, GFP_KERNEL);
8458 	kfree(buf);
8459 	if (!sch->cgrp_path) {
8460 		ret = -ENOMEM;
8461 		goto err_free_lb_resched;
8462 	}
8463 
8464 	sch->cgrp = cgrp;
8465 	INIT_LIST_HEAD(&sch->children);
8466 	INIT_LIST_HEAD(&sch->sibling);
8467 #endif	/* CONFIG_EXT_SUB_SCHED */
8468 
8469 	/*
8470 	 * Publishing makes @sch visible to scx_prog_sched() readers. Failure
8471 	 * paths after this point must free @sch through kobject_put() whose
8472 	 * release path defers the actual freeing by an RCU grace period.
8473 	 */
8474 	rcu_assign_pointer(ops->priv, sch);
8475 
8476 	sch->kobj.kset = scx_kset;
8477 	INIT_LIST_HEAD(&sch->all);
8478 
8479 #ifdef CONFIG_EXT_SUB_SCHED
8480 	if (parent) {
8481 		/*
8482 		 * Pin @parent for @sch's lifetime. The kobject hierarchy pins
8483 		 * it only via @parent->sub_kset, which is dropped during
8484 		 * disable. Released in scx_sched_free_rcu_work().
8485 		 */
8486 		kobject_get(&parent->kobj);
8487 	}
8488 #endif	/* CONFIG_EXT_SUB_SCHED */
8489 
8490 	/*
8491 	 * Init the kobj but don't add to sysfs yet. The enable path calls
8492 	 * scx_sched_sysfs_add() once @sch's sysfs-visible state is initialized.
8493 	 */
8494 	kobject_init(&sch->kobj, &scx_ktype);
8495 
8496 	/*
8497 	 * Consume the arena_map ref bpf_scx_reg_cid() took. Defer to here so
8498 	 * earlier failure paths leave cmd->arena_map set and bpf_scx_reg_cid
8499 	 * drops the ref. After this point, sch owns the ref and any cleanup
8500 	 * runs through scx_sched_free_rcu_work() which puts it.
8501 	 */
8502 	sch->arena_map = cmd->arena_map;
8503 	/* BPF arena is only available on MMU && 64BIT */
8504 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
8505 	if (sch->arena_map)
8506 		sch->arena_kern_base = bpf_arena_map_kern_vm_start(sch->arena_map);
8507 #endif
8508 	cmd->arena_map = NULL;
8509 	return sch;
8510 
8511 #ifdef CONFIG_EXT_SUB_SCHED
8512 err_free_lb_resched:
8513 	free_cpumask_var(sch->stall_cpus);
8514 #endif
8515 err_free_lb_resched_cpumask:
8516 	free_cpumask_var(sch->bypass_lb_resched_cpumask);
8517 err_free_lb_cpumask:
8518 	free_cpumask_var(sch->bypass_lb_donee_cpumask);
8519 err_stop_helper:
8520 	kthread_destroy_worker(sch->helper);
8521 err_free_pcpu:
8522 	for_each_possible_cpu(cpu) {
8523 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
8524 
8525 		free_cpumask_var(pcpu->cpus_to_kick);
8526 		free_cpumask_var(pcpu->cpus_to_kick_if_idle);
8527 		free_cpumask_var(pcpu->cpus_to_preempt);
8528 		free_cpumask_var(pcpu->cpus_to_preempt_lazy);
8529 		free_cpumask_var(pcpu->cpus_to_wait);
8530 	}
8531 	for_each_possible_cpu(cpu) {
8532 		if (cpu == bypass_fail_cpu)
8533 			break;
8534 		exit_dsq(scx_bypass_dsq(sch, cpu));
8535 	}
8536 	free_percpu(sch->pcpu);
8537 err_free_pnode:
8538 	for_each_node_state(node, N_POSSIBLE)
8539 		free_pnode(sch->pnode[node]);
8540 	kfree(sch->pnode);
8541 err_free_hash:
8542 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
8543 err_free_ei:
8544 	free_exit_info(sch->exit_info);
8545 err_free_sch:
8546 	kfree(sch);
8547 err_put_cgrp:
8548 #ifdef CONFIG_EXT_SUB_SCHED
8549 	cgroup_put(cgrp);
8550 #endif
8551 	return ERR_PTR(ret);
8552 }
8553 
8554 /*
8555  * Add @sch's kobject to sysfs, and create its sub_kset if the scheduler
8556  * implements ops.sub_attach. Called by the enable workfns once @sch's
8557  * sysfs-visible state is initialized.
8558  */
8559 int scx_sched_sysfs_add(struct scx_sched *sch)
8560 {
8561 #ifdef CONFIG_EXT_SUB_SCHED
8562 	struct scx_sched *parent = scx_parent(sch);
8563 	int ret;
8564 
8565 	if (parent)
8566 		ret = kobject_add(&sch->kobj, &parent->sub_kset->kobj,
8567 				  "sub-%llu", cgroup_id(sch_cgroup(sch)));
8568 	else
8569 		ret = kobject_add(&sch->kobj, NULL, "root");
8570 	if (ret < 0)
8571 		return ret;
8572 
8573 	if (sch->ops.sub_attach) {
8574 		sch->sub_kset = kset_create_and_add("sub", NULL, &sch->kobj);
8575 		if (!sch->sub_kset)
8576 			return -ENOMEM;
8577 	}
8578 	return 0;
8579 #else
8580 	return kobject_add(&sch->kobj, NULL, "root");
8581 #endif
8582 }
8583 
8584 static int check_hotplug_seq(struct scx_sched *sch,
8585 			      const struct sched_ext_ops *ops)
8586 {
8587 	unsigned long long global_hotplug_seq;
8588 
8589 	/*
8590 	 * If a hotplug event has occurred between when a scheduler was
8591 	 * initialized, and when we were able to attach, exit and notify user
8592 	 * space about it.
8593 	 */
8594 	if (ops->hotplug_seq) {
8595 		global_hotplug_seq = atomic_long_read(&scx_hotplug_seq);
8596 		if (ops->hotplug_seq != global_hotplug_seq) {
8597 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
8598 				 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
8599 				 "expected hotplug seq %llu did not match actual %llu",
8600 				 ops->hotplug_seq, global_hotplug_seq);
8601 			return -EBUSY;
8602 		}
8603 	}
8604 
8605 	return 0;
8606 }
8607 
8608 int scx_validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
8609 {
8610 	/*
8611 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
8612 	 * ops.enqueue() callback isn't implemented.
8613 	 */
8614 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
8615 		scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
8616 		return -EINVAL;
8617 	}
8618 
8619 	if ((ops->flags & SCX_OPS_ENQ_BLOCKED) && !ops->enqueue) {
8620 		scx_error(sch, "SCX_OPS_ENQ_BLOCKED requires ops.enqueue() to be implemented");
8621 		return -EINVAL;
8622 	}
8623 
8624 	/*
8625 	 * SCX_OPS_TID_TO_TASK is enabled by the root scheduler. A sub-sched
8626 	 * may set it to declare a dependency; reject if the root hasn't
8627 	 * enabled it.
8628 	 */
8629 	if ((ops->flags & SCX_OPS_TID_TO_TASK) && scx_parent(sch) &&
8630 	    !(sch->ancestors[0]->ops.flags & SCX_OPS_TID_TO_TASK)) {
8631 		scx_error(sch, "SCX_OPS_TID_TO_TASK requires root scheduler to enable it");
8632 		return -EINVAL;
8633 	}
8634 
8635 	/*
8636 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle
8637 	 * selection policy to be enabled.
8638 	 */
8639 	if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) &&
8640 	    (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) {
8641 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled");
8642 		return -EINVAL;
8643 	}
8644 
8645 	/*
8646 	 * cid-form's struct is shorter and doesn't include the cpu_acquire /
8647 	 * cpu_release tail; reading those fields off a cid-form @ops would
8648 	 * run past the BPF allocation. Skip for cid-form.
8649 	 */
8650 	if (!sch->is_cid_type && (ops->cpu_acquire || ops->cpu_release))
8651 		pr_warn_ratelimited("ops->cpu_acquire/release() are deprecated, use sched_switch TP instead\n");
8652 
8653 	/*
8654 	 * Sub-scheduler support is tied to the cid-form struct_ops. A sub-sched
8655 	 * attaches through a cid-form-only interface (sub_attach/sub_detach),
8656 	 * and a root that accepts sub-scheds must expose cid-form state to
8657 	 * them. Reject cpu-form schedulers on either side.
8658 	 */
8659 	if (!sch->is_cid_type) {
8660 		if (scx_parent(sch)) {
8661 			scx_error(sch, "sub-sched requires cid-form struct_ops");
8662 			return -EINVAL;
8663 		}
8664 		if (ops->sub_attach || ops->sub_detach) {
8665 			scx_error(sch, "sub_attach/sub_detach requires cid-form struct_ops");
8666 			return -EINVAL;
8667 		}
8668 	}
8669 
8670 	return 0;
8671 }
8672 
8673 static void scx_root_enable_workfn(struct kthread_work *work)
8674 {
8675 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
8676 	struct sched_ext_ops *ops = cmd->ops;
8677 	struct cgroup *cgrp = root_cgroup();
8678 	struct scx_sched *sch;
8679 	struct scx_task_iter sti;
8680 	struct task_struct *p;
8681 	int i, cpu, ret;
8682 
8683 	mutex_lock(&scx_enable_mutex);
8684 
8685 	if (scx_enable_state() != SCX_DISABLED) {
8686 		ret = -EBUSY;
8687 		goto err_unlock;
8688 	}
8689 
8690 	/*
8691 	 * @ops->priv binds @ops to its scx_sched instance. It is set here by
8692 	 * scx_alloc_and_add_sched() and cleared at the tail of bpf_scx_unreg(),
8693 	 * which runs after scx_root_disable() has dropped scx_enable_mutex. If
8694 	 * it's still non-NULL here, a previous attachment on @ops has not
8695 	 * finished tearing down; proceeding would let the in-flight unreg's
8696 	 * RCU_INIT_POINTER(NULL) clobber the @ops->priv we are about to assign.
8697 	 */
8698 	if (rcu_access_pointer(ops->priv)) {
8699 		ret = -EBUSY;
8700 		goto err_unlock;
8701 	}
8702 
8703 	ret = alloc_kick_syncs();
8704 	if (ret)
8705 		goto err_unlock;
8706 
8707 	if (ops->flags & SCX_OPS_TID_TO_TASK) {
8708 		ret = rhashtable_init(&scx_tid_hash, &scx_tid_hash_params);
8709 		if (ret)
8710 			goto err_free_ksyncs;
8711 	}
8712 
8713 #ifdef CONFIG_EXT_SUB_SCHED
8714 	cgroup_get(cgrp);
8715 #endif
8716 	/*
8717 	 * Transition to ENABLING to arm the disable path. Allocation failure
8718 	 * still unwinds locally. Full disabling on failure applies only after
8719 	 * scx_alloc_and_add_sched() succeeds.
8720 	 */
8721 	WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED);
8722 	WARN_ON_ONCE(scx_root);
8723 
8724 	sch = scx_alloc_and_add_sched(cmd, cgrp, NULL);
8725 	if (IS_ERR(sch)) {
8726 		ret = PTR_ERR(sch);
8727 		WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_ENABLING);
8728 		goto err_free_tid_hash;
8729 	}
8730 
8731 	if (sch->is_cid_type)
8732 		static_branch_enable(&__scx_is_cid_type);
8733 
8734 	atomic_long_set(&scx_nr_rejected, 0);
8735 
8736 	for_each_possible_cpu(cpu) {
8737 		struct rq *rq = cpu_rq(cpu);
8738 
8739 		rq->scx.local_dsq.sched = sch;
8740 		rq->scx.cpuperf_target = SCX_CPUPERF_ONE;
8741 	}
8742 
8743 	scx_discard_stale_ecaps_syncs();
8744 	scx_rescue_set_knobs(sch);
8745 
8746 	/*
8747 	 * Keep CPUs stable during enable so that the BPF scheduler can track
8748 	 * online CPUs by watching ->on/offline_cpu() after ->init().
8749 	 */
8750 	cpus_read_lock();
8751 
8752 	/*
8753 	 * Build the cid mapping into a private under-construction set. It
8754 	 * becomes visible to readers only through scx_cid_publish_tables() once
8755 	 * ops.init_cids() has finalized the layout.
8756 	 */
8757 	ret = scx_cid_init(sch);
8758 	if (ret) {
8759 		cpus_read_unlock();
8760 		goto err_disable;
8761 	}
8762 
8763 	scx_init_rq_ops_online();
8764 
8765 	/*
8766 	 * Make the scheduler instance visible. Must be inside cpus_read_lock().
8767 	 * See handle_hotplug().
8768 	 */
8769 	rcu_assign_pointer(scx_root, sch);
8770 
8771 	ret = scx_link_sched(sch);
8772 	if (ret) {
8773 		cpus_read_unlock();
8774 		goto err_disable;
8775 	}
8776 
8777 	scx_idle_enable(ops);
8778 
8779 	/*
8780 	 * A cid-form scheduler finalizes its cid layout in ops.init_cids(),
8781 	 * which may call scx_bpf_cid_override(). Run it before the caps and
8782 	 * shard state are built so the final layout is in effect.
8783 	 */
8784 	if (sch->is_cid_type && sch->ops_cid.init_cids) {
8785 		ret = SCX_CALL_OP_RET(sch, init_cids, NULL);
8786 		if (ret) {
8787 			ret = scx_ops_sanitize_err(sch, "init_cids", ret);
8788 			cpus_read_unlock();
8789 			scx_error(sch, "ops.init_cids() failed (%d)", ret);
8790 			goto err_disable;
8791 		}
8792 	}
8793 
8794 	/* the cid layout is final, expose it to readers */
8795 	scx_cid_publish_tables();
8796 
8797 	ret = scx_arena_pool_init(sch);
8798 	if (ret) {
8799 		cpus_read_unlock();
8800 		goto err_disable;
8801 	}
8802 
8803 	ret = scx_alloc_kern_arena_objs(sch);
8804 	if (ret) {
8805 		cpus_read_unlock();
8806 		goto err_disable;
8807 	}
8808 
8809 	ret = scx_alloc_pshards(sch);
8810 	if (ret) {
8811 		cpus_read_unlock();
8812 		goto err_disable;
8813 	}
8814 
8815 	scx_init_root_caps(sch);
8816 
8817 	/* the cid caps and shards are live now, so ops.init() can query them */
8818 	if (sch->ops.init) {
8819 		ret = SCX_CALL_OP_RET(sch, init, NULL);
8820 		if (ret) {
8821 			ret = scx_ops_sanitize_err(sch, "init", ret);
8822 			cpus_read_unlock();
8823 			scx_error(sch, "ops.init() failed (%d)", ret);
8824 			goto err_disable;
8825 		}
8826 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
8827 	}
8828 
8829 	ret = scx_sched_sysfs_add(sch);
8830 	if (ret) {
8831 		cpus_read_unlock();
8832 		goto err_disable;
8833 	}
8834 
8835 	for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++)
8836 		if (((void (**)(void))ops)[i])
8837 			set_bit(i, sch->has_op);
8838 
8839 	ret = check_hotplug_seq(sch, ops);
8840 	if (ret) {
8841 		cpus_read_unlock();
8842 		goto err_disable;
8843 	}
8844 	scx_idle_update_selcpu_topology(ops);
8845 
8846 	cpus_read_unlock();
8847 
8848 	ret = scx_validate_ops(sch, ops);
8849 	if (ret)
8850 		goto err_disable;
8851 
8852 	/*
8853 	 * Attach the ext_server bandwidth reservation before anything is
8854 	 * committed so that we can fail the enable if the root domain cannot
8855 	 * accommodate it. The matching fair_server detach is deferred to the
8856 	 * tail of this function, after the switch is fully committed and can no
8857 	 * longer fail.
8858 	 *
8859 	 * On failure, err_disable funnels into scx_root_disable() which
8860 	 * detaches ext_server, so partially-attached state is cleaned up
8861 	 * automatically.
8862 	 */
8863 	for_each_possible_cpu(cpu) {
8864 		struct rq *rq = cpu_rq(cpu);
8865 
8866 		scoped_guard(rq_lock_irqsave, rq) {
8867 			update_rq_clock(rq);
8868 			ret = dl_server_attach_bw(&rq->ext_server);
8869 		}
8870 		if (ret) {
8871 			pr_warn("sched_ext: failed to attach ext_server on CPU %d (%d)\n",
8872 				cpu, ret);
8873 			goto err_disable;
8874 		}
8875 	}
8876 
8877 	/*
8878 	 * Once __scx_enabled is set, %current can be switched to SCX anytime.
8879 	 * This can lead to stalls as some BPF schedulers (e.g. userspace
8880 	 * scheduling) may not function correctly before all tasks are switched.
8881 	 * Init in bypass mode to guarantee forward progress.
8882 	 */
8883 	scx_bypass(sch, true);
8884 
8885 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
8886 		if (((void (**)(void))ops)[i])
8887 			set_bit(i, sch->has_op);
8888 
8889 	scx_ops_cid_sched_updated_enable(sch);
8890 
8891 	if (sch->ops.cpu_acquire || sch->ops.cpu_release)
8892 		sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT;
8893 
8894 	/*
8895 	 * Lock out forks, cgroup on/offlining and moves before opening the
8896 	 * floodgate so that they don't wander into the operations prematurely.
8897 	 */
8898 	percpu_down_write(&scx_fork_rwsem);
8899 
8900 	WARN_ON_ONCE(scx_init_task_enabled);
8901 	scx_init_task_enabled = true;
8902 
8903 	/* flip under fork_rwsem; the iter below covers existing tasks */
8904 	if (ops->flags & SCX_OPS_TID_TO_TASK)
8905 		static_branch_enable(&__scx_tid_to_task_enabled);
8906 
8907 	/*
8908 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
8909 	 * preventing new tasks from being added. No need to exclude tasks
8910 	 * leaving as sched_ext_dead() can handle both prepped and enabled
8911 	 * tasks. Prep all tasks first and then enable them with preemption
8912 	 * disabled.
8913 	 *
8914 	 * All cgroups should be initialized before scx_init_task() so that the
8915 	 * BPF scheduler can reliably track each task's cgroup membership from
8916 	 * scx_init_task(). Lock out cgroup on/offlining and task migrations
8917 	 * while tasks are being initialized so that scx_cgroup_can_attach()
8918 	 * never sees uninitialized tasks.
8919 	 */
8920 	scx_cgroup_lock();
8921 	set_cgroup_sched(sch_cgroup(sch), sch);
8922 	ret = scx_cgroup_init(sch);
8923 	if (ret)
8924 		goto err_disable_unlock_all;
8925 
8926 	WARN_ON_ONCE(scx_cgroup_enabled);
8927 	scx_cgroup_enabled = true;
8928 
8929 	scx_task_iter_start(&sti, NULL);
8930 	while ((p = scx_task_iter_next_locked(&sti))) {
8931 		/*
8932 		 * @p is in scx_tasks under scx_tasks_lock, and SCX_TASK_DEAD
8933 		 * tasks are filtered by scx_task_iter_next_locked().
8934 		 * sched_ext_dead() removes @p from scx_tasks under the same
8935 		 * lock before put_task_struct_rcu_user() runs, so @p->usage
8936 		 * is guaranteed > 0 here.
8937 		 */
8938 		get_task_struct(p);
8939 
8940 		/*
8941 		 * Set %INIT_BEGIN under the iter's rq lock so that a concurrent
8942 		 * sched_ext_dead() does not call ops.exit_task() on @p while
8943 		 * ops.init_task() is running. If sched_ext_dead() runs before
8944 		 * this store, it has already removed @p from scx_tasks and the
8945 		 * iter won't visit @p; if it runs after, it observes
8946 		 * %INIT_BEGIN and transitions to %DEAD without calling ops,
8947 		 * leaving the post-init recheck below to unwind.
8948 		 */
8949 		scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
8950 		scx_task_iter_unlock(&sti);
8951 
8952 		ret = __scx_init_task(sch, p, NULL, false);
8953 
8954 		scx_task_iter_relock(&sti, p);
8955 
8956 		if (unlikely(ret)) {
8957 			if (scx_get_task_state(p) != SCX_TASK_DEAD)
8958 				scx_set_task_state(p, SCX_TASK_NONE);
8959 			scx_task_iter_stop(&sti);
8960 			scx_error(sch, "ops.init_task() failed (%d) for %s[%d]",
8961 				  ret, p->comm, p->pid);
8962 			put_task_struct(p);
8963 			goto err_disable_unlock_all;
8964 		}
8965 
8966 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
8967 			/*
8968 			 * sched_ext_dead() observed %INIT_BEGIN and set %DEAD.
8969 			 * ops.exit_task() is owed to the sched __scx_init_task()
8970 			 * ran against; call it now.
8971 			 */
8972 			scx_sub_init_cancel_task(sch, p);
8973 		} else {
8974 			scx_set_task_state(p, SCX_TASK_INIT);
8975 			scx_set_task_sched(p, sch);
8976 			scx_set_task_state(p, SCX_TASK_READY);
8977 		}
8978 
8979 		/*
8980 		 * Insert into the tid hash. scx_tasks_lock is held by the iter;
8981 		 * list_empty() guards against sched_ext_dead() having taken @p
8982 		 * off the list while init ran unlocked.
8983 		 */
8984 		if (scx_tid_to_task_enabled() && !list_empty(&p->scx.tasks_node))
8985 			scx_tid_hash_insert(p);
8986 
8987 		put_task_struct(p);
8988 	}
8989 	scx_task_iter_stop(&sti);
8990 	scx_cgroup_unlock();
8991 	percpu_up_write(&scx_fork_rwsem);
8992 
8993 	/*
8994 	 * All tasks are READY. Finish patching all scx_enabled() sites before
8995 	 * opening task_should_scx() and switching eligible tasks.
8996 	 */
8997 	WARN_ON_ONCE(scx_task_switch_enabled);
8998 	static_branch_enable(&__scx_enabled);
8999 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
9000 	/* pairs with smp_load_acquire() in task_should_scx() */
9001 	smp_store_release(&scx_task_switch_enabled, true);
9002 
9003 	/*
9004 	 * We're fully committed and can't fail. The task READY -> ENABLED
9005 	 * transitions here are synchronized against sched_ext_dead() through
9006 	 * scx_tasks_lock.
9007 	 */
9008 	percpu_down_write(&scx_fork_rwsem);
9009 	scx_task_iter_start(&sti, NULL);
9010 	while ((p = scx_task_iter_next_locked(&sti))) {
9011 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
9012 		const struct sched_class *old_class = p->sched_class;
9013 		const struct sched_class *new_class = scx_setscheduler_class(p);
9014 
9015 		if (scx_get_task_state(p) != SCX_TASK_READY)
9016 			continue;
9017 
9018 		if (old_class != new_class)
9019 			queue_flags |= DEQUEUE_CLASS;
9020 		if (new_class == &ext_sched_class) {
9021 			scx_prepare_task_sched_change(p);
9022 			queue_flags |= DEQUEUE_NOCLOCK;
9023 		}
9024 
9025 		scoped_guard (sched_change, p, queue_flags) {
9026 			scx_set_task_slice(p, READ_ONCE(sch->slice_dfl));
9027 			p->sched_class = new_class;
9028 		}
9029 	}
9030 	scx_task_iter_stop(&sti);
9031 	percpu_up_write(&scx_fork_rwsem);
9032 
9033 	scx_bypass(sch, false);
9034 
9035 	if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) {
9036 		WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE);
9037 		ret = -EBUSY;
9038 		goto err_disable;
9039 	}
9040 
9041 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
9042 		static_branch_enable(&__scx_switched_all);
9043 
9044 	/*
9045 	 * Detach the fair_server bandwidth reservation now that the switch
9046 	 * is fully committed. In full mode (!SCX_OPS_SWITCH_PARTIAL) no
9047 	 * task will ever run in the fair class, so give that bandwidth
9048 	 * back to the RT class. The matching ext_server attach already
9049 	 * happened earlier; this only releases bandwidth and cannot fail.
9050 	 *
9051 	 * In partial mode keep fair_server attached.
9052 	 */
9053 	if (scx_switched_all()) {
9054 		for_each_possible_cpu(cpu) {
9055 			struct rq *rq = cpu_rq(cpu);
9056 
9057 			guard(rq_lock_irqsave)(rq);
9058 			update_rq_clock(rq);
9059 			dl_server_detach_bw(&rq->fair_server);
9060 		}
9061 	}
9062 
9063 	pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n",
9064 		sch->ops.name, scx_switched_all() ? "" : " (partial)");
9065 	kobject_uevent(&sch->kobj, KOBJ_ADD);
9066 	mutex_unlock(&scx_enable_mutex);
9067 
9068 	atomic_long_inc(&scx_enable_seq);
9069 
9070 	cmd->ret = 0;
9071 	return;
9072 
9073 err_free_tid_hash:
9074 	if (ops->flags & SCX_OPS_TID_TO_TASK)
9075 		rhashtable_free_and_destroy(&scx_tid_hash, NULL, NULL);
9076 err_free_ksyncs:
9077 	free_kick_syncs();
9078 err_unlock:
9079 	mutex_unlock(&scx_enable_mutex);
9080 	cmd->ret = ret;
9081 	return;
9082 
9083 err_disable_unlock_all:
9084 	scx_cgroup_unlock();
9085 	percpu_up_write(&scx_fork_rwsem);
9086 	/* we'll soon enter disable path, keep bypass on */
9087 err_disable:
9088 	mutex_unlock(&scx_enable_mutex);
9089 	/*
9090 	 * Returning an error code here would not pass all the error information
9091 	 * to userspace. Record errno using scx_error() for cases scx_error()
9092 	 * wasn't already invoked and exit indicating success so that the error
9093 	 * is notified through ops.exit() with all the details.
9094 	 *
9095 	 * Flush scx_disable_work to ensure that error is reported before init
9096 	 * completion. sch's base reference will be put by bpf_scx_unreg().
9097 	 */
9098 	scx_error(sch, "scx_root_enable() failed (%d)", ret);
9099 	scx_flush_disable_work(sch);
9100 	cmd->ret = 0;
9101 }
9102 
9103 static s32 scx_enable(struct scx_enable_cmd *cmd, struct bpf_link *link)
9104 {
9105 	static struct kthread_worker *helper;
9106 	static DEFINE_MUTEX(helper_mutex);
9107 
9108 	if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT)) {
9109 		pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n");
9110 		return -EINVAL;
9111 	}
9112 
9113 	if (!READ_ONCE(helper)) {
9114 		mutex_lock(&helper_mutex);
9115 		if (!helper) {
9116 			struct kthread_worker *w =
9117 				kthread_run_worker(0, "scx_enable_helper");
9118 			if (IS_ERR_OR_NULL(w)) {
9119 				mutex_unlock(&helper_mutex);
9120 				return -ENOMEM;
9121 			}
9122 			sched_set_fifo(w->task);
9123 			WRITE_ONCE(helper, w);
9124 		}
9125 		mutex_unlock(&helper_mutex);
9126 	}
9127 
9128 #ifdef CONFIG_EXT_SUB_SCHED
9129 	if (cmd->ops->sub_cgroup_id > 1)
9130 		kthread_init_work(&cmd->work, scx_sub_enable_workfn);
9131 	else
9132 #endif	/* CONFIG_EXT_SUB_SCHED */
9133 		kthread_init_work(&cmd->work, scx_root_enable_workfn);
9134 
9135 	kthread_queue_work(READ_ONCE(helper), &cmd->work);
9136 	kthread_flush_work(&cmd->work);
9137 	return cmd->ret;
9138 }
9139 
9140 
9141 /********************************************************************************
9142  * bpf_struct_ops plumbing.
9143  */
9144 #include <linux/bpf_verifier.h>
9145 #include <linux/bpf.h>
9146 #include <linux/btf.h>
9147 
9148 static const struct btf_type *task_struct_type;
9149 
9150 static bool bpf_scx_is_valid_access(int off, int size,
9151 				    enum bpf_access_type type,
9152 				    const struct bpf_prog *prog,
9153 				    struct bpf_insn_access_aux *info)
9154 {
9155 	if (type != BPF_READ)
9156 		return false;
9157 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
9158 		return false;
9159 	if (off % size != 0)
9160 		return false;
9161 
9162 	return btf_ctx_access(off, size, type, prog, info);
9163 }
9164 
9165 /* common to both forms: only scx.disallow is writable */
9166 static int bpf_scx_btf_struct_access_common(const struct bpf_reg_state *reg,
9167 					    int off, int size)
9168 {
9169 	const struct btf_type *t;
9170 
9171 	t = btf_type_by_id(reg->btf, reg->btf_id);
9172 	if (t == task_struct_type &&
9173 	    off >= offsetof(struct task_struct, scx.disallow) &&
9174 	    off + size <= offsetofend(struct task_struct, scx.disallow))
9175 		return SCALAR_VALUE;
9176 
9177 	return -EACCES;
9178 }
9179 
9180 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
9181 				     const struct bpf_reg_state *reg, int off,
9182 				     int size)
9183 {
9184 	const struct btf_type *t;
9185 
9186 	t = btf_type_by_id(reg->btf, reg->btf_id);
9187 	if (t == task_struct_type) {
9188 		if ((off >= offsetof(struct task_struct, scx.slice) &&
9189 		     off + size <= offsetofend(struct task_struct, scx.slice)) ||
9190 		    (off >= offsetof(struct task_struct, scx.dsq_vtime) &&
9191 		     off + size <= offsetofend(struct task_struct, scx.dsq_vtime)))
9192 			return SCALAR_VALUE;
9193 	}
9194 
9195 	return bpf_scx_btf_struct_access_common(reg, off, size);
9196 }
9197 
9198 /* cid-form rejects direct slice and dsq_vtime writes in favor of the kfuncs */
9199 static int bpf_scx_cid_btf_struct_access(struct bpf_verifier_log *log,
9200 					 const struct bpf_reg_state *reg, int off,
9201 					 int size)
9202 {
9203 	return bpf_scx_btf_struct_access_common(reg, off, size);
9204 }
9205 
9206 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
9207 	.get_func_proto = bpf_base_func_proto,
9208 	.is_valid_access = bpf_scx_is_valid_access,
9209 	.btf_struct_access = bpf_scx_btf_struct_access,
9210 };
9211 
9212 static const struct bpf_verifier_ops bpf_scx_cid_verifier_ops = {
9213 	.get_func_proto = bpf_base_func_proto,
9214 	.is_valid_access = bpf_scx_is_valid_access,
9215 	.btf_struct_access = bpf_scx_cid_btf_struct_access,
9216 };
9217 
9218 static int bpf_scx_init_member(const struct btf_type *t,
9219 			       const struct btf_member *member,
9220 			       void *kdata, const void *udata)
9221 {
9222 	const struct sched_ext_ops *uops = udata;
9223 	struct sched_ext_ops *ops = kdata;
9224 	u32 moff = __btf_member_bit_offset(t, member) / 8;
9225 	int ret;
9226 
9227 	switch (moff) {
9228 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
9229 		if (*(u32 *)(udata + moff) > INT_MAX)
9230 			return -E2BIG;
9231 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
9232 		return 1;
9233 	case offsetof(struct sched_ext_ops, flags):
9234 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
9235 			return -EINVAL;
9236 		ops->flags = *(u64 *)(udata + moff);
9237 		return 1;
9238 	case offsetof(struct sched_ext_ops, name):
9239 		ret = bpf_obj_name_cpy(ops->name, uops->name,
9240 				       sizeof(ops->name));
9241 		if (ret < 0)
9242 			return ret;
9243 		if (ret == 0)
9244 			return -EINVAL;
9245 		return 1;
9246 	case offsetof(struct sched_ext_ops, timeout_ms):
9247 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
9248 		    SCX_WATCHDOG_MAX_TIMEOUT)
9249 			return -E2BIG;
9250 		ops->timeout_ms = *(u32 *)(udata + moff);
9251 		return 1;
9252 	case offsetof(struct sched_ext_ops, exit_dump_len):
9253 		ops->exit_dump_len =
9254 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
9255 		return 1;
9256 	case offsetof(struct sched_ext_ops, hotplug_seq):
9257 		ops->hotplug_seq = *(u64 *)(udata + moff);
9258 		return 1;
9259 	case offsetof(struct sched_ext_ops, cid_shard_size):
9260 		ops->cid_shard_size = *(u32 *)(udata + moff);
9261 		return 1;
9262 	case offsetof(struct sched_ext_ops, rescue_bandwidth_ppt): {
9263 		u32 bw_ppt = *(u32 *)(udata + moff);
9264 
9265 		if (bw_ppt > SCX_RESCUE_MAX_BW_PPT && bw_ppt != SCX_RESCUE_DISABLE)
9266 			return -E2BIG;
9267 		ops->rescue_bandwidth_ppt = bw_ppt;
9268 		return 1;
9269 	}
9270 	case offsetof(struct sched_ext_ops, rescue_quantum_us): {
9271 		u32 quantum_us = *(u32 *)(udata + moff);
9272 
9273 		if (quantum_us > SCX_RESCUE_MAX_QUANTUM_US)
9274 			return -E2BIG;
9275 		if (quantum_us && quantum_us < SCX_RESCUE_MIN_QUANTUM_US)
9276 			return -EINVAL;
9277 		ops->rescue_quantum_us = quantum_us;
9278 		return 1;
9279 	}
9280 #ifdef CONFIG_EXT_SUB_SCHED
9281 	case offsetof(struct sched_ext_ops, sub_cgroup_id):
9282 		ops->sub_cgroup_id = *(u64 *)(udata + moff);
9283 		return 1;
9284 #endif	/* CONFIG_EXT_SUB_SCHED */
9285 	}
9286 
9287 	return 0;
9288 }
9289 
9290 static int bpf_scx_check_member(const struct btf_type *t,
9291 				const struct btf_member *member,
9292 				const struct bpf_prog *prog)
9293 {
9294 	u32 moff = __btf_member_bit_offset(t, member) / 8;
9295 
9296 	switch (moff) {
9297 	case offsetof(struct sched_ext_ops, init_task):
9298 #ifdef CONFIG_EXT_GROUP_SCHED
9299 	case offsetof(struct sched_ext_ops, cgroup_init):
9300 	case offsetof(struct sched_ext_ops, cgroup_exit):
9301 	case offsetof(struct sched_ext_ops, cgroup_prep_move):
9302 	case offsetof(struct sched_ext_ops, cgroup_set_bandwidth):
9303 #endif
9304 	case offsetof(struct sched_ext_ops, cpu_online):
9305 	case offsetof(struct sched_ext_ops, cpu_offline):
9306 	case offsetof(struct sched_ext_ops, init_cids):
9307 	case offsetof(struct sched_ext_ops, init):
9308 	case offsetof(struct sched_ext_ops, exit):
9309 	case offsetof(struct sched_ext_ops, sub_attach):
9310 	case offsetof(struct sched_ext_ops, sub_detach):
9311 		break;
9312 	default:
9313 		if (prog->sleepable)
9314 			return -EINVAL;
9315 	}
9316 
9317 #ifdef CONFIG_EXT_SUB_SCHED
9318 	/*
9319 	 * Enable private stack for operations that can nest along the
9320 	 * hierarchy.
9321 	 *
9322 	 * XXX - Ideally, we should only do this for scheds that allow
9323 	 * sub-scheds and sub-scheds themselves but I don't know how to access
9324 	 * struct_ops from here.
9325 	 */
9326 	if (bpf_jit_supports_private_stack()) {
9327 		switch (moff) {
9328 		case offsetof(struct sched_ext_ops, dispatch):
9329 			prog->aux->priv_stack_requested = true;
9330 			prog->aux->recursion_detected = scx_pstack_recursion_on_dispatch;
9331 			break;
9332 		case offsetof(struct sched_ext_ops, sub_caps_updated):
9333 			prog->aux->priv_stack_requested = true;
9334 			prog->aux->recursion_detected = scx_pstack_recursion_on_caps_updated;
9335 			break;
9336 		}
9337 	}
9338 #endif	/* CONFIG_EXT_SUB_SCHED */
9339 
9340 	return 0;
9341 }
9342 
9343 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
9344 {
9345 	struct scx_enable_cmd cmd = { .ops = kdata };
9346 
9347 	return scx_enable(&cmd, link);
9348 }
9349 
9350 struct scx_arena_scan {
9351 	struct bpf_map	*arena;
9352 	int		err;
9353 };
9354 
9355 /*
9356  * The verifier enforces one arena per BPF program, so each struct_ops
9357  * member prog contributes at most one arena via bpf_prog_arena().
9358  * Require all non-NULL contributions to match.
9359  */
9360 static int scx_arena_scan_prog(struct bpf_prog *prog, void *data)
9361 {
9362 	struct scx_arena_scan *s = data;
9363 	struct bpf_map *arena = NULL;
9364 
9365 	/* arena.o, which defines these, is built only on MMU && 64BIT */
9366 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
9367 	arena = bpf_prog_arena(prog);
9368 #endif
9369 	if (!arena)
9370 		return 0;
9371 	if (s->arena && s->arena != arena) {
9372 		s->err = -EINVAL;
9373 		return 1;
9374 	}
9375 	s->arena = arena;
9376 	return 0;
9377 }
9378 
9379 static int bpf_scx_reg_cid(void *kdata, struct bpf_link *link)
9380 {
9381 	struct scx_enable_cmd cmd = { .ops_cid = kdata, .is_cid_type = true };
9382 	struct scx_arena_scan scan = {};
9383 	int ret;
9384 
9385 	bpf_struct_ops_for_each_prog(kdata, scx_arena_scan_prog, &scan);
9386 	if (scan.err) {
9387 		pr_err("sched_ext: cid-form scheduler uses multiple arena maps\n");
9388 		return scan.err;
9389 	}
9390 	if (!scan.arena) {
9391 		pr_err("sched_ext: cid-form scheduler must use a BPF arena map\n");
9392 		return -EINVAL;
9393 	}
9394 
9395 	bpf_map_inc(scan.arena);
9396 	cmd.arena_map = scan.arena;
9397 	ret = scx_enable(&cmd, link);
9398 	if (cmd.arena_map)		/* not consumed by scx_alloc_and_add_sched() */
9399 		bpf_map_put(cmd.arena_map);
9400 	return ret;
9401 }
9402 
9403 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
9404 {
9405 	struct sched_ext_ops *ops = kdata;
9406 	struct scx_sched *sch = rcu_dereference_protected(ops->priv, true);
9407 
9408 	scx_disable(sch, SCX_EXIT_UNREG);
9409 	scx_flush_disable_work(sch);
9410 	RCU_INIT_POINTER(ops->priv, NULL);
9411 	kobject_put(&sch->kobj);
9412 }
9413 
9414 static int bpf_scx_init(struct btf *btf)
9415 {
9416 	task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]);
9417 
9418 	return 0;
9419 }
9420 
9421 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
9422 {
9423 	/*
9424 	 * sched_ext does not support updating the actively-loaded BPF
9425 	 * scheduler, as registering a BPF scheduler can always fail if the
9426 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
9427 	 * etc. Similarly, we can always race with unregistration happening
9428 	 * elsewhere, such as with sysrq.
9429 	 */
9430 	return -EOPNOTSUPP;
9431 }
9432 
9433 static int bpf_scx_validate(void *kdata)
9434 {
9435 	return 0;
9436 }
9437 
9438 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
9439 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
9440 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
9441 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {}
9442 static void sched_ext_ops__tick(struct task_struct *p) {}
9443 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {}
9444 static void sched_ext_ops__running(struct task_struct *p) {}
9445 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {}
9446 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {}
9447 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; }
9448 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; }
9449 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {}
9450 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {}
9451 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {}
9452 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {}
9453 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {}
9454 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
9455 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {}
9456 static void sched_ext_ops__enable(struct task_struct *p) {}
9457 static void sched_ext_ops__disable(struct task_struct *p) {}
9458 #ifdef CONFIG_EXT_GROUP_SCHED
9459 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; }
9460 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {}
9461 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; }
9462 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
9463 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
9464 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
9465 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
9466 static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}
9467 #endif	/* CONFIG_EXT_GROUP_SCHED */
9468 static s32 sched_ext_ops__sub_attach(struct scx_sub_attach_args *args) { return -EINVAL; }
9469 static void sched_ext_ops__sub_detach(struct scx_sub_detach_args *args) {}
9470 static void sched_ext_ops__cpu_online(s32 cpu) {}
9471 static void sched_ext_ops__cpu_offline(s32 cpu) {}
9472 static s32 sched_ext_ops__init_cids(void) { return -EINVAL; }
9473 static s32 sched_ext_ops__init(void) { return -EINVAL; }
9474 static void sched_ext_ops__exit(struct scx_exit_info *info) {}
9475 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {}
9476 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {}
9477 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {}
9478 
9479 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
9480 	.select_cpu		= sched_ext_ops__select_cpu,
9481 	.enqueue		= sched_ext_ops__enqueue,
9482 	.dequeue		= sched_ext_ops__dequeue,
9483 	.dispatch		= sched_ext_ops__dispatch,
9484 	.tick			= sched_ext_ops__tick,
9485 	.runnable		= sched_ext_ops__runnable,
9486 	.running		= sched_ext_ops__running,
9487 	.stopping		= sched_ext_ops__stopping,
9488 	.quiescent		= sched_ext_ops__quiescent,
9489 	.yield			= sched_ext_ops__yield,
9490 	.core_sched_before	= sched_ext_ops__core_sched_before,
9491 	.set_weight		= sched_ext_ops__set_weight,
9492 	.set_cpumask		= sched_ext_ops__set_cpumask,
9493 	.update_idle		= sched_ext_ops__update_idle,
9494 	.cpu_acquire		= sched_ext_ops__cpu_acquire,
9495 	.cpu_release		= sched_ext_ops__cpu_release,
9496 	.init_task		= sched_ext_ops__init_task,
9497 	.exit_task		= sched_ext_ops__exit_task,
9498 	.enable			= sched_ext_ops__enable,
9499 	.disable		= sched_ext_ops__disable,
9500 #ifdef CONFIG_EXT_GROUP_SCHED
9501 	.cgroup_init		= sched_ext_ops__cgroup_init,
9502 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
9503 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
9504 	.cgroup_move		= sched_ext_ops__cgroup_move,
9505 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
9506 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
9507 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
9508 	.cgroup_set_idle	= sched_ext_ops__cgroup_set_idle,
9509 #endif
9510 	.sub_attach		= sched_ext_ops__sub_attach,
9511 	.sub_detach		= sched_ext_ops__sub_detach,
9512 	.cpu_online		= sched_ext_ops__cpu_online,
9513 	.cpu_offline		= sched_ext_ops__cpu_offline,
9514 	.init_cids		= sched_ext_ops__init_cids,
9515 	.init			= sched_ext_ops__init,
9516 	.exit			= sched_ext_ops__exit,
9517 	.dump			= sched_ext_ops__dump,
9518 	.dump_cpu		= sched_ext_ops__dump_cpu,
9519 	.dump_task		= sched_ext_ops__dump_task,
9520 };
9521 
9522 static struct bpf_struct_ops bpf_sched_ext_ops = {
9523 	.verifier_ops = &bpf_scx_verifier_ops,
9524 	.reg = bpf_scx_reg,
9525 	.unreg = bpf_scx_unreg,
9526 	.check_member = bpf_scx_check_member,
9527 	.init_member = bpf_scx_init_member,
9528 	.init = bpf_scx_init,
9529 	.update = bpf_scx_update,
9530 	.validate = bpf_scx_validate,
9531 	.name = "sched_ext_ops",
9532 	.owner = THIS_MODULE,
9533 	.cfi_stubs = &__bpf_ops_sched_ext_ops
9534 };
9535 
9536 /*
9537  * cid-form cfi stubs. Stubs whose signatures match the cpu-form (param types
9538  * identical, only param names differ across structs) are reused. Some need
9539  * fresh stubs, set_cmask and enable due to argument differences and the
9540  * sub-sched notifiers because no cpu-form stub exists to reuse.
9541  */
9542 static void sched_ext_ops_cid__set_cmask(struct task_struct *p, const struct scx_cmask *cmask__arena) {}
9543 static void sched_ext_ops_cid__enable(struct task_struct *p, struct scx_enable_args *args) {}
9544 static void sched_ext_ops__sub_caps_updated(const struct scx_cmask *cmask__arena, u64 caps) {}
9545 static void sched_ext_ops__sub_ecaps_updated(s32 cid, u64 before, u64 after) {}
9546 static void sched_ext_ops__sub_cid_sched_updated(s32 cid, u64 sched) {}
9547 static void sched_ext_ops__sub_child_ecaps_updated(u64 cgroup_id, s32 cid, u64 before, u64 after) {}
9548 
9549 static struct sched_ext_ops_cid __bpf_ops_sched_ext_ops_cid = {
9550 	.select_cid		= sched_ext_ops__select_cpu,
9551 	.enqueue		= sched_ext_ops__enqueue,
9552 	.dequeue		= sched_ext_ops__dequeue,
9553 	.dispatch		= sched_ext_ops__dispatch,
9554 	.tick			= sched_ext_ops__tick,
9555 	.runnable		= sched_ext_ops__runnable,
9556 	.running		= sched_ext_ops__running,
9557 	.stopping		= sched_ext_ops__stopping,
9558 	.quiescent		= sched_ext_ops__quiescent,
9559 	.yield			= sched_ext_ops__yield,
9560 	.core_sched_before	= sched_ext_ops__core_sched_before,
9561 	.set_weight		= sched_ext_ops__set_weight,
9562 	.set_cmask		= sched_ext_ops_cid__set_cmask,
9563 	.update_idle		= sched_ext_ops__update_idle,
9564 	.init_task		= sched_ext_ops__init_task,
9565 	.exit_task		= sched_ext_ops__exit_task,
9566 	.enable			= sched_ext_ops_cid__enable,
9567 	.disable		= sched_ext_ops__disable,
9568 #ifdef CONFIG_EXT_GROUP_SCHED
9569 	.cpuctl_init		= sched_ext_ops__cgroup_init,
9570 	.cpuctl_exit		= sched_ext_ops__cgroup_exit,
9571 	.cpuctl_prep_move	= sched_ext_ops__cgroup_prep_move,
9572 	.cpuctl_move		= sched_ext_ops__cgroup_move,
9573 	.cpuctl_cancel_move	= sched_ext_ops__cgroup_cancel_move,
9574 	.cpuctl_set_weight	= sched_ext_ops__cgroup_set_weight,
9575 	.cpuctl_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
9576 	.cpuctl_set_idle	= sched_ext_ops__cgroup_set_idle,
9577 #endif
9578 	.sub_attach		= sched_ext_ops__sub_attach,
9579 	.sub_detach		= sched_ext_ops__sub_detach,
9580 	.sub_caps_updated	= sched_ext_ops__sub_caps_updated,
9581 	.sub_ecaps_updated	= sched_ext_ops__sub_ecaps_updated,
9582 	.sub_cid_sched_updated	= sched_ext_ops__sub_cid_sched_updated,
9583 	.sub_child_ecaps_updated = sched_ext_ops__sub_child_ecaps_updated,
9584 	.cid_online		= sched_ext_ops__cpu_online,
9585 	.cid_offline		= sched_ext_ops__cpu_offline,
9586 	.init_cids		= sched_ext_ops__init_cids,
9587 	.init			= sched_ext_ops__init,
9588 	.exit			= sched_ext_ops__exit,
9589 	.dump			= sched_ext_ops__dump,
9590 	.dump_cid		= sched_ext_ops__dump_cpu,
9591 	.dump_task		= sched_ext_ops__dump_task,
9592 };
9593 
9594 /*
9595  * The cid-form struct_ops shares all bpf_struct_ops hooks with the cpu form.
9596  * init_member, check_member, reg, unreg, etc. process kdata as the byte block
9597  * verified to match by the BUILD_BUG_ON checks in scx_init().
9598  */
9599 static struct bpf_struct_ops bpf_sched_ext_ops_cid = {
9600 	.verifier_ops = &bpf_scx_cid_verifier_ops,
9601 	.reg = bpf_scx_reg_cid,
9602 	.unreg = bpf_scx_unreg,
9603 	.check_member = bpf_scx_check_member,
9604 	.init_member = bpf_scx_init_member,
9605 	.init = bpf_scx_init,
9606 	.update = bpf_scx_update,
9607 	.validate = bpf_scx_validate,
9608 	.name = "sched_ext_ops_cid",
9609 	.owner = THIS_MODULE,
9610 	.cfi_stubs = &__bpf_ops_sched_ext_ops_cid
9611 };
9612 
9613 
9614 /********************************************************************************
9615  * System integration and init.
9616  */
9617 
9618 static void sysrq_handle_sched_ext_reset(u8 key)
9619 {
9620 	struct scx_sched *sch;
9621 
9622 	sch = rcu_dereference(scx_root);
9623 	if (likely(sch))
9624 		scx_disable(sch, SCX_EXIT_SYSRQ);
9625 	else
9626 		pr_info("sched_ext: BPF schedulers not loaded\n");
9627 }
9628 
9629 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
9630 	.handler	= sysrq_handle_sched_ext_reset,
9631 	.help_msg	= "reset-sched-ext(S)",
9632 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
9633 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
9634 };
9635 
9636 static void sysrq_handle_sched_ext_dump(u8 key)
9637 {
9638 	struct scx_exit_info ei = {
9639 		.kind		= SCX_EXIT_NONE,
9640 		.exit_cpu	= -1,
9641 		.reason		= "SysRq-D",
9642 	};
9643 	struct scx_sched *sch;
9644 
9645 	list_for_each_entry_rcu(sch, &scx_sched_all, all)
9646 		scx_dump_state(sch, &ei, 0, false);
9647 }
9648 
9649 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
9650 	.handler	= sysrq_handle_sched_ext_dump,
9651 	.help_msg	= "dump-sched-ext(D)",
9652 	.action_msg	= "Trigger sched_ext debug dump",
9653 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
9654 };
9655 
9656 static bool can_skip_idle_kick(struct rq *rq)
9657 {
9658 	lockdep_assert_rq_held(rq);
9659 
9660 	/*
9661 	 * We can skip idle kicking if @rq is going to go through at least one
9662 	 * full SCX scheduling cycle before going idle. Just checking whether
9663 	 * curr is not idle is insufficient because we could be racing
9664 	 * dispatch_one() trying to pull the next task from a remote rq, which
9665 	 * may fail, and @rq may become idle afterwards.
9666 	 *
9667 	 * The race window is small and we don't and can't guarantee that @rq is
9668 	 * only kicked while idle anyway. Skip only when sure.
9669 	 */
9670 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_DISPATCH);
9671 }
9672 
9673 static bool kick_one_cpu(s32 cpu, struct scx_sched_pcpu *pcpu, struct rq *this_rq,
9674 			 unsigned long *ksyncs)
9675 {
9676 	struct rq *rq = cpu_rq(cpu);
9677 	struct scx_rq *this_scx = &this_rq->scx;
9678 	struct rq_flags rf;
9679 	const struct sched_class *cur_class;
9680 	bool should_wait = false;
9681 	bool kickable;
9682 	bool preempt, preempt_lazy, wait, immediate;
9683 
9684 	rq_lock_irqsave(rq, &rf);
9685 	cur_class = rq->donor->sched_class;
9686 	preempt = cpumask_test_cpu(cpu, pcpu->cpus_to_preempt);
9687 	preempt_lazy = cpumask_test_cpu(cpu, pcpu->cpus_to_preempt_lazy);
9688 	wait = cpumask_test_cpu(cpu, pcpu->cpus_to_wait);
9689 	/*
9690 	 * Immediate preemption, waiting and a plain kick take precedence over
9691 	 * lazy preemption. The lazy request still clears the slice, so all
9692 	 * accumulated requests are served.
9693 	 */
9694 	immediate = preempt || wait || cpumask_test_cpu(cpu, pcpu->cpus_to_kick);
9695 
9696 	/*
9697 	 * During CPU hotplug, a CPU may depend on kicking itself to make
9698 	 * forward progress. Allow kicking self regardless of online state. If
9699 	 * @cpu is running a higher class task, we have no control over @cpu.
9700 	 * Skip kicking. A sub-sched lacking baseline access on @cid has no
9701 	 * business forcing a reschedule there - skip. This is the authoritative
9702 	 * cap check: ecaps is read here under @rq's lock.
9703 	 */
9704 	kickable = (cpu_online(cpu) || cpu == cpu_of(this_rq)) &&
9705 		   !sched_class_above(cur_class, &ext_sched_class);
9706 
9707 	if (kickable && !scx_missing_caps(pcpu->sch, cpu, SCX_CAP_BASE)) {
9708 		if (preempt || preempt_lazy) {
9709 			if (cur_class == &ext_sched_class) {
9710 				u64 caps = scx_caps_for_preempt(pcpu->sch, rq, 0);
9711 
9712 				if (unlikely(scx_missing_caps(pcpu->sch, cpu, caps))) {
9713 					__scx_add_event(pcpu->sch, SCX_EV_SUB_PREEMPT_DENIED, 1);
9714 					/* degrade to a plain, immediate kick */
9715 					immediate = true;
9716 				} else if (unlikely(!scx_set_task_slice(rq->donor, 0))) {
9717 					__scx_add_event(pcpu->sch, SCX_EV_SLICE_DENIED, 1);
9718 				}
9719 			}
9720 			cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt);
9721 			cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt_lazy);
9722 		}
9723 
9724 		if (wait) {
9725 			if (cur_class == &ext_sched_class) {
9726 				cpumask_set_cpu(cpu, this_scx->cpus_to_sync);
9727 				ksyncs[cpu] = rq->scx.kick_sync;
9728 				should_wait = true;
9729 			}
9730 			cpumask_clear_cpu(cpu, pcpu->cpus_to_wait);
9731 		}
9732 
9733 		if (immediate)
9734 			resched_curr(rq);
9735 		else
9736 			scx_resched_curr_lazy(rq);
9737 	} else {
9738 		/* a kickable cpu was skipped solely for the missing caps */
9739 		if (kickable)
9740 			__scx_add_event(pcpu->sch, SCX_EV_SUB_KICK_DENIED, 1);
9741 		cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt);
9742 		cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt_lazy);
9743 		cpumask_clear_cpu(cpu, pcpu->cpus_to_wait);
9744 	}
9745 
9746 	scx_rq_lock_drop(rq);
9747 	rq_unlock_irqrestore(rq, &rf);
9748 
9749 	return should_wait;
9750 }
9751 
9752 static void kick_one_cpu_if_idle(s32 cpu, struct scx_sched_pcpu *pcpu,
9753 				 struct rq *this_rq)
9754 {
9755 	struct rq *rq = cpu_rq(cpu);
9756 	unsigned long flags;
9757 
9758 	raw_spin_rq_lock_irqsave(rq, flags);
9759 
9760 	/* idle kicks need baseline access too, see kick_one_cpu() */
9761 	if (!can_skip_idle_kick(rq) &&
9762 	    (cpu_online(cpu) || cpu == cpu_of(this_rq))) {
9763 		if (likely(!scx_missing_caps(pcpu->sch, cpu, SCX_CAP_BASE)))
9764 			resched_curr(rq);
9765 		else
9766 			__scx_add_event(pcpu->sch, SCX_EV_SUB_KICK_DENIED, 1);
9767 	}
9768 
9769 	scx_rq_lock_drop(rq);
9770 	raw_spin_rq_unlock_irqrestore(rq, flags);
9771 }
9772 
9773 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
9774 {
9775 	struct rq *this_rq = this_rq();
9776 	struct scx_rq *this_scx = &this_rq->scx;
9777 	struct scx_kick_syncs __rcu *ksyncs_pcpu = __this_cpu_read(scx_kick_syncs);
9778 	struct scx_sched_pcpu *pcpu, *tmp;
9779 	bool should_wait = false;
9780 	unsigned long *ksyncs;
9781 	s32 cpu;
9782 
9783 	/* can race with free_kick_syncs() during scheduler disable */
9784 	if (unlikely(!ksyncs_pcpu))
9785 		return;
9786 
9787 	ksyncs = rcu_dereference_bh(ksyncs_pcpu)->syncs;
9788 
9789 	/*
9790 	 * Walk scheds with pending kicks on this cpu. scx_kick_cpu() adds to
9791 	 * the list under local_irq_save() and only this irq_work consumes it.
9792 	 * A plain list without locking is sufficient.
9793 	 */
9794 	list_for_each_entry_safe(pcpu, tmp, &this_scx->sched_pcpus_to_kick, to_kick_node) {
9795 		list_del_init(&pcpu->to_kick_node);
9796 
9797 		for_each_cpu_or(cpu, pcpu->cpus_to_kick, pcpu->cpus_to_preempt_lazy) {
9798 			should_wait |= kick_one_cpu(cpu, pcpu, this_rq, ksyncs);
9799 			cpumask_clear_cpu(cpu, pcpu->cpus_to_kick);
9800 			cpumask_clear_cpu(cpu, pcpu->cpus_to_kick_if_idle);
9801 		}
9802 
9803 		for_each_cpu(cpu, pcpu->cpus_to_kick_if_idle) {
9804 			kick_one_cpu_if_idle(cpu, pcpu, this_rq);
9805 			cpumask_clear_cpu(cpu, pcpu->cpus_to_kick_if_idle);
9806 		}
9807 	}
9808 
9809 	/*
9810 	 * Can't wait in hardirq — kick_sync can't advance, deadlocking if
9811 	 * CPUs wait for each other. Defer to kick_sync_wait_bal_cb().
9812 	 */
9813 	if (should_wait) {
9814 		raw_spin_rq_lock(this_rq);
9815 		this_scx->kick_sync_pending = true;
9816 		resched_curr(this_rq);
9817 		scx_rq_lock_drop(this_rq);
9818 		raw_spin_rq_unlock(this_rq);
9819 	}
9820 }
9821 
9822 /**
9823  * print_scx_info - print out sched_ext scheduler state
9824  * @log_lvl: the log level to use when printing
9825  * @p: target task
9826  *
9827  * If a sched_ext scheduler is enabled, print the name and state of the
9828  * scheduler. If @p is on sched_ext, print further information about the task.
9829  *
9830  * This function can be safely called on any task as long as the task_struct
9831  * itself is accessible. While safe, this function isn't synchronized and may
9832  * print out mixups or garbages of limited length.
9833  */
9834 void print_scx_info(const char *log_lvl, struct task_struct *p)
9835 {
9836 	struct scx_sched *sch;
9837 	enum scx_enable_state state = scx_enable_state();
9838 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
9839 	char runnable_at_buf[22] = "?";
9840 	struct sched_class *class;
9841 	unsigned long runnable_at;
9842 
9843 	guard(rcu)();
9844 
9845 	sch = scx_task_sched_rcu(p);
9846 
9847 	if (!sch)
9848 		return;
9849 
9850 	/*
9851 	 * Carefully check if the task was running on sched_ext, and then
9852 	 * carefully copy the time it's been runnable, and its state.
9853 	 */
9854 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
9855 	    class != &ext_sched_class) {
9856 		printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name,
9857 		       scx_enable_state_str[state], all);
9858 		return;
9859 	}
9860 
9861 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
9862 				      sizeof(runnable_at)))
9863 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
9864 			  jiffies_delta_msecs(runnable_at, jiffies));
9865 
9866 	/* print everything onto one line to conserve console space */
9867 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
9868 	       log_lvl, sch->ops.name, scx_enable_state_str[state], all,
9869 	       runnable_at_buf);
9870 }
9871 
9872 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr)
9873 {
9874 	struct scx_sched *sch;
9875 
9876 	/* track the PM cycle whether or not a root is loaded */
9877 	switch (event) {
9878 	case PM_HIBERNATION_PREPARE:
9879 	case PM_SUSPEND_PREPARE:
9880 	case PM_RESTORE_PREPARE:
9881 		scx_sub_pm_begin();
9882 		break;
9883 	case PM_POST_HIBERNATION:
9884 	case PM_POST_SUSPEND:
9885 	case PM_POST_RESTORE:
9886 		scx_sub_pm_end();
9887 		break;
9888 	}
9889 
9890 	guard(rcu)();
9891 
9892 	sch = rcu_dereference(scx_root);
9893 	if (!sch)
9894 		return NOTIFY_OK;
9895 
9896 	/*
9897 	 * SCX schedulers often have userspace components which are sometimes
9898 	 * involved in critial scheduling paths. PM operations involve freezing
9899 	 * userspace which can lead to scheduling misbehaviors including stalls.
9900 	 * Let's bypass while PM operations are in progress.
9901 	 */
9902 	switch (event) {
9903 	case PM_HIBERNATION_PREPARE:
9904 	case PM_SUSPEND_PREPARE:
9905 	case PM_RESTORE_PREPARE:
9906 		scx_bypass(sch, true);
9907 		break;
9908 	case PM_POST_HIBERNATION:
9909 	case PM_POST_SUSPEND:
9910 	case PM_POST_RESTORE:
9911 		scx_bypass(sch, false);
9912 		break;
9913 	}
9914 
9915 	return NOTIFY_OK;
9916 }
9917 
9918 static struct notifier_block scx_pm_notifier = {
9919 	.notifier_call = scx_pm_handler,
9920 };
9921 
9922 void __init init_sched_ext_class(void)
9923 {
9924 	s32 cpu, v;
9925 
9926 	/*
9927 	 * The following is to prevent the compiler from optimizing out the enum
9928 	 * definitions so that BPF scheduler implementations can use them
9929 	 * through the generated vmlinux.h.
9930 	 */
9931 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT |
9932 		   SCX_TG_ONLINE);
9933 
9934 	scx_idle_init_masks();
9935 
9936 	for_each_possible_cpu(cpu) {
9937 		struct rq *rq = cpu_rq(cpu);
9938 		int  n = cpu_to_node(cpu);
9939 
9940 		/* local_dsq's sch will be set during scx_root_enable() */
9941 		BUG_ON(scx_init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL, NULL));
9942 		BUG_ON(scx_init_dsq(&rq->scx.reject_dsq, SCX_DSQ_REJECT, NULL));
9943 #ifdef CONFIG_EXT_SUB_SCHED
9944 		scx_rescue_init(rq);
9945 #endif
9946 
9947 		INIT_LIST_HEAD(&rq->scx.runnable_list);
9948 		INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals);
9949 
9950 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_sync, GFP_KERNEL, n));
9951 		INIT_LIST_HEAD(&rq->scx.sched_pcpus_to_kick);
9952 		raw_spin_lock_init(&rq->scx.deferred_reenq_lock);
9953 		INIT_LIST_HEAD(&rq->scx.deferred_reenq_locals);
9954 		INIT_LIST_HEAD(&rq->scx.deferred_reenq_users);
9955 		rq->scx.deferred_irq_work = IRQ_WORK_INIT_HARD(deferred_irq_workfn);
9956 		rq->scx.kick_cpus_irq_work = IRQ_WORK_INIT_HARD(kick_cpus_irq_workfn);
9957 		rq->scx.resched_irq_work = IRQ_WORK_INIT_HARD(resched_irq_workfn);
9958 
9959 		if (cpu_online(cpu))
9960 			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
9961 	}
9962 
9963 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
9964 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
9965 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
9966 
9967 #ifdef CONFIG_EXT_SUB_SCHED
9968 	BUG_ON(rhashtable_init(&scx_sched_hash, &scx_sched_hash_params));
9969 #endif	/* CONFIG_EXT_SUB_SCHED */
9970 }
9971 
9972 
9973 /********************************************************************************
9974  * Helpers that can be called from the BPF scheduler.
9975  */
9976 static bool scx_vet_enq_flags(struct scx_sched *sch, u64 dsq_id, u64 *enq_flags)
9977 {
9978 	bool is_local = dsq_id == SCX_DSQ_LOCAL ||
9979 		(dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON;
9980 
9981 	if (unlikely(*enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
9982 		scx_error(sch, "invalid enq_flags 0x%llx", *enq_flags);
9983 		return false;
9984 	}
9985 
9986 	if (*enq_flags & SCX_ENQ_IMMED) {
9987 		if (unlikely(!is_local)) {
9988 			scx_error(sch, "SCX_ENQ_IMMED on a non-local DSQ 0x%llx", dsq_id);
9989 			return false;
9990 		}
9991 	} else if ((sch->ops.flags & SCX_OPS_ALWAYS_ENQ_IMMED) && is_local) {
9992 		*enq_flags |= SCX_ENQ_IMMED;
9993 	}
9994 
9995 	if (unlikely((*enq_flags & SCX_ENQ_RESCUE) && !is_local)) {
9996 		scx_error(sch, "SCX_ENQ_RESCUE on a non-local DSQ 0x%llx", dsq_id);
9997 		return false;
9998 	}
9999 
10000 	return true;
10001 }
10002 
10003 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p,
10004 				    u64 dsq_id, u64 *enq_flags)
10005 {
10006 	lockdep_assert_irqs_disabled();
10007 
10008 	if (unlikely(!p)) {
10009 		scx_error(sch, "called with NULL task");
10010 		return false;
10011 	}
10012 
10013 	/* see SCX_EV_INSERT_NOT_OWNED definition */
10014 	if (unlikely(!scx_task_on_sched(sch, p))) {
10015 		__scx_add_event(sch, SCX_EV_INSERT_NOT_OWNED, 1);
10016 		return false;
10017 	}
10018 
10019 	if (!scx_vet_enq_flags(sch, dsq_id, enq_flags))
10020 		return false;
10021 
10022 	return true;
10023 }
10024 
10025 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p,
10026 				  u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
10027 {
10028 	struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
10029 	struct task_struct *ddsp_task;
10030 
10031 	ddsp_task = __this_cpu_read(direct_dispatch_task);
10032 	if (ddsp_task) {
10033 		mark_direct_dispatch(sch, ddsp_task, p, dsq_id, slice, vtime, enq_flags);
10034 		return;
10035 	}
10036 
10037 	if (unlikely(dspc->cursor >= sch->dsp_max_batch)) {
10038 		scx_error(sch, "dispatch buffer overflow");
10039 		return;
10040 	}
10041 
10042 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
10043 		.task = p,
10044 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
10045 		.dsq_id = dsq_id,
10046 		.slice = slice,
10047 		.vtime = vtime,
10048 		.enq_flags = enq_flags,
10049 	};
10050 }
10051 
10052 __bpf_kfunc_start_defs();
10053 
10054 /**
10055  * scx_bpf_dsq_insert___v2 - Insert a task into the FIFO queue of a DSQ
10056  * @p: task_struct to insert
10057  * @dsq_id: DSQ to insert into
10058  * @slice: duration @p can run for in nsecs, 0 to keep the current value
10059  * @enq_flags: SCX_ENQ_*
10060  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10061  *
10062  * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to
10063  * call this function spuriously. Can be called from ops.enqueue(),
10064  * ops.select_cpu(), and ops.dispatch().
10065  *
10066  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
10067  * and @p must match the task being enqueued.
10068  *
10069  * When called from ops.select_cpu(), @enq_flags and @dsq_id are stored, and @p
10070  * will be directly inserted into the corresponding dispatch queue after
10071  * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be
10072  * inserted into the local DSQ of the CPU returned by ops.select_cpu().
10073  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
10074  * task is inserted.
10075  *
10076  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
10077  * and this function can be called up to ops.dispatch_max_batch times to insert
10078  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
10079  * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the
10080  * counter.
10081  *
10082  * This function doesn't have any locking restrictions and may be called under
10083  * BPF locks (in the future when BPF introduces more flexible locking).
10084  *
10085  * @p is allowed to run for @slice. The scheduling path is triggered on slice
10086  * exhaustion. If zero, the current residual slice is maintained. If
10087  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
10088  * scx_bpf_kick_cpu() to trigger scheduling.
10089  *
10090  * Returns %true on successful insertion, %false on failure. On the root
10091  * scheduler, %false return triggers scheduler abort and the caller doesn't need
10092  * to check the return value.
10093  */
10094 __bpf_kfunc bool scx_bpf_dsq_insert___v2(struct task_struct *p, u64 dsq_id,
10095 					 u64 slice, u64 enq_flags,
10096 					 const struct bpf_prog_aux *aux)
10097 {
10098 	struct scx_sched *sch;
10099 
10100 	guard(rcu)();
10101 	sch = scx_prog_sched(aux);
10102 	if (unlikely(!sch))
10103 		return false;
10104 
10105 	if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags))
10106 		return false;
10107 
10108 	scx_dsq_insert_commit(sch, p, dsq_id, slice, 0, enq_flags);
10109 
10110 	return true;
10111 }
10112 
10113 /*
10114  * COMPAT: Will be removed in v6.23 along with the ___v2 suffix.
10115  */
10116 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id,
10117 				    u64 slice, u64 enq_flags,
10118 				    const struct bpf_prog_aux *aux)
10119 {
10120 	scx_bpf_dsq_insert___v2(p, dsq_id, slice, enq_flags, aux);
10121 }
10122 
10123 static bool scx_dsq_insert_vtime(struct scx_sched *sch, struct task_struct *p,
10124 				 u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
10125 {
10126 	if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags))
10127 		return false;
10128 
10129 	scx_dsq_insert_commit(sch, p, dsq_id, slice, vtime, enq_flags | SCX_ENQ_DSQ_PRIQ);
10130 
10131 	return true;
10132 }
10133 
10134 struct scx_bpf_dsq_insert_vtime_args {
10135 	/* @p can't be packed together as KF_RCU is not transitive */
10136 	u64			dsq_id;
10137 	u64			slice;
10138 	u64			vtime;
10139 	u64			enq_flags;
10140 };
10141 
10142 /**
10143  * __scx_bpf_dsq_insert_vtime - Arg-wrapped vtime DSQ insertion
10144  * @p: task_struct to insert
10145  * @args: struct containing the rest of the arguments
10146  *       @args->dsq_id: DSQ to insert into
10147  *       @args->slice: duration @p can run for in nsecs, 0 to keep the current value
10148  *       @args->vtime: @p's ordering inside the vtime-sorted queue of the target DSQ
10149  *       @args->enq_flags: SCX_ENQ_*
10150  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10151  *
10152  * Wrapper kfunc that takes arguments via struct to work around BPF's 5 argument
10153  * limit. BPF programs should use scx_bpf_dsq_insert_vtime() which is provided
10154  * as an inline wrapper in common.bpf.h.
10155  *
10156  * Insert @p into the vtime priority queue of the DSQ identified by
10157  * @args->dsq_id. Tasks queued into the priority queue are ordered by
10158  * @args->vtime. All other aspects are identical to scx_bpf_dsq_insert().
10159  *
10160  * @args->vtime ordering is according to time_before64() which considers
10161  * wrapping. A numerically larger vtime may indicate an earlier position in the
10162  * ordering and vice-versa. vtime is a rolling cursor and values used for
10163  * ordering within a given DSQ should stay less than 2^63 apart for
10164  * time_before64() ordering to remain well-defined.
10165  *
10166  * A DSQ can only be used as a FIFO or priority queue at any given time and this
10167  * function must not be called on a DSQ which already has one or more FIFO tasks
10168  * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and
10169  * SCX_DSQ_GLOBAL) cannot be used as priority queues.
10170  *
10171  * Returns %true on successful insertion, %false on failure. On the root
10172  * scheduler, %false return triggers scheduler abort and the caller doesn't need
10173  * to check the return value.
10174  */
10175 __bpf_kfunc bool
10176 __scx_bpf_dsq_insert_vtime(struct task_struct *p,
10177 			   struct scx_bpf_dsq_insert_vtime_args *args,
10178 			   const struct bpf_prog_aux *aux)
10179 {
10180 	struct scx_sched *sch;
10181 
10182 	guard(rcu)();
10183 
10184 	sch = scx_prog_sched(aux);
10185 	if (unlikely(!sch))
10186 		return false;
10187 
10188 	return scx_dsq_insert_vtime(sch, p, args->dsq_id, args->slice,
10189 				    args->vtime, args->enq_flags);
10190 }
10191 
10192 /*
10193  * COMPAT: Will be removed in v6.23.
10194  */
10195 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id,
10196 					  u64 slice, u64 vtime, u64 enq_flags)
10197 {
10198 	struct scx_sched *sch;
10199 
10200 	guard(rcu)();
10201 
10202 	sch = rcu_dereference(scx_root);
10203 	if (unlikely(!sch))
10204 		return;
10205 
10206 #ifdef CONFIG_EXT_SUB_SCHED
10207 	/*
10208 	 * Disallow if any sub-scheds are attached. There is no way to tell
10209 	 * which scheduler called us, so error out @p's scheduler -- read it
10210 	 * under RCU as @p's locks aren't necessarily held here. @p may be a
10211 	 * task past sched_ext_dead() or an idle task, in which case its
10212 	 * scheduler can't be determined and there is nothing obviously wrong
10213 	 * to report; just refuse the call.
10214 	 */
10215 	if (unlikely(!list_empty(&sch->children))) {
10216 		struct scx_sched *tsch = scx_task_sched_rcu(p);
10217 
10218 		if (tsch)
10219 			scx_error(tsch, "__scx_bpf_dsq_insert_vtime() must be used");
10220 		return;
10221 	}
10222 #endif
10223 
10224 	scx_dsq_insert_vtime(sch, p, dsq_id, slice, vtime, enq_flags);
10225 }
10226 
10227 __bpf_kfunc_end_defs();
10228 
10229 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
10230 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_IMPLICIT_ARGS | KF_RCU)
10231 BTF_ID_FLAGS(func, scx_bpf_dsq_insert___v2, KF_IMPLICIT_ARGS | KF_RCU)
10232 BTF_ID_FLAGS(func, __scx_bpf_dsq_insert_vtime, KF_IMPLICIT_ARGS | KF_RCU)
10233 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU)
10234 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
10235 
10236 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
10237 	.owner			= THIS_MODULE,
10238 	.set			= &scx_kfunc_ids_enqueue_dispatch,
10239 	.filter			= scx_kfunc_context_filter,
10240 };
10241 
10242 /*
10243  * Lock @rq from a kfunc called either from ops.dispatch(), which holds the
10244  * dispatched rq's lock, or from a context holding no rq lock. Under core
10245  * scheduling, dispatch can run for a sibling rq, so the locked rq is not
10246  * necessarily this CPU's. Return the rq locked on entry, NULL if none.
10247  */
10248 static struct rq *kf_switch_rq_lock(struct rq *rq, unsigned long *flags)
10249 {
10250 	struct rq *entry_rq;
10251 
10252 	local_irq_save(*flags);
10253 
10254 	entry_rq = scx_locked_rq();
10255 	if (entry_rq) {
10256 		if (entry_rq != rq)
10257 			switch_rq_lock(entry_rq, rq);
10258 	} else {
10259 		raw_spin_rq_lock(rq);
10260 	}
10261 	return entry_rq;
10262 }
10263 
10264 /* undo kf_switch_rq_lock(), @rq is the rq locked now */
10265 static void kf_restore_rq_lock(struct rq *rq, struct rq *entry_rq, unsigned long flags)
10266 {
10267 	if (entry_rq) {
10268 		if (entry_rq != rq)
10269 			switch_rq_lock(rq, entry_rq);
10270 	} else {
10271 		scx_rq_lock_drop(rq);
10272 		raw_spin_rq_unlock_irqrestore(rq, flags);
10273 	}
10274 }
10275 
10276 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit,
10277 			 struct task_struct *p, u64 dsq_id, u64 enq_flags,
10278 			 bool priq)
10279 {
10280 	struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq;
10281 	struct scx_sched *sch;
10282 	struct rq *p_rq, *src_rq, *locked_rq;
10283 	bool dispatched = false;
10284 	unsigned long flags;
10285 
10286 	/*
10287 	 * The verifier considers an iterator slot initialized on any
10288 	 * KF_ITER_NEW return, so a BPF program may legally reach here after
10289 	 * bpf_iter_scx_dsq_new() failed and left @kit->dsq NULL.
10290 	 */
10291 	if (unlikely(!src_dsq))
10292 		return false;
10293 
10294 	sch = src_dsq->sched;
10295 
10296 	if (!scx_vet_enq_flags(sch, dsq_id, &enq_flags))
10297 		return false;
10298 
10299 	/* internal bit, can only go in after @enq_flags is vetted */
10300 	if (priq)
10301 		enq_flags |= SCX_ENQ_DSQ_PRIQ;
10302 
10303 	/*
10304 	 * If the BPF scheduler keeps calling this function repeatedly, it can
10305 	 * cause similar live-lock conditions as scx_consume_dispatch_q().
10306 	 */
10307 	if (unlikely(READ_ONCE(sch->aborting)))
10308 		return false;
10309 
10310 	src_rq = task_rq(p);
10311 	locked_rq = kf_switch_rq_lock(src_rq, &flags);
10312 
10313 	p_rq = src_rq;
10314 	raw_spin_lock(&src_dsq->lock);
10315 
10316 	/* did someone else get to it while we dropped the locks? */
10317 	if (nldsq_cursor_lost_task(&kit->cursor, src_rq, src_dsq, p)) {
10318 		raw_spin_unlock(&src_dsq->lock);
10319 		goto out;
10320 	}
10321 
10322 	/*
10323 	 * @p has been on $src_dsq and can't move anymore. If @p is not on @sch,
10324 	 * the caller didn't have authority over @p at the time of the call.
10325 	 */
10326 	if (unlikely(!scx_task_on_sched(sch, p))) {
10327 		scx_error(sch, "scx_bpf_dsq_move[_vtime]() on %s[%d] but the task belongs to a different scheduler",
10328 			  p->comm, p->pid);
10329 		raw_spin_unlock(&src_dsq->lock);
10330 		goto out;
10331 	}
10332 
10333 	/* @p is still on $src_dsq and stable, determine the destination */
10334 	dst_dsq = find_dsq_for_dispatch(sch, locked_rq ?: this_rq(), dsq_id, task_cpu(p));
10335 
10336 	/*
10337 	 * Apply vtime and slice updates before moving. @p is still on $src_dsq
10338 	 * with both $src_dsq and its task_rq locked, satisfying the write
10339 	 * rules, and the PRIQ insertion into $dst_dsq reads the new vtime.
10340 	 */
10341 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME)
10342 		p->scx.dsq_vtime = kit->vtime;
10343 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE)
10344 		scx_set_task_slice(p, kit->slice);
10345 
10346 	/* execute move */
10347 	p_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq);
10348 	dispatched = true;
10349 out:
10350 	kf_restore_rq_lock(p_rq, locked_rq, flags);
10351 
10352 	kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE |
10353 			       __SCX_DSQ_ITER_HAS_VTIME);
10354 	return dispatched;
10355 }
10356 
10357 __bpf_kfunc_start_defs();
10358 
10359 /**
10360  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
10361  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10362  *
10363  * Can only be called from ops.dispatch().
10364  */
10365 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(const struct bpf_prog_aux *aux)
10366 {
10367 	struct scx_sched *sch;
10368 
10369 	guard(rcu)();
10370 
10371 	sch = scx_prog_sched(aux);
10372 	if (unlikely(!sch))
10373 		return 0;
10374 
10375 	return sch->dsp_max_batch - __this_cpu_read(sch->pcpu->dsp_ctx.cursor);
10376 }
10377 
10378 /**
10379  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
10380  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10381  *
10382  * Cancel the latest dispatch. Can be called multiple times to cancel further
10383  * dispatches. Can only be called from ops.dispatch().
10384  */
10385 __bpf_kfunc void scx_bpf_dispatch_cancel(const struct bpf_prog_aux *aux)
10386 {
10387 	struct scx_sched *sch;
10388 	struct scx_dsp_ctx *dspc;
10389 
10390 	guard(rcu)();
10391 
10392 	sch = scx_prog_sched(aux);
10393 	if (unlikely(!sch))
10394 		return;
10395 
10396 	dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
10397 
10398 	if (dspc->cursor > 0)
10399 		dspc->cursor--;
10400 	else
10401 		scx_error(sch, "dispatch buffer underflow");
10402 }
10403 
10404 /**
10405  * scx_bpf_dsq_move_to_local___v2 - move a task from a DSQ to the current CPU's local DSQ
10406  * @dsq_id: DSQ to move task from. Must be a user-created DSQ
10407  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10408  * @enq_flags: %SCX_ENQ_*
10409  *
10410  * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's
10411  * local DSQ for execution with @enq_flags applied. Can only be called from
10412  * ops.dispatch().
10413  *
10414  * Built-in DSQs (%SCX_DSQ_GLOBAL and %SCX_DSQ_LOCAL*) are not supported as
10415  * sources. Local DSQs support reenqueueing (a task can be picked up for
10416  * execution, dequeued for property changes, or reenqueued), but the BPF
10417  * scheduler cannot directly iterate or move tasks from them. %SCX_DSQ_GLOBAL
10418  * is similar but also doesn't support reenqueueing, as it maps to multiple
10419  * per-node DSQs making the scope difficult to define; this may change in the
10420  * future.
10421  *
10422  * This function flushes the in-flight dispatches from scx_bpf_dsq_insert()
10423  * before trying to move from the specified DSQ. It may also grab rq locks and
10424  * thus can't be called under any BPF locks.
10425  *
10426  * Returns %true if a task has been moved, %false if there isn't any task to
10427  * move.
10428  */
10429 __bpf_kfunc bool scx_bpf_dsq_move_to_local___v2(u64 dsq_id, u64 enq_flags,
10430 						const struct bpf_prog_aux *aux)
10431 {
10432 	struct scx_dispatch_q *dsq;
10433 	struct scx_sched *sch;
10434 	struct scx_dsp_ctx *dspc;
10435 
10436 	guard(rcu)();
10437 
10438 	sch = scx_prog_sched(aux);
10439 	if (unlikely(!sch))
10440 		return false;
10441 
10442 	if (!scx_vet_enq_flags(sch, SCX_DSQ_LOCAL, &enq_flags))
10443 		return false;
10444 
10445 	dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
10446 
10447 	scx_flush_dispatch_buf(sch, dspc->rq);
10448 
10449 	dsq = find_user_dsq(sch, dsq_id);
10450 	if (unlikely(!dsq)) {
10451 		scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id);
10452 		return false;
10453 	}
10454 
10455 	if (scx_consume_dispatch_q(sch, dspc->rq, dsq, enq_flags)) {
10456 		/*
10457 		 * A successfully consumed task can be dequeued before it starts
10458 		 * running while the CPU is trying to migrate other dispatched
10459 		 * tasks. Bump nr_tasks to tell dispatch_one() to retry on empty
10460 		 * local DSQ.
10461 		 */
10462 		dspc->nr_tasks++;
10463 		return true;
10464 	} else {
10465 		return false;
10466 	}
10467 }
10468 
10469 /*
10470  * COMPAT: ___v2 was introduced in v7.1. Remove this and ___v2 tag in the future.
10471  */
10472 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id, const struct bpf_prog_aux *aux)
10473 {
10474 	return scx_bpf_dsq_move_to_local___v2(dsq_id, 0, aux);
10475 }
10476 
10477 /**
10478  * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs
10479  * @it__iter: DSQ iterator in progress
10480  * @slice: duration the moved task can run for in nsecs
10481  *
10482  * Override the slice of the next task that will be moved from @it__iter using
10483  * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous
10484  * slice duration is kept.
10485  */
10486 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter,
10487 					    u64 slice)
10488 {
10489 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
10490 
10491 	kit->slice = slice;
10492 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE;
10493 }
10494 
10495 /**
10496  * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs
10497  * @it__iter: DSQ iterator in progress
10498  * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ
10499  *
10500  * Override the vtime of the next task that will be moved from @it__iter using
10501  * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice
10502  * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the
10503  * override is ignored and cleared.
10504  */
10505 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter,
10506 					    u64 vtime)
10507 {
10508 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
10509 
10510 	kit->vtime = vtime;
10511 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME;
10512 }
10513 
10514 /**
10515  * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ
10516  * @it__iter: DSQ iterator in progress
10517  * @p: task to transfer
10518  * @dsq_id: DSQ to move @p to
10519  * @enq_flags: SCX_ENQ_*
10520  *
10521  * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ
10522  * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can
10523  * be the destination.
10524  *
10525  * For the transfer to be successful, @p must still be on the DSQ and have been
10526  * queued before the DSQ iteration started. This function doesn't care whether
10527  * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have
10528  * been queued before the iteration started.
10529  *
10530  * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update.
10531  *
10532  * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq
10533  * lock (e.g. BPF timers or SYSCALL programs).
10534  *
10535  * Returns %true if @p has been consumed, %false if @p had already been
10536  * consumed, dequeued, or, for sub-scheds, @dsq_id points to a disallowed local
10537  * DSQ.
10538  */
10539 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter,
10540 				  struct task_struct *p, u64 dsq_id,
10541 				  u64 enq_flags)
10542 {
10543 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
10544 			    p, dsq_id, enq_flags, false);
10545 }
10546 
10547 /**
10548  * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ
10549  * @it__iter: DSQ iterator in progress
10550  * @p: task to transfer
10551  * @dsq_id: DSQ to move @p to
10552  * @enq_flags: SCX_ENQ_*
10553  *
10554  * Transfer @p which is on the DSQ currently iterated by @it__iter to the
10555  * priority queue of the DSQ specified by @dsq_id. The destination must be a
10556  * user DSQ as only user DSQs support priority queue.
10557  *
10558  * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice()
10559  * and scx_bpf_dsq_move_set_vtime() to update.
10560  *
10561  * All other aspects are identical to scx_bpf_dsq_move(). See
10562  * scx_bpf_dsq_insert_vtime() for more information on @vtime.
10563  */
10564 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter,
10565 					struct task_struct *p, u64 dsq_id,
10566 					u64 enq_flags)
10567 {
10568 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
10569 			    p, dsq_id, enq_flags, true);
10570 }
10571 
10572 __bpf_kfunc_end_defs();
10573 
10574 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
10575 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots, KF_IMPLICIT_ARGS)
10576 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel, KF_IMPLICIT_ARGS)
10577 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local, KF_IMPLICIT_ARGS)
10578 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local___v2, KF_IMPLICIT_ARGS)
10579 /* scx_bpf_dsq_move*() also in scx_kfunc_ids_unlocked: callable from unlocked contexts */
10580 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
10581 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
10582 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
10583 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
10584 /* also in scx_kfunc_ids_unlocked, same contexts as scx_bpf_dsq_move() */
10585 BTF_ID_FLAGS(func, scx_bpf_dsq_reenq_task, KF_RCU)
10586 #ifdef CONFIG_EXT_SUB_SCHED
10587 BTF_ID_FLAGS(func, scx_bpf_sub_dispatch, KF_IMPLICIT_ARGS)
10588 #endif
10589 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
10590 
10591 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
10592 	.owner			= THIS_MODULE,
10593 	.set			= &scx_kfunc_ids_dispatch,
10594 	.filter			= scx_kfunc_context_filter,
10595 };
10596 
10597 __bpf_kfunc_start_defs();
10598 
10599 /**
10600  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
10601  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10602  *
10603  * Iterate over all of the tasks currently enqueued on the local DSQ of the
10604  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
10605  * processed tasks. Can only be called from ops.cpu_release().
10606  */
10607 __bpf_kfunc u32 scx_bpf_reenqueue_local(const struct bpf_prog_aux *aux)
10608 {
10609 	struct scx_sched *sch;
10610 	struct rq *rq;
10611 
10612 	guard(rcu)();
10613 	sch = scx_prog_sched(aux);
10614 	if (unlikely(!sch))
10615 		return 0;
10616 
10617 	rq = cpu_rq(smp_processor_id());
10618 	lockdep_assert_rq_held(rq);
10619 
10620 	return reenq_local(sch, rq, SCX_REENQ_ANY);
10621 }
10622 
10623 __bpf_kfunc_end_defs();
10624 
10625 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
10626 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local, KF_IMPLICIT_ARGS)
10627 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
10628 
10629 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
10630 	.owner			= THIS_MODULE,
10631 	.set			= &scx_kfunc_ids_cpu_release,
10632 	.filter			= scx_kfunc_context_filter,
10633 };
10634 
10635 __bpf_kfunc_start_defs();
10636 
10637 /**
10638  * scx_bpf_create_dsq - Create a custom DSQ
10639  * @dsq_id: DSQ to create
10640  * @node: NUMA node to allocate from
10641  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10642  *
10643  * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable
10644  * scx callback, and any BPF_PROG_TYPE_SYSCALL prog.
10645  */
10646 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node, const struct bpf_prog_aux *aux)
10647 {
10648 	struct scx_dispatch_q *dsq;
10649 	struct scx_sched *sch;
10650 	s32 ret;
10651 
10652 	if (unlikely(node >= (int)nr_node_ids ||
10653 		     (node < 0 && node != NUMA_NO_NODE)))
10654 		return -EINVAL;
10655 
10656 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN))
10657 		return -EINVAL;
10658 
10659 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
10660 	if (!dsq)
10661 		return -ENOMEM;
10662 
10663 	/*
10664 	 * scx_init_dsq() must be called in GFP_KERNEL context. Init it with
10665 	 * NULL @sch and update afterwards.
10666 	 */
10667 	ret = scx_init_dsq(dsq, dsq_id, NULL);
10668 	if (ret) {
10669 		kfree(dsq);
10670 		return ret;
10671 	}
10672 
10673 	rcu_read_lock();
10674 
10675 	sch = scx_prog_sched(aux);
10676 	if (sch) {
10677 		dsq->sched = sch;
10678 		ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node,
10679 						    dsq_hash_params);
10680 	} else {
10681 		ret = -ENODEV;
10682 	}
10683 
10684 	rcu_read_unlock();
10685 	if (ret) {
10686 		exit_dsq(dsq);
10687 		kfree(dsq);
10688 	}
10689 	return ret;
10690 }
10691 
10692 __bpf_kfunc_end_defs();
10693 
10694 BTF_KFUNCS_START(scx_kfunc_ids_unlocked)
10695 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_IMPLICIT_ARGS | KF_SLEEPABLE)
10696 /* also in scx_kfunc_ids_dispatch: also callable from ops.dispatch() */
10697 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
10698 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
10699 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
10700 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
10701 BTF_ID_FLAGS(func, scx_bpf_dsq_reenq_task, KF_RCU)
10702 /* also in scx_kfunc_ids_select_cpu: also callable from ops.select_cpu()/ops.enqueue() */
10703 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU)
10704 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU)
10705 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU)
10706 BTF_KFUNCS_END(scx_kfunc_ids_unlocked)
10707 
10708 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = {
10709 	.owner			= THIS_MODULE,
10710 	.set			= &scx_kfunc_ids_unlocked,
10711 	.filter			= scx_kfunc_context_filter,
10712 };
10713 
10714 __bpf_kfunc_start_defs();
10715 
10716 /**
10717  * scx_bpf_task_set_slice - Set task's time slice
10718  * @p: task of interest
10719  * @slice: time slice to set in nsecs
10720  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10721  *
10722  * Set @p's time slice. @p must be on the calling scheduler. The value is
10723  * applied whether or not the caller holds @p's rq lock - see the slice write
10724  * rules above for the ownership model.
10725  *
10726  * Raising the slice is honored only while the scheduler holds %SCX_CAP_BASE on
10727  * @p's cpu, and never on a kernel slice, see %SCX_TASK_KERNEL_SLICE. Shortening
10728  * is honored unless @p is protected, see %SCX_TASK_PROTECTED, which refuses
10729  * every write. A refused write is counted in %SCX_EV_SLICE_DENIED. On the
10730  * stashed path the slice is packed into an atomic64_t with the scheduler id and
10731  * a flag bit, so a slice too large to fit is clamped and counted in
10732  * %SCX_EV_SLICE_CLAMPED. %SCX_SLICE_INF is preserved.
10733  *
10734  * Return %true on success, %false if @p is not on the calling scheduler.
10735  */
10736 __bpf_kfunc bool scx_bpf_task_set_slice(struct task_struct *p, u64 slice,
10737 					const struct bpf_prog_aux *aux)
10738 {
10739 	struct scx_sched *sch;
10740 	struct rq *locked_rq;
10741 
10742 	guard(rcu)();
10743 	sch = scx_prog_sched(aux);
10744 	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
10745 		return false;
10746 
10747 	/*
10748 	 * Directly write only when we hold the lock of the rq @p is queued on or
10749 	 * provides the current scheduling context for. Under proxy execution,
10750 	 * rq->donor owns and consumes the slice while rq->curr executes on its
10751 	 * behalf. See the slice write rules above.
10752 	 *
10753 	 * While @p is queued on a user DSQ or in the BPF scheduler,
10754 	 * synchronization is the scheduler's responsibility. This write can
10755 	 * race a concurrent dispatch's commit, see apply_slice_vtime().
10756 	 *
10757 	 * Making this kfunc always go through the oob stash would leave the
10758 	 * commit as the only direct writer and close the race, but that would
10759 	 * require two more oob application points - the dispatch keep-prev test
10760 	 * and the tick-time expiry check.
10761 	 */
10762 	locked_rq = scx_locked_rq();
10763 	if (!locked_rq ||
10764 	    (READ_ONCE(p->scx.runnable_cpu) != cpu_of(locked_rq) &&
10765 	     !task_current_donor(locked_rq, p))) {
10766 		set_task_slice_oob(sch, p, slice);
10767 		return true;
10768 	}
10769 
10770 	/*
10771 	 * @p's rq is locked, so apply now. An extension needs baseline access
10772 	 * and is refused on a kernel slice.
10773 	 */
10774 	if (slice > p->scx.slice &&
10775 	    unlikely(scx_task_has_kernel_slice(p) ||
10776 		     scx_missing_caps(sch, cpu_of(locked_rq), SCX_CAP_BASE))) {
10777 		__scx_add_event(sch, SCX_EV_SLICE_DENIED, 1);
10778 		return true;
10779 	}
10780 
10781 	if (unlikely(!scx_set_task_slice(p, slice)))
10782 		__scx_add_event(sch, SCX_EV_SLICE_DENIED, 1);
10783 
10784 	return true;
10785 }
10786 
10787 /**
10788  * scx_bpf_task_set_dsq_vtime - Set task's virtual time for DSQ ordering
10789  * @p: task of interest
10790  * @vtime: virtual time to set
10791  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10792  *
10793  * Set @p's virtual time to @vtime. Returns %true on success, %false if the
10794  * calling scheduler doesn't have authority over @p.
10795  */
10796 __bpf_kfunc bool scx_bpf_task_set_dsq_vtime(struct task_struct *p, u64 vtime,
10797 					    const struct bpf_prog_aux *aux)
10798 {
10799 	struct scx_sched *sch;
10800 
10801 	guard(rcu)();
10802 	sch = scx_prog_sched(aux);
10803 	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
10804 		return false;
10805 
10806 	p->scx.dsq_vtime = vtime;
10807 	return true;
10808 }
10809 
10810 /**
10811  * scx_bpf_task_set_lazy_resched - Set task's tick reschedule mode
10812  * @p: task of interest
10813  * @lazy: whether slice expiry should request lazy rescheduling
10814  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10815  *
10816  * Choose whether depletion of @p's slice at the scheduler tick requests lazy or
10817  * immediate rescheduling. This is a persistent per-task policy and does not
10818  * itself clear @p's slice or request rescheduling, unlike the
10819  * %SCX_ENQ_PREEMPT_LAZY and %SCX_KICK_PREEMPT_LAZY one-shot operations.
10820  *
10821  * With lazy rescheduling enabled, a task interrupted in user space still
10822  * reschedules before returning to user space. A task interrupted in the kernel
10823  * may continue until its next return to user space or the next scheduler tick,
10824  * which promotes the request. If lazy preemption is disabled at runtime, the
10825  * request behaves like an immediate reschedule.
10826  *
10827  * @p must be on the calling scheduler.
10828  *
10829  * Return %true on success, %false if @p is not on the calling scheduler.
10830  */
10831 __bpf_kfunc bool scx_bpf_task_set_lazy_resched(struct task_struct *p, bool lazy,
10832 					       const struct bpf_prog_aux *aux)
10833 {
10834 	struct scx_sched *sch;
10835 
10836 	/*
10837 	 * clang's register locations for @lazy make pahole 1.32 drop this kfunc
10838 	 * from BTF. Keep @lazy in memory so its location names no register.
10839 	 */
10840 	barrier_data(&lazy);
10841 	guard(rcu)();
10842 	sch = scx_prog_sched(aux);
10843 	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
10844 		return false;
10845 
10846 	WRITE_ONCE(p->scx.lazy_resched, lazy);
10847 	return true;
10848 }
10849 
10850 void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags)
10851 {
10852 	struct scx_sched_pcpu *pcpu;
10853 	struct rq *this_rq;
10854 	unsigned long irq_flags;
10855 
10856 	if (!scx_kf_allowed_ctx(sch))
10857 		return;
10858 	if (unlikely(flags & ~SCX_KICK_ALL_FLAGS)) {
10859 		scx_error(sch, "invalid kick flags 0x%llx", flags);
10860 		return;
10861 	}
10862 
10863 	local_irq_save(irq_flags);
10864 
10865 	this_rq = this_rq();
10866 	pcpu = this_cpu_ptr(sch->pcpu);
10867 
10868 	/*
10869 	 * While bypassing for PM ops, IRQ handling may not be online which can
10870 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
10871 	 * IRQ status update. Suppress kicking.
10872 	 */
10873 	if (scx_bypassing(sch, cpu_of(this_rq)))
10874 		goto out;
10875 
10876 	/*
10877 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
10878 	 * rq locks. We can probably be smarter and avoid bouncing if called
10879 	 * from ops which don't hold a rq lock.
10880 	 *
10881 	 * The kick masks are owned by @sch->pcpu, so that a preempt kick can be
10882 	 * attributed to @sch.
10883 	 */
10884 	if (flags & SCX_KICK_IDLE) {
10885 		struct rq *target_rq = cpu_rq(cpu);
10886 
10887 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_PREEMPT_LAZY |
10888 				     SCX_KICK_WAIT)))
10889 			scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
10890 
10891 		if (raw_spin_rq_trylock(target_rq)) {
10892 			if (can_skip_idle_kick(target_rq)) {
10893 				scx_rq_lock_drop(target_rq);
10894 				raw_spin_rq_unlock(target_rq);
10895 				goto out;
10896 			}
10897 			scx_rq_lock_drop(target_rq);
10898 			raw_spin_rq_unlock(target_rq);
10899 		}
10900 		cpumask_set_cpu(cpu, pcpu->cpus_to_kick_if_idle);
10901 	} else {
10902 		/*
10903 		 * Accumulate requests and resolve their precedence at delivery.
10904 		 */
10905 		if (flags & SCX_KICK_PREEMPT)
10906 			cpumask_set_cpu(cpu, pcpu->cpus_to_preempt);
10907 		if (flags & SCX_KICK_PREEMPT_LAZY)
10908 			cpumask_set_cpu(cpu, pcpu->cpus_to_preempt_lazy);
10909 		if (flags & SCX_KICK_WAIT)
10910 			cpumask_set_cpu(cpu, pcpu->cpus_to_wait);
10911 		if (!(flags & SCX_KICK_PREEMPT_LAZY))
10912 			cpumask_set_cpu(cpu, pcpu->cpus_to_kick);
10913 	}
10914 
10915 	if (list_empty(&pcpu->to_kick_node))
10916 		list_add_tail(&pcpu->to_kick_node, &this_rq->scx.sched_pcpus_to_kick);
10917 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
10918 out:
10919 	local_irq_restore(irq_flags);
10920 }
10921 
10922 /**
10923  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
10924  * @cpu: cpu to kick
10925  * @flags: %SCX_KICK_* flags
10926  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10927  *
10928  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
10929  * trigger rescheduling on a busy CPU. This can be called from any online
10930  * scx_ops operation and the actual kicking is performed asynchronously through
10931  * an irq work.
10932  */
10933 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags, const struct bpf_prog_aux *aux)
10934 {
10935 	struct scx_sched *sch;
10936 
10937 	guard(rcu)();
10938 	sch = scx_prog_sched(aux);
10939 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
10940 		scx_kick_cpu(sch, cpu, flags);
10941 }
10942 
10943 /**
10944  * scx_bpf_kick_cid - Trigger reschedule on the CPU mapped to @cid
10945  * @cid: cid to kick
10946  * @flags: %SCX_KICK_* flags
10947  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10948  *
10949  * cid-addressed equivalent of scx_bpf_kick_cpu(). An invalid @cid aborts the
10950  * scheduler via scx_cid_to_cpu(). Caps are enforced on the delivery path: a
10951  * kick is dropped if the caller lacks baseline access on @cid, and a
10952  * %SCX_KICK_PREEMPT or %SCX_KICK_PREEMPT_LAZY request degrades to a plain
10953  * reschedule if the caller lacks %SCX_CAP_PREEMPT for a task outside its
10954  * subtree.
10955  */
10956 __bpf_kfunc void scx_bpf_kick_cid(s32 cid, u64 flags, const struct bpf_prog_aux *aux)
10957 {
10958 	struct scx_sched *sch;
10959 	s32 cpu;
10960 
10961 	guard(rcu)();
10962 	sch = scx_prog_sched(aux);
10963 	if (unlikely(!sch))
10964 		return;
10965 	cpu = scx_cid_to_cpu(sch, cid);
10966 	if (cpu < 0)
10967 		return;
10968 	scx_kick_cpu(sch, cpu, flags);
10969 }
10970 
10971 /**
10972  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
10973  * @dsq_id: id of the DSQ
10974  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10975  *
10976  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
10977  * -%ENOENT is returned.
10978  *
10979  * %SCX_DSQ_LOCAL resolves to the local DSQ of the rq the current scheduler
10980  * operation is locked to - e.g. the rq being dispatched for in ops.dispatch() -
10981  * or the calling CPU's when no rq is locked.
10982  */
10983 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id, const struct bpf_prog_aux *aux)
10984 {
10985 	struct scx_sched *sch;
10986 	struct scx_dispatch_q *dsq;
10987 	s32 ret;
10988 
10989 	preempt_disable();
10990 
10991 	sch = scx_prog_sched(aux);
10992 	if (unlikely(!sch)) {
10993 		ret = -ENODEV;
10994 		goto out;
10995 	}
10996 
10997 	if (dsq_id == SCX_DSQ_LOCAL) {
10998 		ret = READ_ONCE((scx_locked_rq() ?: this_rq())->scx.local_dsq.nr);
10999 		goto out;
11000 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
11001 		s32 cpu = scx_cpu_ret(sch, dsq_id & SCX_DSQ_LOCAL_CPU_MASK);
11002 
11003 		if (scx_cpu_valid(sch, cpu, NULL)) {
11004 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
11005 			goto out;
11006 		}
11007 	} else {
11008 		dsq = find_user_dsq(sch, dsq_id);
11009 		if (dsq) {
11010 			ret = READ_ONCE(dsq->nr);
11011 			goto out;
11012 		}
11013 	}
11014 	ret = -ENOENT;
11015 out:
11016 	preempt_enable();
11017 	return ret;
11018 }
11019 
11020 /**
11021  * scx_bpf_destroy_dsq - Destroy a custom DSQ
11022  * @dsq_id: DSQ to destroy
11023  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11024  *
11025  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
11026  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
11027  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
11028  * which doesn't exist. Can be called from any online scx_ops operations.
11029  */
11030 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id, const struct bpf_prog_aux *aux)
11031 {
11032 	struct scx_sched *sch;
11033 
11034 	guard(rcu)();
11035 	sch = scx_prog_sched(aux);
11036 	if (unlikely(!sch))
11037 		return;
11038 
11039 	if (!scx_kf_allowed_ctx(sch))
11040 		return;
11041 
11042 	destroy_dsq(sch, dsq_id);
11043 }
11044 
11045 /**
11046  * bpf_iter_scx_dsq_new - Create a DSQ iterator
11047  * @it: iterator to initialize
11048  * @dsq_id: DSQ to iterate
11049  * @flags: %SCX_DSQ_ITER_*
11050  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11051  *
11052  * Initialize BPF iterator @it which can be used with bpf_for_each() to walk
11053  * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes
11054  * tasks which are already queued when this function is invoked.
11055  */
11056 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id,
11057 				     u64 flags, const struct bpf_prog_aux *aux)
11058 {
11059 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
11060 	struct scx_sched *sch;
11061 
11062 	BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) >
11063 		     sizeof(struct bpf_iter_scx_dsq));
11064 	BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) !=
11065 		     __alignof__(struct bpf_iter_scx_dsq));
11066 	BUILD_BUG_ON(__SCX_DSQ_ITER_ALL_FLAGS &
11067 		     ((1U << __SCX_DSQ_LNODE_PRIV_SHIFT) - 1));
11068 
11069 	/*
11070 	 * next() and destroy() will be called regardless of the return value.
11071 	 * Always clear $kit->dsq.
11072 	 */
11073 	kit->dsq = NULL;
11074 
11075 	sch = scx_prog_sched(aux);
11076 	if (unlikely(!sch))
11077 		return -ENODEV;
11078 
11079 	if (!scx_kf_allowed_ctx(sch))
11080 		return -EDEADLK;
11081 
11082 	if (flags & ~__SCX_DSQ_ITER_USER_FLAGS)
11083 		return -EINVAL;
11084 
11085 	kit->dsq = find_user_dsq(sch, dsq_id);
11086 	if (!kit->dsq)
11087 		return -ENOENT;
11088 
11089 	kit->cursor = INIT_DSQ_LIST_CURSOR(kit->cursor, kit->dsq, flags);
11090 
11091 	return 0;
11092 }
11093 
11094 /**
11095  * bpf_iter_scx_dsq_next - Progress a DSQ iterator
11096  * @it: iterator to progress
11097  *
11098  * Return the next task. See bpf_iter_scx_dsq_new().
11099  */
11100 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it)
11101 {
11102 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
11103 	struct task_struct *p;
11104 
11105 	if (!kit->dsq || (kit->cursor.flags & __SCX_DSQ_ITER_DRAINED))
11106 		return NULL;
11107 
11108 	guard(raw_spinlock_irqsave)(&kit->dsq->lock);
11109 
11110 	p = nldsq_cursor_next_task(&kit->cursor, kit->dsq);
11111 	/*
11112 	 * nldsq_cursor_next_task() unlinks the cursor and starts from the DSQ
11113 	 * head when it is called again.  The verifier relies on an iterator
11114 	 * which returned NULL to keep returning NULL (see
11115 	 * process_iter_next_call()), so remember the drained state.
11116 	 */
11117 	if (!p)
11118 		kit->cursor.flags |= __SCX_DSQ_ITER_DRAINED;
11119 
11120 	return p;
11121 }
11122 
11123 /**
11124  * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator
11125  * @it: iterator to destroy
11126  *
11127  * Undo bpf_iter_scx_dsq_new(). If the iteration marked tasks with
11128  * scx_bpf_dsq_reenq_task(), schedule their re-enqueue.
11129  */
11130 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it)
11131 {
11132 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
11133 
11134 	if (!kit->dsq)
11135 		return;
11136 
11137 	if (!list_empty(&kit->cursor.node)) {
11138 		unsigned long flags;
11139 
11140 		raw_spin_lock_irqsave(&kit->dsq->lock, flags);
11141 		list_del_init(&kit->cursor.node);
11142 		raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
11143 	}
11144 
11145 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_REENQ) {
11146 		guard(preempt)();
11147 		schedule_dsq_reenq(kit->dsq->sched, kit->dsq, SCX_REENQ_MARKED,
11148 				   scx_locked_rq());
11149 	}
11150 
11151 	kit->dsq = NULL;
11152 }
11153 
11154 /**
11155  * scx_bpf_dsq_peek - Lockless peek at the first element.
11156  * @dsq_id: DSQ to examine.
11157  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11158  *
11159  * Read the first element in the DSQ. This is semantically equivalent to using
11160  * the DSQ iterator, but is lockfree. Of course, like any lockless operation,
11161  * this provides only a point-in-time snapshot, and the contents may change
11162  * by the time any subsequent locking operation reads the queue.
11163  *
11164  * Returns the pointer, or NULL indicates an empty queue OR internal error.
11165  */
11166 __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id,
11167 						 const struct bpf_prog_aux *aux)
11168 {
11169 	struct scx_sched *sch;
11170 	struct scx_dispatch_q *dsq;
11171 
11172 	sch = scx_prog_sched(aux);
11173 	if (unlikely(!sch))
11174 		return NULL;
11175 
11176 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) {
11177 		scx_error(sch, "peek disallowed on builtin DSQ 0x%llx", dsq_id);
11178 		return NULL;
11179 	}
11180 
11181 	dsq = find_user_dsq(sch, dsq_id);
11182 	if (unlikely(!dsq)) {
11183 		scx_error(sch, "peek on non-existent DSQ 0x%llx", dsq_id);
11184 		return NULL;
11185 	}
11186 
11187 	return rcu_dereference_all(dsq->first_task);
11188 }
11189 
11190 /**
11191  * scx_bpf_dsq_reenq - Re-enqueue tasks on a DSQ
11192  * @dsq_id: DSQ to re-enqueue
11193  * @reenq_flags: %SCX_REENQ_*
11194  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11195  *
11196  * Iterate over all of the tasks currently enqueued on the DSQ identified by
11197  * @dsq_id, and re-enqueue them in the BPF scheduler. The following DSQs are
11198  * supported:
11199  *
11200  * - Local DSQs (%SCX_DSQ_LOCAL or %SCX_DSQ_LOCAL_ON | $cpu)
11201  * - User DSQs
11202  *
11203  * Re-enqueues are performed asynchronously. Can be called from any context
11204  * except NMI. A call from NMI aborts the scheduler. A re-enqueue of an inactive
11205  * cpu's local DSQ is ignored.
11206  *
11207  * %SCX_DSQ_LOCAL resolves to the local DSQ of the rq the current scheduler
11208  * operation is locked to - e.g. the rq being dispatched for in ops.dispatch() -
11209  * or the calling CPU's when no rq is locked.
11210  */
11211 __bpf_kfunc void scx_bpf_dsq_reenq(u64 dsq_id, u64 reenq_flags,
11212 				   const struct bpf_prog_aux *aux)
11213 {
11214 	struct rq *locked_rq = scx_locked_rq();
11215 	struct scx_sched *sch;
11216 	struct scx_dispatch_q *dsq;
11217 
11218 	guard(preempt)();
11219 
11220 	sch = scx_prog_sched(aux);
11221 	if (unlikely(!sch))
11222 		return;
11223 
11224 	if (unlikely(reenq_flags & ~__SCX_REENQ_USER_MASK)) {
11225 		scx_error(sch, "invalid SCX_REENQ flags 0x%llx", reenq_flags);
11226 		return;
11227 	}
11228 
11229 	if (!scx_kf_allowed_ctx(sch))
11230 		return;
11231 
11232 	/* not specifying any filter bits is the same as %SCX_REENQ_ANY */
11233 	if (!(reenq_flags & __SCX_REENQ_FILTER_MASK))
11234 		reenq_flags |= SCX_REENQ_ANY;
11235 
11236 	dsq = find_dsq_for_dispatch(sch, locked_rq ?: this_rq(), dsq_id, smp_processor_id());
11237 	schedule_dsq_reenq(sch, dsq, reenq_flags, locked_rq);
11238 }
11239 
11240 /**
11241  * scx_bpf_dsq_reenq_task - Re-enqueue a task from a DSQ iteration
11242  * @it__iter: DSQ iterator in progress
11243  * @p: task to re-enqueue
11244  *
11245  * Mark @p, which is on the DSQ iterated by @it__iter and was queued before the
11246  * iteration started, for re-enqueue. When the iteration ends, the DSQ's marked
11247  * tasks go through ops.enqueue() with %SCX_ENQ_REENQ in DSQ order and the other
11248  * tasks on the DSQ keep their positions. A marked task that leaves the DSQ in
11249  * the meantime is not re-enqueued. The mark belongs to @p, so a re-enqueue
11250  * scheduled by another iteration of the DSQ may re-enqueue @p before this
11251  * iteration ends. @p must be on the DSQ's scheduler.
11252  *
11253  * Re-enqueues are performed asynchronously. Can be called from ops.dispatch()
11254  * or any BPF context which doesn't hold a rq lock (e.g. BPF timers or SYSCALL
11255  * programs).
11256  *
11257  * Return %true if @p was marked, %false if @p left the DSQ or was queued after
11258  * the iteration started, @p is on another scheduler, or the iterator holds no
11259  * DSQ.
11260  */
11261 __bpf_kfunc bool scx_bpf_dsq_reenq_task(struct bpf_iter_scx_dsq *it__iter,
11262 					struct task_struct *p)
11263 {
11264 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
11265 	struct scx_dispatch_q *dsq = kit->dsq;
11266 	struct rq *src_rq, *entry_rq;
11267 	unsigned long flags;
11268 	bool marked = false;
11269 
11270 	/* NULL after a failed bpf_iter_scx_dsq_new(), see scx_dsq_move() */
11271 	if (unlikely(!dsq))
11272 		return false;
11273 
11274 	/* the cursor check needs @p's rq locked */
11275 	src_rq = task_rq(p);
11276 	entry_rq = kf_switch_rq_lock(src_rq, &flags);
11277 
11278 	scoped_guard (raw_spinlock, &dsq->lock) {
11279 		if (nldsq_cursor_lost_task(&kit->cursor, src_rq, dsq, p))
11280 			break;
11281 
11282 		if (unlikely(!scx_task_on_sched(dsq->sched, p))) {
11283 			scx_error(dsq->sched, "scx_bpf_dsq_reenq_task() on %s[%d] but the task belongs to a different scheduler",
11284 				  p->comm, p->pid);
11285 			break;
11286 		}
11287 
11288 		p->scx.dsq_flags |= SCX_TASK_DSQ_REENQ;
11289 		/* the walk is scheduled once, by bpf_iter_scx_dsq_destroy() */
11290 		kit->cursor.flags |= __SCX_DSQ_ITER_HAS_REENQ;
11291 		marked = true;
11292 	}
11293 
11294 	kf_restore_rq_lock(src_rq, entry_rq, flags);
11295 	return marked;
11296 }
11297 
11298 /**
11299  * scx_bpf_reenqueue_local___v2 - Re-enqueue tasks on a local DSQ
11300  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11301  *
11302  * Iterate over all of the tasks currently enqueued on the local DSQ of the rq
11303  * the current scheduler operation is locked to, or the calling CPU's when no rq
11304  * is locked, and re-enqueue them in the BPF scheduler. Can be called from any
11305  * context except NMI. A call from NMI aborts the scheduler.
11306  *
11307  * This is now a special case of scx_bpf_dsq_reenq() and may be removed in the
11308  * future.
11309  */
11310 __bpf_kfunc void scx_bpf_reenqueue_local___v2(const struct bpf_prog_aux *aux)
11311 {
11312 	scx_bpf_dsq_reenq(SCX_DSQ_LOCAL, 0, aux);
11313 }
11314 
11315 __bpf_kfunc_end_defs();
11316 
11317 __printf(5, 0)
11318 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
11319 			 size_t line_size, char *fmt, unsigned long long *data,
11320 			 u32 data__sz)
11321 {
11322 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
11323 	s32 ret;
11324 
11325 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
11326 	    (data__sz && !data)) {
11327 		scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz);
11328 		return -EINVAL;
11329 	}
11330 
11331 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
11332 	if (ret < 0) {
11333 		scx_error(sch, "failed to read data fields (%d)", ret);
11334 		return ret;
11335 	}
11336 
11337 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
11338 				  &bprintf_data);
11339 	if (ret < 0) {
11340 		scx_error(sch, "format preparation failed (%d)", ret);
11341 		return ret;
11342 	}
11343 
11344 	ret = bstr_printf(line_buf, line_size, fmt,
11345 			  bprintf_data.bin_args);
11346 	bpf_bprintf_cleanup(&bprintf_data);
11347 	if (ret < 0) {
11348 		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
11349 		return ret;
11350 	}
11351 
11352 	return ret;
11353 }
11354 
11355 /*
11356  * Exit @sch with the reason formatted from a BPF-supplied bstr format. The exit
11357  * is claimed first and the reason is formatted directly into the winner-owned
11358  * exit_info buffer, which allows use from any context including NMI.
11359  *
11360  * @fmt_blame is the sched blamed for formatting failures through the
11361  * scx_error() calls in __bstr_format() and differs from @sch when a parent
11362  * supplies the kill reason for a child. A formatting failure doesn't revert the
11363  * claim - @sch still exits with the claimed kind and a fallback message.
11364  */
11365 __printf(5, 0)
11366 bool scx_exit_bstr(struct scx_sched *sch, enum scx_exit_kind kind,
11367 		   s64 exit_code, struct scx_sched *fmt_blame, char *fmt,
11368 		   unsigned long long *data, u32 data__sz)
11369 {
11370 	struct scx_exit_info *ei = sch->exit_info;
11371 	u64 data_buf[MAX_BPRINTF_VARARGS];
11372 	s32 ret;
11373 
11374 	guard(preempt)();
11375 
11376 	if (!scx_claim_exit(sch, kind))
11377 		return false;
11378 
11379 	ret = __bstr_format(fmt_blame, data_buf, ei->msg, SCX_EXIT_MSG_LEN,
11380 			    fmt, data, data__sz);
11381 	if (ret < 0)
11382 		scnprintf(ei->msg, SCX_EXIT_MSG_LEN,
11383 			  "exit message formatting failed (%d)", ret);
11384 
11385 	scx_finish_exit(sch, kind, exit_code, raw_smp_processor_id());
11386 	return true;
11387 }
11388 
11389 __bpf_kfunc_start_defs();
11390 
11391 /**
11392  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
11393  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
11394  * @fmt: error message format string
11395  * @data: format string parameters packaged using ___bpf_fill() macro
11396  * @data__sz: @data len, must end in '__sz' for the verifier
11397  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11398  *
11399  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
11400  * disabling.
11401  */
11402 __printf(2, 0)
11403 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
11404 				   unsigned long long *data, u32 data__sz,
11405 				   const struct bpf_prog_aux *aux)
11406 {
11407 	struct scx_sched *sch;
11408 
11409 	guard(rcu)();
11410 
11411 	sch = scx_prog_sched(aux);
11412 	if (likely(sch))
11413 		scx_exit_bstr(sch, SCX_EXIT_UNREG_BPF, exit_code, sch, fmt,
11414 			      data, data__sz);
11415 }
11416 
11417 /**
11418  * scx_bpf_error_bstr - Indicate fatal error
11419  * @fmt: error message format string
11420  * @data: format string parameters packaged using ___bpf_fill() macro
11421  * @data__sz: @data len, must end in '__sz' for the verifier
11422  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11423  *
11424  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
11425  * disabling.
11426  */
11427 __printf(1, 0)
11428 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
11429 				    u32 data__sz, const struct bpf_prog_aux *aux)
11430 {
11431 	struct scx_sched *sch;
11432 
11433 	guard(rcu)();
11434 
11435 	sch = scx_prog_sched(aux);
11436 	if (likely(sch))
11437 		scx_exit_bstr(sch, SCX_EXIT_ERROR_BPF, 0, sch, fmt, data,
11438 			      data__sz);
11439 }
11440 
11441 /**
11442  * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler
11443  * @fmt: format string
11444  * @data: format string parameters packaged using ___bpf_fill() macro
11445  * @data__sz: @data len, must end in '__sz' for the verifier
11446  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11447  *
11448  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
11449  * dump_task() to generate extra debug dump specific to the BPF scheduler.
11450  *
11451  * The extra dump may be multiple lines. A single line may be split over
11452  * multiple calls. The last line is automatically terminated.
11453  */
11454 __printf(1, 0)
11455 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
11456 				   u32 data__sz, const struct bpf_prog_aux *aux)
11457 {
11458 	struct scx_sched *sch;
11459 	struct scx_dump_data *dd = &scx_dump_data;
11460 	struct scx_bstr_buf *buf = &dd->buf;
11461 	s32 ret;
11462 
11463 	guard(rcu)();
11464 
11465 	sch = scx_prog_sched(aux);
11466 	if (unlikely(!sch))
11467 		return;
11468 
11469 	if (raw_smp_processor_id() != dd->cpu) {
11470 		scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends");
11471 		return;
11472 	}
11473 
11474 	/* append the formatted string to the line buf */
11475 	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
11476 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
11477 	if (ret < 0) {
11478 		scx_dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
11479 			      dd->prefix, fmt, data, data__sz, ret);
11480 		return;
11481 	}
11482 
11483 	dd->cursor += ret;
11484 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
11485 
11486 	if (!dd->cursor)
11487 		return;
11488 
11489 	/*
11490 	 * If the line buf overflowed or ends in a newline, flush it into the
11491 	 * dump. This is to allow the caller to generate a single line over
11492 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
11493 	 * the line buf, the only case which can lead to an unexpected
11494 	 * truncation is when the caller keeps generating newlines in the middle
11495 	 * instead of the end consecutively. Don't do that.
11496 	 */
11497 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
11498 		ops_dump_flush();
11499 }
11500 
11501 /**
11502  * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU
11503  * @cpu: CPU of interest
11504  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11505  *
11506  * Return the maximum relative capacity of @cpu in relation to the most
11507  * performant CPU in the system. The return value is in the range [1,
11508  * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur().
11509  */
11510 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu, const struct bpf_prog_aux *aux)
11511 {
11512 	struct scx_sched *sch;
11513 
11514 	guard(rcu)();
11515 
11516 	sch = scx_prog_sched(aux);
11517 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
11518 		return arch_scale_cpu_capacity(cpu);
11519 	else
11520 		return SCX_CPUPERF_ONE;
11521 }
11522 
11523 /**
11524  * scx_bpf_cidperf_cap - Query the maximum relative capacity of the CPU at @cid
11525  * @cid: cid of the CPU to query
11526  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11527  *
11528  * cid-addressed equivalent of scx_bpf_cpuperf_cap().
11529  */
11530 __bpf_kfunc u32 scx_bpf_cidperf_cap(s32 cid, const struct bpf_prog_aux *aux)
11531 {
11532 	struct scx_sched *sch;
11533 	s32 cpu;
11534 
11535 	guard(rcu)();
11536 
11537 	sch = scx_prog_sched(aux);
11538 	if (unlikely(!sch))
11539 		return SCX_CPUPERF_ONE;
11540 	cpu = scx_cid_to_cpu(sch, cid);
11541 	if (cpu < 0)
11542 		return SCX_CPUPERF_ONE;
11543 	return arch_scale_cpu_capacity(cpu);
11544 }
11545 
11546 /**
11547  * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU
11548  * @cpu: CPU of interest
11549  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11550  *
11551  * Return the current relative performance of @cpu in relation to its maximum.
11552  * The return value is in the range [1, %SCX_CPUPERF_ONE].
11553  *
11554  * The current performance level of a CPU in relation to the maximum performance
11555  * available in the system can be calculated as follows:
11556  *
11557  *   scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE
11558  *
11559  * The result is in the range [1, %SCX_CPUPERF_ONE].
11560  */
11561 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu, const struct bpf_prog_aux *aux)
11562 {
11563 	struct scx_sched *sch;
11564 
11565 	guard(rcu)();
11566 
11567 	sch = scx_prog_sched(aux);
11568 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
11569 		return arch_scale_freq_capacity(cpu);
11570 	else
11571 		return SCX_CPUPERF_ONE;
11572 }
11573 
11574 /**
11575  * scx_bpf_cidperf_cur - Query the current performance of the CPU at @cid
11576  * @cid: cid of the CPU to query
11577  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11578  *
11579  * cid-addressed equivalent of scx_bpf_cpuperf_cur().
11580  */
11581 __bpf_kfunc u32 scx_bpf_cidperf_cur(s32 cid, const struct bpf_prog_aux *aux)
11582 {
11583 	struct scx_sched *sch;
11584 	s32 cpu;
11585 
11586 	guard(rcu)();
11587 
11588 	sch = scx_prog_sched(aux);
11589 	if (unlikely(!sch))
11590 		return SCX_CPUPERF_ONE;
11591 	cpu = scx_cid_to_cpu(sch, cid);
11592 	if (cpu < 0)
11593 		return SCX_CPUPERF_ONE;
11594 	return arch_scale_freq_capacity(cpu);
11595 }
11596 
11597 /* validate and apply a cpuperf target, see scx_bpf_cpuperf_set() */
11598 static s32 scx_cpuperf_set(struct scx_sched *sch, s32 cpu, u32 perf)
11599 {
11600 	struct rq *rq, *locked_rq;
11601 	struct rq_flags rf;
11602 	s32 ret;
11603 
11604 	if (unlikely(perf > SCX_CPUPERF_ONE)) {
11605 		scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu);
11606 		return -EINVAL;
11607 	}
11608 
11609 	if (!scx_cpu_valid(sch, cpu, NULL))
11610 		return -EINVAL;
11611 
11612 	rq = cpu_rq(cpu);
11613 	locked_rq = scx_locked_rq();
11614 
11615 	/*
11616 	 * When called with an rq lock held, restrict the operation to the
11617 	 * corresponding CPU to prevent ABBA deadlocks.
11618 	 */
11619 	if (locked_rq && rq != locked_rq) {
11620 		scx_error(sch, "Invalid target CPU %d", cpu);
11621 		return -EINVAL;
11622 	}
11623 
11624 	/*
11625 	 * If no rq lock is held, allow to operate on any CPU by acquiring
11626 	 * the corresponding rq lock.
11627 	 */
11628 	if (!locked_rq) {
11629 		rq_lock_irqsave(rq, &rf);
11630 		update_rq_clock(rq);
11631 	}
11632 
11633 	/*
11634 	 * ecaps updates are folded under the rq lock, making this test
11635 	 * authoritative: a write can never land after a revoke has taken
11636 	 * effect on @cpu.
11637 	 */
11638 	if (likely(!scx_missing_caps(sch, cpu, SCX_CAP_PERF))) {
11639 		rq->scx.cpuperf_target = perf;
11640 		cpufreq_update_util(rq, 0);
11641 		ret = 0;
11642 	} else {
11643 		__scx_add_event(sch, SCX_EV_SUB_CIDPERF_DENIED, 1);
11644 		ret = -EACCES;
11645 	}
11646 
11647 	if (!locked_rq)
11648 		rq_unlock_irqrestore(rq, &rf);
11649 
11650 	return ret;
11651 }
11652 
11653 /**
11654  * scx_bpf_cpuperf_set - Set the relative performance target of a CPU
11655  * @cpu: CPU of interest
11656  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
11657  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11658  *
11659  * Set the target performance level of @cpu to @perf. @perf is in linear
11660  * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the
11661  * schedutil cpufreq governor chooses the target frequency.
11662  *
11663  * The actual performance level chosen, CPU grouping, and the overhead and
11664  * latency of the operations are dependent on the hardware and cpufreq driver in
11665  * use. Consult hardware and cpufreq documentation for more information. The
11666  * current performance level can be monitored using scx_bpf_cpuperf_cur().
11667  */
11668 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf, const struct bpf_prog_aux *aux)
11669 {
11670 	struct scx_sched *sch;
11671 
11672 	guard(rcu)();
11673 
11674 	sch = scx_prog_sched(aux);
11675 	if (unlikely(!sch))
11676 		return;
11677 
11678 	if (!scx_kf_allowed_ctx(sch))
11679 		return;
11680 
11681 	scx_cpuperf_set(sch, cpu, perf);
11682 }
11683 
11684 /**
11685  * scx_bpf_cidperf_set - Set the performance target of the CPU at @cid
11686  * @cid: cid of the CPU to target
11687  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
11688  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11689  *
11690  * cid-addressed equivalent of scx_bpf_cpuperf_set(). A sub-sched needs
11691  * SCX_CAP_PERF on @cid. Returns 0 if the target was applied, -%EACCES if
11692  * the write was denied for missing caps, other -errnos if @cid didn't
11693  * resolve.
11694  */
11695 __bpf_kfunc s32 scx_bpf_cidperf_set(s32 cid, u32 perf,
11696 				    const struct bpf_prog_aux *aux)
11697 {
11698 	struct scx_sched *sch;
11699 	s32 cpu;
11700 
11701 	guard(rcu)();
11702 
11703 	sch = scx_prog_sched(aux);
11704 	if (unlikely(!sch))
11705 		return -ENODEV;
11706 
11707 	if (!scx_kf_allowed_ctx(sch))
11708 		return -EDEADLK;
11709 
11710 	cpu = scx_cid_to_cpu(sch, cid);
11711 	if (cpu < 0)
11712 		return cpu;
11713 
11714 	return scx_cpuperf_set(sch, cpu, perf);
11715 }
11716 
11717 /**
11718  * scx_bpf_nr_node_ids - Return the number of possible node IDs
11719  *
11720  * All valid node IDs in the system are smaller than the returned value.
11721  */
11722 __bpf_kfunc u32 scx_bpf_nr_node_ids(void)
11723 {
11724 	return nr_node_ids;
11725 }
11726 
11727 /**
11728  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
11729  *
11730  * All valid CPU IDs in the system are smaller than the returned value.
11731  */
11732 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
11733 {
11734 	return nr_cpu_ids;
11735 }
11736 
11737 /**
11738  * scx_bpf_nr_cids - Return the size of the cid space
11739  *
11740  * Equals num_possible_cpus(). All valid cids are in [0, return value).
11741  */
11742 __bpf_kfunc u32 scx_bpf_nr_cids(void)
11743 {
11744 	return num_possible_cpus();
11745 }
11746 
11747 /**
11748  * scx_bpf_nr_online_cids - Return current count of online CPUs in cid space
11749  *
11750  * Return num_online_cpus(). The standard model restarts the scheduler on
11751  * hotplug, which lets schedulers treat [0, nr_online_cids) as the online
11752  * range. Schedulers that prefer to handle hotplug without a restart should
11753  * install a custom mapping via scx_bpf_cid_override() and track onlining
11754  * through the ops.cid_online / ops.cid_offline callbacks, starting from the
11755  * mask scx_bpf_online_cmask() returns.
11756  */
11757 __bpf_kfunc u32 scx_bpf_nr_online_cids(void)
11758 {
11759 	return num_online_cpus();
11760 }
11761 
11762 /**
11763  * scx_bpf_online_cmask - Return the online cid mask in the scheduler arena
11764  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11765  *
11766  * Return a kernel-maintained cmask covering [0, scx_bpf_nr_cids()), or NULL if
11767  * the calling program is not associated with a live cid-form scheduler or the
11768  * mask is not allocated yet, as in ops.init_cids(). Treat the mask as read-only
11769  * even though arena memory stays writable by the BPF scheduler. The mask
11770  * follows the SCX hotplug notifications: a cid's bit is updated before
11771  * ops.cid_online/offline() runs for it. The pointer is valid from ops.init()
11772  * through ops.exit(). Root ops.init() runs with hotplug excluded. Other
11773  * contexts can observe concurrent updates.
11774  */
11775 __bpf_kfunc const void *scx_bpf_online_cmask(const struct bpf_prog_aux *aux)
11776 {
11777 	struct scx_sched *sch;
11778 	struct scx_cmask *online;
11779 
11780 	guard(rcu)();
11781 
11782 	sch = scx_prog_sched(aux);
11783 	if (unlikely(!sch))
11784 		return NULL;
11785 	online = sch->online_cmask;
11786 	if (unlikely(!online))
11787 		return NULL;
11788 
11789 	return (void *)scx_kaddr_to_arena(sch, online);
11790 }
11791 
11792 /**
11793  * scx_bpf_this_cid - Return the cid of the CPU this program is running on
11794  *
11795  * cid-addressed equivalent of bpf_get_smp_processor_id() for scx programs.
11796  * The current cpu is trivially valid, so this is just a table lookup. Return
11797  * -EINVAL if called before any scheduler has ever published its cid tables.
11798  */
11799 __bpf_kfunc s32 scx_bpf_this_cid(void)
11800 {
11801 	s16 *tbl;
11802 
11803 	guard(rcu)();
11804 
11805 	tbl = rcu_dereference(scx_cpu_to_cid_tbl);
11806 	if (!tbl)
11807 		return -EINVAL;
11808 	return tbl[raw_smp_processor_id()];
11809 }
11810 
11811 /**
11812  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
11813  */
11814 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
11815 {
11816 	return cpu_possible_mask;
11817 }
11818 
11819 /**
11820  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
11821  */
11822 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
11823 {
11824 	return cpu_online_mask;
11825 }
11826 
11827 /**
11828  * scx_bpf_put_cpumask - Release a possible/online cpumask
11829  * @cpumask: cpumask to release
11830  */
11831 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
11832 {
11833 	/*
11834 	 * Empty function body because we aren't actually acquiring or releasing
11835 	 * a reference to a global cpumask, which is read-only in the caller and
11836 	 * is never released. The acquire / release semantics here are just used
11837 	 * to make the cpumask is a trusted pointer in the caller.
11838 	 */
11839 }
11840 
11841 /**
11842  * scx_bpf_task_running - Is task the current scheduling context?
11843  * @p: task of interest
11844  *
11845  * Under proxy execution, this reports the donor rather than the task whose
11846  * code is physically executing. The physical execution context is intentionally
11847  * not exposed to the BPF scheduler, which continues to observe the donor as the
11848  * running scheduling context.
11849  */
11850 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
11851 {
11852 	return rcu_access_pointer(task_rq(p)->donor) == p;
11853 }
11854 
11855 /**
11856  * scx_bpf_task_cpu - CPU a task is currently associated with
11857  * @p: task of interest
11858  */
11859 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
11860 {
11861 	return task_cpu(p);
11862 }
11863 
11864 /**
11865  * scx_bpf_task_cid - cid a task is currently associated with
11866  * @p: task of interest
11867  *
11868  * cid-addressed equivalent of scx_bpf_task_cpu(). task_cpu(p) is always a
11869  * valid cpu, so this is just a table lookup. Return -EINVAL if called before
11870  * any scheduler has ever published its cid tables.
11871  */
11872 __bpf_kfunc s32 scx_bpf_task_cid(const struct task_struct *p)
11873 {
11874 	s16 *tbl;
11875 
11876 	/* KF_RCU covers only @p - a sleepable program holds no RCU lock */
11877 	guard(rcu)();
11878 
11879 	tbl = rcu_dereference(scx_cpu_to_cid_tbl);
11880 	if (!tbl)
11881 		return -EINVAL;
11882 	return tbl[task_cpu(p)];
11883 }
11884 
11885 /**
11886  * scx_bpf_locked_rq - Return the rq currently locked by SCX
11887  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11888  *
11889  * Returns the rq if a rq lock is currently held by SCX.
11890  * Otherwise emits an error and returns NULL.
11891  */
11892 __bpf_kfunc struct rq *scx_bpf_locked_rq(const struct bpf_prog_aux *aux)
11893 {
11894 	struct scx_sched *sch;
11895 	struct rq *rq;
11896 
11897 	guard(preempt)();
11898 
11899 	sch = scx_prog_sched(aux);
11900 	if (unlikely(!sch))
11901 		return NULL;
11902 
11903 	rq = scx_locked_rq();
11904 	if (!rq) {
11905 		scx_error(sch, "accessing rq without holding rq lock");
11906 		return NULL;
11907 	}
11908 
11909 	return rq;
11910 }
11911 
11912 /**
11913  * scx_bpf_cpu_curr - Return remote CPU's current scheduling context
11914  * @cpu: CPU of interest
11915  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11916  *
11917  * Under proxy execution, this returns the donor, which supplies the scheduling
11918  * policy and runtime budget, rather than the task whose code is physically
11919  * executing. The physical execution context is intentionally not exposed to
11920  * the BPF scheduler.
11921  *
11922  * Callers must hold RCU read lock (KF_RCU).
11923  */
11924 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_aux *aux)
11925 {
11926 	struct scx_sched *sch;
11927 
11928 	sch = scx_prog_sched(aux);
11929 	if (unlikely(!sch))
11930 		return NULL;
11931 
11932 	if (!scx_cpu_valid(sch, cpu, NULL))
11933 		return NULL;
11934 
11935 	return rcu_dereference_all(cpu_rq(cpu)->donor);
11936 }
11937 
11938 /**
11939  * scx_bpf_cid_curr - Return the curr task on the CPU at @cid
11940  * @cid: cid of interest
11941  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
11942  *
11943  * cid-addressed equivalent of scx_bpf_cpu_curr(). Callers must hold RCU
11944  * read lock (KF_RCU).
11945  */
11946 __bpf_kfunc struct task_struct *scx_bpf_cid_curr(s32 cid, const struct bpf_prog_aux *aux)
11947 {
11948 	struct scx_sched *sch;
11949 	s32 cpu;
11950 
11951 	sch = scx_prog_sched(aux);
11952 	if (unlikely(!sch))
11953 		return NULL;
11954 	cpu = scx_cid_to_cpu(sch, cid);
11955 	if (cpu < 0)
11956 		return NULL;
11957 	return rcu_dereference_all(cpu_rq(cpu)->donor);
11958 }
11959 
11960 /**
11961  * scx_bpf_tid_to_task - Look up a task by its scx tid
11962  * @tid: task ID previously read from p->scx.tid
11963  *
11964  * Returns the task with the given tid, or NULL if no such task exists. The
11965  * returned pointer is valid until the end of the current RCU read section
11966  * (KF_RCU_PROTECTED). Requires SCX_OPS_TID_TO_TASK to be set on the root
11967  * scheduler; otherwise an error is raised and NULL returned.
11968  */
11969 __bpf_kfunc struct task_struct *scx_bpf_tid_to_task(u64 tid)
11970 {
11971 	struct sched_ext_entity *scx;
11972 
11973 	if (!scx_tid_to_task_enabled()) {
11974 		struct scx_sched *sch = rcu_dereference_all(scx_root);
11975 
11976 		if (sch)
11977 			scx_error(sch, "scx_bpf_tid_to_task() called without SCX_OPS_TID_TO_TASK");
11978 		return NULL;
11979 	}
11980 
11981 	scx = rhashtable_lookup(&scx_tid_hash, &tid, scx_tid_hash_params);
11982 	if (!scx)
11983 		return NULL;
11984 
11985 	return container_of(scx, struct task_struct, scx);
11986 }
11987 
11988 u64 __scx_bpf_now(struct rq *rq)
11989 {
11990 	/* the caller must be on @rq's cpu or hold its lock */
11991 	lockdep_assert((rq == this_rq() && !preemptible()) ||
11992 		       lockdep_is_held(__rq_lockp(rq)));
11993 
11994 	if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) {
11995 		/* if the rq clock is valid, use the cached rq clock */
11996 		return READ_ONCE(rq->scx.clock);
11997 	} else {
11998 		/*
11999 		 * Otherwise, return a fresh rq clock.
12000 		 *
12001 		 * The rq clock is updated outside of the rq lock.
12002 		 * In this case, keep the updated rq clock invalid so the next
12003 		 * read outside the rq lock gets a fresh rq clock.
12004 		 */
12005 		return sched_clock_cpu(cpu_of(rq));
12006 	}
12007 }
12008 
12009 /**
12010  * scx_bpf_now - Returns a high-performance monotonically non-decreasing
12011  * clock for the current CPU. The clock returned is in nanoseconds.
12012  *
12013  * It provides the following properties:
12014  *
12015  * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently
12016  *  to account for execution time and track tasks' runtime properties.
12017  *  Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which
12018  *  eventually reads a hardware timestamp counter -- is neither performant nor
12019  *  scalable. scx_bpf_now() aims to provide a high-performance clock by
12020  *  using the rq clock in the scheduler core whenever possible.
12021  *
12022  * 2) High enough resolution for the BPF scheduler use cases: In most BPF
12023  *  scheduler use cases, the required clock resolution is lower than the most
12024  *  accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically
12025  *  uses the rq clock in the scheduler core whenever it is valid. It considers
12026  *  that the rq clock is valid from the time the rq clock is updated
12027  *  (update_rq_clock) until the rq is unlocked (rq_unpin_lock).
12028  *
12029  * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now()
12030  *  guarantees the clock never goes backward when comparing them in the same
12031  *  CPU. On the other hand, when comparing clocks in different CPUs, there
12032  *  is no such guarantee -- the clock can go backward. It provides a
12033  *  monotonically *non-decreasing* clock so that it would provide the same
12034  *  clock values in two different scx_bpf_now() calls in the same CPU
12035  *  during the same period of when the rq clock is valid.
12036  */
12037 __bpf_kfunc u64 scx_bpf_now(void)
12038 {
12039 	/*
12040 	 * Note that scx_bpf_now() is re-entrant between a process context and
12041 	 * an interrupt context (e.g., timer interrupt). However, we don't need
12042 	 * to consider the race between them because such race is not observable
12043 	 * from a caller.
12044 	 */
12045 	guard(preempt)();
12046 	return __scx_bpf_now(this_rq());
12047 }
12048 
12049 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events)
12050 {
12051 	int cpu;
12052 
12053 	/* Aggregate per-CPU event counters into @events. */
12054 	memset(events, 0, sizeof(*events));
12055 	for_each_possible_cpu(cpu) {
12056 		struct scx_event_stats *e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats;
12057 #define SCX_EVENT(name)	(events->name += READ_ONCE(e_cpu->name))
12058 		SCX_EVENTS_LIST(SCX_EVENT);
12059 #undef SCX_EVENT
12060 	}
12061 }
12062 
12063 /**
12064  * scx_bpf_events - Read the event counters of the calling scheduler
12065  * @events: output buffer from a BPF program
12066  * @events__sz: @events len, must end in '__sz' for the verifier
12067  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
12068  *
12069  * Read the event counters of the scheduler associated with the calling program.
12070  * @events is zeroed when no scheduler can be resolved.
12071  */
12072 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events, size_t events__sz,
12073 				const struct bpf_prog_aux *aux)
12074 {
12075 	struct scx_sched *sch;
12076 	struct scx_event_stats e_sys;
12077 
12078 	rcu_read_lock();
12079 	sch = scx_prog_sched(aux);
12080 	if (sch)
12081 		scx_read_events(sch, &e_sys);
12082 	else
12083 		memset(&e_sys, 0, sizeof(e_sys));
12084 	rcu_read_unlock();
12085 
12086 	/*
12087 	 * We cannot entirely trust a BPF-provided size since a BPF program
12088 	 * might be compiled against a different vmlinux.h, of which
12089 	 * scx_event_stats would be larger (a newer vmlinux.h) or smaller
12090 	 * (an older vmlinux.h). Hence, we use the smaller size to avoid
12091 	 * memory corruption.
12092 	 */
12093 	events__sz = min(events__sz, sizeof(*events));
12094 	memcpy(events, &e_sys, events__sz);
12095 }
12096 
12097 #ifdef CONFIG_CGROUP_SCHED
12098 /**
12099  * scx_bpf_task_cgroup - Return the sched cgroup of a task
12100  * @p: task of interest
12101  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
12102  *
12103  * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with
12104  * from the scheduler's POV. SCX operations should use this function to
12105  * determine @p's current cgroup as, unlike following @p->cgroups,
12106  * @p->sched_task_group is stable for the duration of the SCX op. See
12107  * SCX_CALL_OP_TASK() for details.
12108  */
12109 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p,
12110 					       const struct bpf_prog_aux *aux)
12111 {
12112 	struct task_group *tg = p->sched_task_group;
12113 	struct cgroup *cgrp = &cgrp_dfl_root.cgrp;
12114 	struct scx_sched *sch;
12115 
12116 	guard(rcu)();
12117 
12118 	sch = scx_prog_sched(aux);
12119 	if (unlikely(!sch))
12120 		goto out;
12121 
12122 	if (!scx_kf_arg_task_ok(sch, p))
12123 		goto out;
12124 
12125 	cgrp = tg_cgrp(tg);
12126 
12127 out:
12128 	cgroup_get(cgrp);
12129 	return cgrp;
12130 }
12131 
12132 /**
12133  * scx_bpf_cgroup_nr_cpus - Return the number of CPUs in a cgroup's cpuset
12134  * @cgrp: cgroup of interest
12135  *
12136  * Return the number of CPUs in @cgrp's effective cpuset, which is inherited
12137  * from the nearest ancestor with the cpuset controller enabled. This matches
12138  * the count used by fair's group share calculation and lets hierarchical BPF
12139  * schedulers bound a group's weight by the CPUs it can actually run on.
12140  *
12141  * The value is a snapshot and may change at any time through cpuset updates or
12142  * CPU hotplug. Schedulers should re-read it when recomputing group state.
12143  */
12144 __bpf_kfunc u32 scx_bpf_cgroup_nr_cpus(struct cgroup *cgrp)
12145 {
12146 	return cpuset_num_cpus(cgrp);
12147 }
12148 #endif	/* CONFIG_CGROUP_SCHED */
12149 
12150 __bpf_kfunc_end_defs();
12151 
12152 BTF_KFUNCS_START(scx_kfunc_ids_any)
12153 BTF_ID_FLAGS(func, scx_bpf_task_set_slice, KF_IMPLICIT_ARGS | KF_RCU);
12154 BTF_ID_FLAGS(func, scx_bpf_task_set_dsq_vtime, KF_IMPLICIT_ARGS | KF_RCU);
12155 BTF_ID_FLAGS(func, scx_bpf_task_set_lazy_resched, KF_IMPLICIT_ARGS | KF_RCU);
12156 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
12157 BTF_ID_FLAGS(func, scx_bpf_kick_cid, KF_IMPLICIT_ARGS)
12158 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued, KF_IMPLICIT_ARGS)
12159 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS)
12160 BTF_ID_FLAGS(func, scx_bpf_dsq_peek, KF_IMPLICIT_ARGS | KF_RCU_PROTECTED | KF_RET_NULL)
12161 BTF_ID_FLAGS(func, scx_bpf_dsq_reenq, KF_IMPLICIT_ARGS)
12162 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local___v2, KF_IMPLICIT_ARGS)
12163 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_IMPLICIT_ARGS | KF_ITER_NEW | KF_RCU_PROTECTED)
12164 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
12165 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
12166 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_IMPLICIT_ARGS)
12167 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_IMPLICIT_ARGS)
12168 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_IMPLICIT_ARGS)
12169 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS)
12170 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS)
12171 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
12172 BTF_ID_FLAGS(func, scx_bpf_cidperf_cap, KF_IMPLICIT_ARGS)
12173 BTF_ID_FLAGS(func, scx_bpf_cidperf_cur, KF_IMPLICIT_ARGS)
12174 BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS)
12175 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
12176 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
12177 BTF_ID_FLAGS(func, scx_bpf_nr_cids)
12178 BTF_ID_FLAGS(func, scx_bpf_nr_online_cids)
12179 BTF_ID_FLAGS(func, scx_bpf_online_cmask, KF_IMPLICIT_ARGS | KF_ARENA_RET)
12180 BTF_ID_FLAGS(func, scx_bpf_this_cid)
12181 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
12182 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
12183 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
12184 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
12185 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
12186 BTF_ID_FLAGS(func, scx_bpf_task_cid, KF_RCU)
12187 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL)
12188 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
12189 BTF_ID_FLAGS(func, scx_bpf_cid_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
12190 BTF_ID_FLAGS(func, scx_bpf_tid_to_task, KF_RET_NULL | KF_RCU_PROTECTED)
12191 BTF_ID_FLAGS(func, scx_bpf_now)
12192 BTF_ID_FLAGS(func, scx_bpf_events, KF_IMPLICIT_ARGS)
12193 #ifdef CONFIG_CGROUP_SCHED
12194 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_IMPLICIT_ARGS | KF_RCU | KF_ACQUIRE)
12195 BTF_ID_FLAGS(func, scx_bpf_cgroup_nr_cpus, KF_RCU)
12196 #endif
12197 BTF_ID_FLAGS(func, scx_bpf_sub_grant, KF_IMPLICIT_ARGS)
12198 BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS)
12199 BTF_ID_FLAGS(func, scx_bpf_sub_caps, KF_IMPLICIT_ARGS)
12200 BTF_ID_FLAGS(func, scx_bpf_sub_kill_bstr, KF_IMPLICIT_ARGS)
12201 BTF_KFUNCS_END(scx_kfunc_ids_any)
12202 
12203 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
12204 	.owner			= THIS_MODULE,
12205 	.set			= &scx_kfunc_ids_any,
12206 	.filter			= scx_kfunc_context_filter,
12207 };
12208 
12209 /*
12210  * Kfuncs that tracing programs can't call. A tracing program can run in any
12211  * kernel context, including with an rq lock held. scx_locked_rq() only tracks
12212  * rq locks held across SCX callbacks and returns NULL there.
12213  *
12214  * scx_bpf_cpuperf_set() and scx_bpf_cidperf_set() take the target cpu's rq lock
12215  * when scx_locked_rq() returns NULL. Taking it while the context already holds
12216  * an rq lock, the same one or another cpu's, can deadlock.
12217  *
12218  * scx_bpf_destroy_dsq() takes a user DSQ lock. So do
12219  * bpf_iter_scx_dsq_next() and bpf_iter_scx_dsq_destroy(), the latter only
12220  * after a successful next() has linked the cursor. A tracing program can
12221  * run while that lock is already held and recursively acquire it.
12222  *
12223  * Before returning, scx_bpf_sub_grant() and scx_bpf_sub_revoke() invoke
12224  * ops.sub_caps_updated() of the sub-schedulers whose caps changed, so those ops
12225  * run in the tracing program's context. No SCX op expects to run from an
12226  * arbitrary tracing context. One that calls scx_bpf_cidperf_set() hits the
12227  * deadlock above.
12228  *
12229  * Members must also stay in scx_kfunc_ids_any so that struct_ops and syscall
12230  * programs keep their access.
12231  */
12232 BTF_KFUNCS_START(scx_kfunc_ids_no_tracing)
12233 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
12234 BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS)
12235 BTF_ID_FLAGS(func, scx_bpf_sub_grant, KF_IMPLICIT_ARGS)
12236 BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS)
12237 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS)
12238 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
12239 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
12240 BTF_KFUNCS_END(scx_kfunc_ids_no_tracing)
12241 
12242 /*
12243  * cpu-form kfuncs that are forbidden from cid-form schedulers
12244  * (bpf_sched_ext_ops_cid). Programs targeting the cid struct_ops type must
12245  * use the cid-form alternative (cid/cmask kfuncs).
12246  *
12247  * Membership overlaps with scx_kfunc_ids_{any,idle,select_cpu}; the filter
12248  * tests this set independently and rejects matches before the per-op
12249  * allow-list check runs.
12250  *
12251  * pahole/resolve_btfids scans every BTF_ID_FLAGS() at build time and
12252  * intersects flags across duplicate entries, so each entry must carry the
12253  * same flags as the kfunc's primary declaration; otherwise the flags get
12254  * dropped globally.
12255  */
12256 BTF_KFUNCS_START(scx_kfunc_ids_cpu_only)
12257 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
12258 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
12259 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
12260 BTF_ID_FLAGS(func, scx_bpf_cpu_node, KF_IMPLICIT_ARGS)
12261 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS)
12262 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS)
12263 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
12264 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
12265 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
12266 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
12267 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU)
12268 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU)
12269 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU)
12270 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask, KF_IMPLICIT_ARGS | KF_ACQUIRE)
12271 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE)
12272 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask, KF_IMPLICIT_ARGS | KF_ACQUIRE)
12273 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE)
12274 BTF_ID_FLAGS(func, scx_bpf_put_idle_cpumask, KF_RELEASE)
12275 BTF_ID_FLAGS(func, scx_bpf_test_and_clear_cpu_idle, KF_IMPLICIT_ARGS)
12276 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu, KF_IMPLICIT_ARGS | KF_RCU)
12277 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu_node, KF_IMPLICIT_ARGS | KF_RCU)
12278 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu, KF_IMPLICIT_ARGS | KF_RCU)
12279 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu_node, KF_IMPLICIT_ARGS | KF_RCU)
12280 BTF_KFUNCS_END(scx_kfunc_ids_cpu_only)
12281 
12282 /*
12283  * Per-op kfunc allow flags. Each bit corresponds to a context-sensitive kfunc
12284  * group; an op may permit zero or more groups, with the union expressed in
12285  * scx_kf_allow_flags[]. The verifier-time filter (scx_kfunc_context_filter())
12286  * consults this table to decide whether a context-sensitive kfunc is callable
12287  * from a given SCX op.
12288  */
12289 enum scx_kf_allow_flags {
12290 	SCX_KF_ALLOW_UNLOCKED		= 1 << 0,
12291 	SCX_KF_ALLOW_INIT_CIDS		= 1 << 1,
12292 	SCX_KF_ALLOW_CPU_RELEASE	= 1 << 2,
12293 	SCX_KF_ALLOW_DISPATCH		= 1 << 3,
12294 	SCX_KF_ALLOW_ENQUEUE		= 1 << 4,
12295 	SCX_KF_ALLOW_SELECT_CPU		= 1 << 5,
12296 };
12297 
12298 /*
12299  * Map each SCX op to the union of kfunc groups it permits, indexed by
12300  * SCX_OP_IDX(op). Ops not listed only permit kfuncs that are not
12301  * context-sensitive.
12302  */
12303 static const u32 scx_kf_allow_flags[] = {
12304 	[SCX_OP_IDX(select_cpu)]	= SCX_KF_ALLOW_SELECT_CPU | SCX_KF_ALLOW_ENQUEUE,
12305 	[SCX_OP_IDX(enqueue)]		= SCX_KF_ALLOW_SELECT_CPU | SCX_KF_ALLOW_ENQUEUE,
12306 	[SCX_OP_IDX(dispatch)]		= SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH,
12307 	[SCX_OP_IDX(cpu_release)]	= SCX_KF_ALLOW_CPU_RELEASE,
12308 	[SCX_OP_IDX(init_task)]		= SCX_KF_ALLOW_UNLOCKED,
12309 #ifdef CONFIG_EXT_GROUP_SCHED
12310 	[SCX_OP_IDX(cgroup_init)]	= SCX_KF_ALLOW_UNLOCKED,
12311 	[SCX_OP_IDX(cgroup_exit)]	= SCX_KF_ALLOW_UNLOCKED,
12312 	[SCX_OP_IDX(cgroup_prep_move)]	= SCX_KF_ALLOW_UNLOCKED,
12313 	[SCX_OP_IDX(cgroup_cancel_move)] = SCX_KF_ALLOW_UNLOCKED,
12314 	[SCX_OP_IDX(cgroup_set_weight)]	= SCX_KF_ALLOW_UNLOCKED,
12315 	[SCX_OP_IDX(cgroup_set_bandwidth)] = SCX_KF_ALLOW_UNLOCKED,
12316 	[SCX_OP_IDX(cgroup_set_idle)]	= SCX_KF_ALLOW_UNLOCKED,
12317 #endif	/* CONFIG_EXT_GROUP_SCHED */
12318 	[SCX_OP_IDX(sub_attach)]	= SCX_KF_ALLOW_UNLOCKED,
12319 	[SCX_OP_IDX(sub_detach)]	= SCX_KF_ALLOW_UNLOCKED,
12320 	[SCX_OP_IDX(sub_ecaps_updated)]	= SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH,
12321 	[SCX_OP_IDX(sub_child_ecaps_updated)] = SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH,
12322 	[SCX_OP_IDX(cpu_online)]	= SCX_KF_ALLOW_UNLOCKED,
12323 	[SCX_OP_IDX(cpu_offline)]	= SCX_KF_ALLOW_UNLOCKED,
12324 	/*
12325 	 * ops.init_cids() runs before the cid tables are published and before
12326 	 * the arena pool and pshards are allocated. Limit it to finalizing the
12327 	 * cid layout; everything else belongs in ops.init().
12328 	 */
12329 	[SCX_OP_IDX(init_cids)]		= SCX_KF_ALLOW_INIT_CIDS,
12330 	[SCX_OP_IDX(init)]		= SCX_KF_ALLOW_UNLOCKED,
12331 	[SCX_OP_IDX(exit)]		= SCX_KF_ALLOW_UNLOCKED,
12332 };
12333 
12334 /*
12335  * Verifier-time filter for SCX kfuncs. Registered via the .filter field on
12336  * each per-group btf_kfunc_id_set. The BPF core invokes this for every kfunc
12337  * call in the registered hook (BPF_PROG_TYPE_STRUCT_OPS or
12338  * BPF_PROG_TYPE_SYSCALL), regardless of which set originally introduced the
12339  * kfunc - so the filter must short-circuit on kfuncs it doesn't govern by
12340  * falling through to "allow" when none of the SCX sets contain the kfunc.
12341  */
12342 int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id)
12343 {
12344 	bool in_unlocked = btf_id_set8_contains(&scx_kfunc_ids_unlocked, kfunc_id);
12345 	bool in_init_cids = btf_id_set8_contains(&scx_kfunc_ids_init_cids, kfunc_id);
12346 	bool in_select_cpu = btf_id_set8_contains(&scx_kfunc_ids_select_cpu, kfunc_id);
12347 	bool in_enqueue = btf_id_set8_contains(&scx_kfunc_ids_enqueue_dispatch, kfunc_id);
12348 	bool in_dispatch = btf_id_set8_contains(&scx_kfunc_ids_dispatch, kfunc_id);
12349 	bool in_cpu_release = btf_id_set8_contains(&scx_kfunc_ids_cpu_release, kfunc_id);
12350 	bool in_idle = btf_id_set8_contains(&scx_kfunc_ids_idle, kfunc_id);
12351 	bool in_any = btf_id_set8_contains(&scx_kfunc_ids_any, kfunc_id);
12352 	bool in_cpu_only = btf_id_set8_contains(&scx_kfunc_ids_cpu_only, kfunc_id);
12353 	bool in_cid = btf_id_set8_contains(&scx_kfunc_ids_cid, kfunc_id);
12354 	bool in_no_tracing = btf_id_set8_contains(&scx_kfunc_ids_no_tracing, kfunc_id);
12355 	u32 moff, flags;
12356 
12357 	/* Not an SCX kfunc - allow. */
12358 	if (!(in_unlocked || in_init_cids || in_select_cpu || in_enqueue || in_dispatch ||
12359 	      in_cpu_release || in_idle || in_any || in_cid))
12360 		return 0;
12361 
12362 	/* SYSCALL progs (e.g. BPF test_run()) may call unlocked and select_cpu kfuncs. */
12363 	if (prog->type == BPF_PROG_TYPE_SYSCALL)
12364 		return (in_unlocked || in_select_cpu || in_idle || in_any || in_cid) ? 0 : -EACCES;
12365 
12366 	if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
12367 		return (!in_no_tracing && (in_any || in_idle || in_cid)) ? 0 : -EACCES;
12368 
12369 	/*
12370 	 * add_subprog_and_kfunc() collects all kfunc calls, including dead code
12371 	 * guarded by bpf_ksym_exists(), before check_attach_btf_id() sets
12372 	 * prog->aux->st_ops. Allow all kfuncs when st_ops is not yet set;
12373 	 * do_check_main() re-runs the filter with st_ops set and enforces the
12374 	 * actual restrictions.
12375 	 */
12376 	if (!prog->aux->st_ops)
12377 		return 0;
12378 
12379 	/*
12380 	 * Non-SCX struct_ops: SCX kfuncs are not permitted.
12381 	 *
12382 	 * Both bpf_sched_ext_ops (cpu-form) and bpf_sched_ext_ops_cid
12383 	 * (cid-form) are valid SCX struct_ops. Member offsets match between
12384 	 * the two (verified by BUILD_BUG_ON in scx_init()), so the shared
12385 	 * scx_kf_allow_flags[] table indexed by SCX_MOFF_IDX(moff) applies to
12386 	 * both.
12387 	 */
12388 	if (prog->aux->st_ops != &bpf_sched_ext_ops &&
12389 	    prog->aux->st_ops != &bpf_sched_ext_ops_cid)
12390 		return -EACCES;
12391 
12392 	/*
12393 	 * cid-form schedulers must use cid/cmask kfuncs. cid and cpu are both
12394 	 * small s32s and trivially confused, so cpu-only kfuncs are rejected at
12395 	 * load time. The reverse (cpu-form calling cid-form kfuncs) is
12396 	 * intentionally permissive to ease gradual cpumask -> cid migration.
12397 	 */
12398 	if (prog->aux->st_ops == &bpf_sched_ext_ops_cid && in_cpu_only)
12399 		return -EACCES;
12400 
12401 	/* SCX struct_ops: check the per-op allow list. */
12402 	if (in_any || in_idle || in_cid)
12403 		return 0;
12404 
12405 	moff = prog->aux->attach_st_ops_member_off;
12406 	flags = scx_kf_allow_flags[SCX_MOFF_IDX(moff)];
12407 
12408 	if ((flags & SCX_KF_ALLOW_UNLOCKED) && in_unlocked)
12409 		return 0;
12410 	if ((flags & SCX_KF_ALLOW_INIT_CIDS) && in_init_cids)
12411 		return 0;
12412 	if ((flags & SCX_KF_ALLOW_CPU_RELEASE) && in_cpu_release)
12413 		return 0;
12414 	if ((flags & SCX_KF_ALLOW_DISPATCH) && in_dispatch)
12415 		return 0;
12416 	if ((flags & SCX_KF_ALLOW_ENQUEUE) && in_enqueue)
12417 		return 0;
12418 	if ((flags & SCX_KF_ALLOW_SELECT_CPU) && in_select_cpu)
12419 		return 0;
12420 
12421 	return -EACCES;
12422 }
12423 
12424 static int __init scx_init(void)
12425 {
12426 	int ret;
12427 
12428 	/*
12429 	 * sched_ext_ops_cid mirrors sched_ext_ops up to and including @priv.
12430 	 * Both bpf_scx_init_member() and bpf_scx_check_member() use offsets
12431 	 * from struct sched_ext_ops; sched_ext_ops_cid relies on those offsets
12432 	 * matching for the shared fields. Catch any drift at boot.
12433 	 */
12434 #define CID_OFFSET_MATCH(cpu_field, cid_field)					\
12435 	BUILD_BUG_ON(offsetof(struct sched_ext_ops, cpu_field) !=		\
12436 		     offsetof(struct sched_ext_ops_cid, cid_field))
12437 	/* data fields used by bpf_scx_init_member() */
12438 	CID_OFFSET_MATCH(dispatch_max_batch, dispatch_max_batch);
12439 	CID_OFFSET_MATCH(flags, flags);
12440 	CID_OFFSET_MATCH(name, name);
12441 	CID_OFFSET_MATCH(timeout_ms, timeout_ms);
12442 	CID_OFFSET_MATCH(exit_dump_len, exit_dump_len);
12443 	CID_OFFSET_MATCH(hotplug_seq, hotplug_seq);
12444 	CID_OFFSET_MATCH(cid_shard_size, cid_shard_size);
12445 	CID_OFFSET_MATCH(rescue_bandwidth_ppt, rescue_bandwidth_ppt);
12446 	CID_OFFSET_MATCH(rescue_quantum_us, rescue_quantum_us);
12447 	CID_OFFSET_MATCH(sub_cgroup_id, sub_cgroup_id);
12448 	/* shared callbacks: the union view requires byte-for-byte offset match */
12449 	CID_OFFSET_MATCH(enqueue, enqueue);
12450 	CID_OFFSET_MATCH(dequeue, dequeue);
12451 	CID_OFFSET_MATCH(dispatch, dispatch);
12452 	CID_OFFSET_MATCH(tick, tick);
12453 	CID_OFFSET_MATCH(runnable, runnable);
12454 	CID_OFFSET_MATCH(running, running);
12455 	CID_OFFSET_MATCH(stopping, stopping);
12456 	CID_OFFSET_MATCH(quiescent, quiescent);
12457 	CID_OFFSET_MATCH(yield, yield);
12458 	CID_OFFSET_MATCH(core_sched_before, core_sched_before);
12459 	CID_OFFSET_MATCH(set_weight, set_weight);
12460 	CID_OFFSET_MATCH(update_idle, update_idle);
12461 	CID_OFFSET_MATCH(init_task, init_task);
12462 	CID_OFFSET_MATCH(exit_task, exit_task);
12463 	CID_OFFSET_MATCH(enable, enable);
12464 	CID_OFFSET_MATCH(disable, disable);
12465 	CID_OFFSET_MATCH(dump, dump);
12466 	CID_OFFSET_MATCH(dump_task, dump_task);
12467 	CID_OFFSET_MATCH(sub_attach, sub_attach);
12468 	CID_OFFSET_MATCH(sub_detach, sub_detach);
12469 	CID_OFFSET_MATCH(sub_caps_updated, sub_caps_updated);
12470 	CID_OFFSET_MATCH(sub_ecaps_updated, sub_ecaps_updated);
12471 	CID_OFFSET_MATCH(sub_cid_sched_updated, sub_cid_sched_updated);
12472 	CID_OFFSET_MATCH(sub_child_ecaps_updated, sub_child_ecaps_updated);
12473 	CID_OFFSET_MATCH(init_cids, init_cids);
12474 	CID_OFFSET_MATCH(init, init);
12475 	CID_OFFSET_MATCH(exit, exit);
12476 	/* renamed callbacks must occupy the same slot as their cpu-form sibling */
12477 	CID_OFFSET_MATCH(select_cpu, select_cid);
12478 	CID_OFFSET_MATCH(set_cpumask, set_cmask);
12479 	CID_OFFSET_MATCH(cpu_online, cid_online);
12480 	CID_OFFSET_MATCH(cpu_offline, cid_offline);
12481 	CID_OFFSET_MATCH(dump_cpu, dump_cid);
12482 #ifdef CONFIG_EXT_GROUP_SCHED
12483 	CID_OFFSET_MATCH(cgroup_init, cpuctl_init);
12484 	CID_OFFSET_MATCH(cgroup_exit, cpuctl_exit);
12485 	CID_OFFSET_MATCH(cgroup_prep_move, cpuctl_prep_move);
12486 	CID_OFFSET_MATCH(cgroup_move, cpuctl_move);
12487 	CID_OFFSET_MATCH(cgroup_cancel_move, cpuctl_cancel_move);
12488 	CID_OFFSET_MATCH(cgroup_set_weight, cpuctl_set_weight);
12489 	CID_OFFSET_MATCH(cgroup_set_bandwidth, cpuctl_set_bandwidth);
12490 	CID_OFFSET_MATCH(cgroup_set_idle, cpuctl_set_idle);
12491 #endif
12492 	/* @priv tail must align since both share the same data block */
12493 	CID_OFFSET_MATCH(priv, priv);
12494 	/*
12495 	 * cid-form must end exactly at @priv - scx_validate_ops() skips
12496 	 * cpu_acquire/cpu_release for cid-form because reading those fields
12497 	 * past the BPF allocation would be UB.
12498 	 */
12499 	BUILD_BUG_ON(offsetof(struct sched_ext_ops_cid, __end) !=
12500 		     offsetofend(struct sched_ext_ops, priv));
12501 #undef CID_OFFSET_MATCH
12502 
12503 	/*
12504 	 * kfunc registration can't be done from init_sched_ext_class() as
12505 	 * register_btf_kfunc_id_set() needs most of the system to be up.
12506 	 *
12507 	 * Some kfuncs are context-sensitive and can only be called from
12508 	 * specific SCX ops. They are grouped into per-context BTF sets, each
12509 	 * registered with scx_kfunc_context_filter as its .filter callback. The
12510 	 * BPF core dedups identical filter pointers per hook
12511 	 * (btf_populate_kfunc_set()), so the filter is invoked exactly once per
12512 	 * kfunc lookup; it consults scx_kf_allow_flags[] to enforce per-op
12513 	 * restrictions at verify time.
12514 	 */
12515 	if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
12516 					     &scx_kfunc_set_enqueue_dispatch)) ||
12517 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
12518 					     &scx_kfunc_set_dispatch)) ||
12519 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
12520 					     &scx_kfunc_set_cpu_release)) ||
12521 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
12522 					     &scx_kfunc_set_unlocked)) ||
12523 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
12524 					     &scx_kfunc_set_unlocked)) ||
12525 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
12526 					     &scx_kfunc_set_any)) ||
12527 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
12528 					     &scx_kfunc_set_any)) ||
12529 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
12530 					     &scx_kfunc_set_any))) {
12531 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
12532 		return ret;
12533 	}
12534 
12535 	ret = scx_idle_init();
12536 	if (ret) {
12537 		pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret);
12538 		return ret;
12539 	}
12540 
12541 	ret = scx_cid_kfunc_init();
12542 	if (ret) {
12543 		pr_err("sched_ext: Failed to register cid kfuncs (%d)\n", ret);
12544 		return ret;
12545 	}
12546 
12547 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops);
12548 	if (ret) {
12549 		pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret);
12550 		return ret;
12551 	}
12552 
12553 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops_cid, sched_ext_ops_cid);
12554 	if (ret) {
12555 		pr_err("sched_ext: Failed to register cid struct_ops (%d)\n", ret);
12556 		return ret;
12557 	}
12558 
12559 	ret = register_pm_notifier(&scx_pm_notifier);
12560 	if (ret) {
12561 		pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret);
12562 		return ret;
12563 	}
12564 
12565 	scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj);
12566 	if (!scx_kset) {
12567 		pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n");
12568 		return -ENOMEM;
12569 	}
12570 
12571 	ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group);
12572 	if (ret < 0) {
12573 		pr_err("sched_ext: Failed to add global attributes\n");
12574 		return ret;
12575 	}
12576 
12577 	return 0;
12578 }
12579 __initcall(scx_init);
12580 
12581 /*
12582  * Compatibility markers for userspace. Existence of a marker function
12583  * represents that the kernel supports that sched-ext feature.
12584  */
12585 
12586 /*
12587  * scx_compat_marker_cgroup_set_bandwidth_may_sleep: advertises that
12588  * ops.cgroup_set_bandwidth() may be implemented as a sleepable callback.
12589  */
12590 #ifdef CONFIG_EXT_GROUP_SCHED
12591 DEFINE_SCX_COMPAT_MARKER(cgroup_set_bandwidth_may_sleep);
12592 #endif	/* CONFIG_EXT_GROUP_SCHED */
12593