xref: /linux/kernel/sched/ext/internal.h (revision a8dc810968af02190f55cc7574bc87c93156f266)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * BPF extensible scheduler class: Documentation/scheduler/sched-ext.rst
4  *
5  * Copyright (c) 2025 Meta Platforms, Inc. and affiliates.
6  * Copyright (c) 2025 Tejun Heo <tj@kernel.org>
7  */
8 #ifndef _KERNEL_SCHED_EXT_INTERNAL_H
9 #define _KERNEL_SCHED_EXT_INTERNAL_H
10 
11 #include "../sched.h"
12 #include "types.h"
13 
14 #include <trace/events/sched_ext.h>
15 
16 /**
17  * scx_add_event - Increase an event counter for 'name' by 'cnt'
18  * @sch: scx_sched to account events for
19  * @name: an event name defined in struct scx_event_stats
20  * @cnt: the number of the event occurred
21  *
22  * This can be used when preemption is not disabled.
23  */
24 #define scx_add_event(sch, name, cnt) do {					\
25 	this_cpu_add((sch)->pcpu->event_stats.name, (cnt));			\
26 	trace_sched_ext_event(#name, (cnt));					\
27 } while(0)
28 
29 /**
30  * __scx_add_event - Increase an event counter for 'name' by 'cnt'
31  * @sch: scx_sched to account events for
32  * @name: an event name defined in struct scx_event_stats
33  * @cnt: the number of the event occurred
34  *
35  * This should be used only when preemption is disabled.
36  */
37 #define __scx_add_event(sch, name, cnt) do {					\
38 	__this_cpu_add((sch)->pcpu->event_stats.name, (cnt));			\
39 	trace_sched_ext_event(#name, cnt);					\
40 } while(0)
41 
42 #define SCX_OP_IDX(op)		(offsetof(struct sched_ext_ops, op) / sizeof(void (*)(void)))
43 #define SCX_MOFF_IDX(moff)	((moff) / sizeof(void (*)(void)))
44 
45 enum scx_exit_kind {
46 	SCX_EXIT_NONE,
47 	SCX_EXIT_DONE,
48 
49 	SCX_EXIT_UNREG = 64,	/* user-space initiated unregistration */
50 	SCX_EXIT_UNREG_BPF,	/* BPF-initiated unregistration */
51 	SCX_EXIT_UNREG_KERN,	/* kernel-initiated unregistration */
52 	SCX_EXIT_SYSRQ,		/* requested by 'S' sysrq */
53 	SCX_EXIT_PARENT,	/* parent exiting */
54 	SCX_EXIT_PARENT_KILL,	/* killed by parent scheduler */
55 
56 	SCX_EXIT_ERROR = 1024,	/* runtime error, error msg contains details */
57 	SCX_EXIT_ERROR_BPF,	/* ERROR but triggered through scx_bpf_error() */
58 	SCX_EXIT_ERROR_STALL,	/* watchdog detected stalled runnable tasks */
59 	SCX_EXIT_ERROR_REENQ,	/* task hit reenqueue limit without running */
60 	SCX_EXIT_ERROR_RESCUE,	/* ejected for overloading rescue execution */
61 };
62 
63 /*
64  * An exit code can be specified when exiting with scx_bpf_exit() or scx_exit(),
65  * corresponding to exit_kind UNREG_BPF and UNREG_KERN respectively. The codes
66  * are 64bit of the format:
67  *
68  *   Bits: [63  ..  48 47   ..  32 31 .. 0]
69  *         [ SYS ACT ] [ SYS RSN ] [ USR  ]
70  *
71  *   SYS ACT: System-defined exit actions
72  *   SYS RSN: System-defined exit reasons
73  *   USR    : User-defined exit codes and reasons
74  *
75  * Using the above, users may communicate intention and context by ORing system
76  * actions and/or system reasons with a user-defined exit code.
77  */
78 enum scx_exit_code {
79 	/* Reasons */
80 	SCX_ECODE_RSN_HOTPLUG	= 1LLU << 32,
81 	SCX_ECODE_RSN_CGROUP_OFFLINE = 2LLU << 32,
82 
83 	/* Actions */
84 	SCX_ECODE_ACT_RESTART	= 1LLU << 48,
85 };
86 
87 enum scx_exit_flags {
88 	/*
89 	 * ops.exit() may be called even if the loading failed before ops.init()
90 	 * finishes successfully. This is because ops.exit() allows rich exit
91 	 * info communication. The following flag indicates whether ops.init()
92 	 * finished successfully.
93 	 */
94 	SCX_EFLAG_INITIALIZED   = 1LLU << 0,
95 };
96 
97 /*
98  * scx_exit_info is passed to ops.exit() to describe why the BPF scheduler is
99  * being disabled.
100  */
101 struct scx_exit_info {
102 	/* %SCX_EXIT_* - broad category of the exit reason */
103 	enum scx_exit_kind	kind;
104 
105 	/*
106 	 * CPU that initiated the exit, valid once @kind has been set.
107 	 * Negative if the exit path didn't identify a CPU.
108 	 */
109 	s32			exit_cpu;
110 
111 	/* exit code if gracefully exiting */
112 	s64			exit_code;
113 
114 	/* %SCX_EFLAG_* */
115 	u64			flags;
116 
117 	/* textual representation of the above */
118 	const char		*reason;
119 
120 	/* backtrace if exiting due to an error */
121 	unsigned long		*bt;
122 	u32			bt_len;
123 
124 	/* informational message */
125 	char			*msg;
126 
127 	/* debug dump */
128 	char			*dump;
129 };
130 
131 /* sched_ext_ops.flags */
132 enum scx_ops_flags {
133 	/*
134 	 * Keep built-in idle tracking even if ops.update_idle() is implemented.
135 	 */
136 	SCX_OPS_KEEP_BUILTIN_IDLE	= 1LLU << 0,
137 
138 	/*
139 	 * By default, if there are no other task to run on the CPU, ext core
140 	 * keeps running the current task even after its slice expires. If this
141 	 * flag is specified, such tasks are passed to ops.enqueue() with
142 	 * %SCX_ENQ_LAST. See the comment above %SCX_ENQ_LAST for more info.
143 	 */
144 	SCX_OPS_ENQ_LAST		= 1LLU << 1,
145 
146 	/*
147 	 * An exiting task may schedule after PF_EXITING is set. In such cases,
148 	 * bpf_task_from_pid() may not be able to find the task and if the BPF
149 	 * scheduler depends on pid lookup for dispatching, the task will be
150 	 * lost leading to various issues including RCU grace period stalls.
151 	 *
152 	 * To mask this problem, by default, unhashed tasks are automatically
153 	 * dispatched to the local DSQ on enqueue. If the BPF scheduler doesn't
154 	 * depend on pid lookups and wants to handle these tasks directly, the
155 	 * following flag can be used. With %SCX_OPS_TID_TO_TASK,
156 	 * scx_bpf_tid_to_task() can find exiting tasks reliably.
157 	 */
158 	SCX_OPS_ENQ_EXITING		= 1LLU << 2,
159 
160 	/*
161 	 * If set, only tasks with policy set to SCHED_EXT are attached to
162 	 * sched_ext. If clear, SCHED_NORMAL tasks are also included.
163 	 */
164 	SCX_OPS_SWITCH_PARTIAL		= 1LLU << 3,
165 
166 	/*
167 	 * A migration disabled task can only execute on its current CPU. By
168 	 * default, such tasks are automatically put on the CPU's local DSQ with
169 	 * the default slice on enqueue. If this ops flag is set, they also go
170 	 * through ops.enqueue().
171 	 *
172 	 * A migration disabled task never invokes ops.select_cpu() as it can
173 	 * only select the current CPU. Also, p->cpus_ptr will only contain its
174 	 * current CPU while p->nr_cpus_allowed keeps tracking p->user_cpus_ptr
175 	 * and thus may disagree with cpumask_weight(p->cpus_ptr).
176 	 */
177 	SCX_OPS_ENQ_MIGRATION_DISABLED	= 1LLU << 4,
178 
179 	/*
180 	 * Queued wakeup (ttwu_queue) is a wakeup optimization that invokes
181 	 * ops.enqueue() on the ops.select_cpu() selected or the wakee's
182 	 * previous CPU via IPI (inter-processor interrupt) to reduce cacheline
183 	 * transfers. When this optimization is enabled, ops.select_cpu() is
184 	 * skipped in some cases (when racing against the wakee switching out).
185 	 * As the BPF scheduler may depend on ops.select_cpu() being invoked
186 	 * during wakeups, queued wakeup is disabled by default.
187 	 *
188 	 * If this ops flag is set, queued wakeup optimization is enabled and
189 	 * the BPF scheduler must be able to handle ops.enqueue() invoked on the
190 	 * wakee's CPU without preceding ops.select_cpu() even for tasks which
191 	 * may be executed on multiple CPUs.
192 	 */
193 	SCX_OPS_ALLOW_QUEUED_WAKEUP	= 1LLU << 5,
194 
195 	/*
196 	 * If set, enable per-node idle cpumasks. If clear, use a single global
197 	 * flat idle cpumask.
198 	 */
199 	SCX_OPS_BUILTIN_IDLE_PER_NODE	= 1LLU << 6,
200 
201 	/*
202 	 * If set, %SCX_ENQ_IMMED is assumed to be set on all local DSQ
203 	 * enqueues.
204 	 */
205 	SCX_OPS_ALWAYS_ENQ_IMMED	= 1LLU << 7,
206 
207 	/*
208 	 * Maintain a mapping from p->scx.tid to task_struct so the BPF
209 	 * scheduler can recover task pointers from stored tids via
210 	 * scx_bpf_tid_to_task().
211 	 *
212 	 * Only the root scheduler turns this on. A sub-sched may set the flag
213 	 * to declare a dependency on the lookup; if the root scheduler hasn't
214 	 * enabled it, attaching the sub-sched is rejected.
215 	 */
216 	SCX_OPS_TID_TO_TASK		= 1LLU << 8,
217 
218 	SCX_OPS_ALL_FLAGS		= SCX_OPS_KEEP_BUILTIN_IDLE |
219 					  SCX_OPS_ENQ_LAST |
220 					  SCX_OPS_ENQ_EXITING |
221 					  SCX_OPS_ENQ_MIGRATION_DISABLED |
222 					  SCX_OPS_ALLOW_QUEUED_WAKEUP |
223 					  SCX_OPS_SWITCH_PARTIAL |
224 					  SCX_OPS_BUILTIN_IDLE_PER_NODE |
225 					  SCX_OPS_ALWAYS_ENQ_IMMED |
226 					  SCX_OPS_TID_TO_TASK,
227 
228 	/* high 8 bits are internal, don't include in SCX_OPS_ALL_FLAGS */
229 	__SCX_OPS_INTERNAL_MASK		= 0xffLLU << 56,
230 
231 	SCX_OPS_HAS_CPU_PREEMPT		= 1LLU << 56,
232 };
233 
234 /* argument container for ops.init_task() */
235 struct scx_init_task_args {
236 	/*
237 	 * Set if ops.init_task() is being invoked on the fork path, as opposed
238 	 * to the scheduler transition path.
239 	 */
240 	bool			fork;
241 #ifdef CONFIG_EXT_GROUP_SCHED
242 	/* the cgroup the task is joining */
243 	struct cgroup		*cgroup;
244 #endif
245 };
246 
247 /* argument container for ops.exit_task() */
248 struct scx_exit_task_args {
249 	/* Whether the task exited before running on sched_ext. */
250 	bool cancelled;
251 };
252 
253 /* argument container for ops.cgroup_init() */
254 struct scx_cgroup_init_args {
255 	/* the weight of the cgroup [1..10000] */
256 	u32			weight;
257 
258 	/* bandwidth control parameters from cpu.max and cpu.max.burst */
259 	u64			bw_period_us;
260 	u64			bw_quota_us;
261 	u64			bw_burst_us;
262 };
263 
264 enum scx_cpu_preempt_reason {
265 	/* next task is being scheduled by &sched_class_rt */
266 	SCX_CPU_PREEMPT_RT,
267 	/* next task is being scheduled by &sched_class_dl */
268 	SCX_CPU_PREEMPT_DL,
269 	/* next task is being scheduled by &sched_class_stop */
270 	SCX_CPU_PREEMPT_STOP,
271 	/* unknown reason for SCX being preempted */
272 	SCX_CPU_PREEMPT_UNKNOWN,
273 };
274 
275 /*
276  * Argument container for ops.cpu_acquire(). Currently empty, but may be
277  * expanded in the future.
278  */
279 struct scx_cpu_acquire_args {};
280 
281 /* argument container for ops.cpu_release() */
282 struct scx_cpu_release_args {
283 	/* the reason the CPU was preempted */
284 	enum scx_cpu_preempt_reason reason;
285 
286 	/* the task that's going to be scheduled on the CPU */
287 	struct task_struct	*task;
288 };
289 
290 /* informational context provided to dump operations */
291 struct scx_dump_ctx {
292 	enum scx_exit_kind	kind;
293 	s64			exit_code;
294 	const char		*reason;
295 	u64			at_ns;
296 	u64			at_jiffies;
297 };
298 
299 /* argument container for ops.sub_attach() */
300 struct scx_sub_attach_args {
301 	struct sched_ext_ops	*ops;
302 	char			*cgroup_path;
303 };
304 
305 /* argument container for ops.sub_detach() */
306 struct scx_sub_detach_args {
307 	struct sched_ext_ops	*ops;
308 	char			*cgroup_path;
309 };
310 
311 /**
312  * struct sched_ext_ops - Operation table for BPF scheduler implementation
313  *
314  * A BPF scheduler can implement an arbitrary scheduling policy by
315  * implementing and loading operations in this table. Note that a userland
316  * scheduling policy can also be implemented using the BPF scheduler
317  * as a shim layer.
318  */
319 struct sched_ext_ops {
320 	/**
321 	 * @select_cpu: Pick the target CPU for a task which is being woken up
322 	 * @p: task being woken up
323 	 * @prev_cpu: the cpu @p was on before sleeping
324 	 * @wake_flags: SCX_WAKE_*
325 	 *
326 	 * Decision made here isn't final. @p may be moved to any CPU while it
327 	 * is getting dispatched for execution later. However, as @p is not on
328 	 * the rq at this point, getting the eventual execution CPU right here
329 	 * saves a small bit of overhead down the line.
330 	 *
331 	 * If an idle CPU is returned, the CPU is kicked and will try to
332 	 * dispatch. While an explicit custom mechanism can be added,
333 	 * select_cpu() serves as the default way to wake up idle CPUs.
334 	 *
335 	 * @p may be inserted into a DSQ directly by calling
336 	 * scx_bpf_dsq_insert(). If so, the ops.enqueue() will be skipped.
337 	 * Directly inserting into %SCX_DSQ_LOCAL will put @p in the local DSQ
338 	 * of the CPU returned by this operation.
339 	 *
340 	 * Note that select_cpu() is never called for tasks that can only run
341 	 * on a single CPU or tasks with migration disabled, as they don't have
342 	 * the option to select a different CPU. See select_task_rq() for
343 	 * details.
344 	 */
345 	s32 (*select_cpu)(struct task_struct *p, s32 prev_cpu, u64 wake_flags);
346 
347 	/**
348 	 * @enqueue: Enqueue a task on the BPF scheduler
349 	 * @p: task being enqueued
350 	 * @enq_flags: %SCX_ENQ_*
351 	 *
352 	 * @p is ready to run. Insert directly into a DSQ by calling
353 	 * scx_bpf_dsq_insert() or enqueue on the BPF scheduler. If not directly
354 	 * inserted, the bpf scheduler owns @p and if it fails to dispatch @p,
355 	 * the task will stall.
356 	 *
357 	 * If @p was inserted into a DSQ from ops.select_cpu(), this callback is
358 	 * skipped.
359 	 */
360 	void (*enqueue)(struct task_struct *p, u64 enq_flags);
361 
362 	/**
363 	 * @dequeue: Remove a task from the BPF scheduler
364 	 * @p: task being dequeued
365 	 * @deq_flags: %SCX_DEQ_*
366 	 *
367 	 * Remove @p from the BPF scheduler. This is usually called to isolate
368 	 * the task while updating its scheduling properties (e.g. priority).
369 	 *
370 	 * The ext core keeps track of whether the BPF side owns a given task or
371 	 * not and can gracefully ignore spurious dispatches from BPF side,
372 	 * which makes it safe to not implement this method. However, depending
373 	 * on the scheduling logic, this can lead to confusing behaviors - e.g.
374 	 * scheduling position not being updated across a priority change.
375 	 */
376 	void (*dequeue)(struct task_struct *p, u64 deq_flags);
377 
378 	/**
379 	 * @dispatch: Dispatch tasks from the BPF scheduler and/or user DSQs
380 	 * @cpu: CPU to dispatch tasks for
381 	 * @prev: previous task being switched out
382 	 *
383 	 * Called when a CPU's local dsq is empty. The operation should dispatch
384 	 * one or more tasks from the BPF scheduler into the DSQs using
385 	 * scx_bpf_dsq_insert() and/or move from user DSQs into the local DSQ
386 	 * using scx_bpf_dsq_move_to_local().
387 	 *
388 	 * The maximum number of times scx_bpf_dsq_insert() can be called
389 	 * without an intervening scx_bpf_dsq_move_to_local() is specified by
390 	 * ops.dispatch_max_batch. See the comments on top of the two functions
391 	 * for more details.
392 	 *
393 	 * When not %NULL, @prev is an SCX task with its slice depleted. If
394 	 * @prev is still runnable as indicated by set %SCX_TASK_QUEUED in
395 	 * @prev->scx.flags, it is not enqueued yet and will be enqueued after
396 	 * ops.dispatch() returns. To keep executing @prev, return without
397 	 * dispatching or moving any tasks. Also see %SCX_OPS_ENQ_LAST.
398 	 */
399 	void (*dispatch)(s32 cpu, struct task_struct *prev);
400 
401 	/**
402 	 * @tick: Periodic tick
403 	 * @p: task running currently
404 	 *
405 	 * This operation is called every 1/HZ seconds on CPUs which are
406 	 * executing an SCX task. Setting a slice of 0 for @p with
407 	 * scx_bpf_task_set_slice() will trigger an immediate dispatch cycle on
408 	 * the CPU.
409 	 */
410 	void (*tick)(struct task_struct *p);
411 
412 	/**
413 	 * @runnable: A task is becoming runnable on its associated CPU
414 	 * @p: task becoming runnable
415 	 * @enq_flags: %SCX_ENQ_*
416 	 *
417 	 * This and the following three functions can be used to track a task's
418 	 * execution state transitions. A task becomes ->runnable() on a CPU,
419 	 * and then goes through one or more ->running() and ->stopping() pairs
420 	 * as it runs on the CPU, and eventually becomes ->quiescent() when it's
421 	 * done running on the CPU.
422 	 *
423 	 * @p is becoming runnable on the CPU because it's
424 	 *
425 	 * - waking up (%SCX_ENQ_WAKEUP)
426 	 * - being moved from another CPU
427 	 * - being restored after temporarily taken off the queue for an
428 	 *   attribute change.
429 	 *
430 	 * This and ->enqueue() are related but not coupled. This operation
431 	 * notifies @p's state transition and may not be followed by ->enqueue()
432 	 * e.g. when @p is being dispatched to a remote CPU, or when @p is
433 	 * being enqueued on a CPU experiencing a hotplug event. Likewise, a
434 	 * task may be ->enqueue()'d without being preceded by this operation
435 	 * e.g. after exhausting its slice.
436 	 */
437 	void (*runnable)(struct task_struct *p, u64 enq_flags);
438 
439 	/**
440 	 * @running: A task is starting to run on its associated CPU
441 	 * @p: task starting to run
442 	 *
443 	 * Note that this callback may be called from a CPU other than the
444 	 * one the task is going to run on. This can happen when a task
445 	 * property is changed (i.e., affinity), since scx_next_task_scx(),
446 	 * which triggers this callback, may run on a CPU different from
447 	 * the task's assigned CPU.
448 	 *
449 	 * Therefore, always use scx_bpf_task_cpu(@p) to determine the
450 	 * target CPU the task is going to use.
451 	 *
452 	 * See ->runnable() for explanation on the task state notifiers.
453 	 */
454 	void (*running)(struct task_struct *p);
455 
456 	/**
457 	 * @stopping: A task is stopping execution
458 	 * @p: task stopping to run
459 	 * @runnable: is task @p still runnable?
460 	 *
461 	 * Note that this callback may be called from a CPU other than the
462 	 * one the task was running on. This can happen when a task
463 	 * property is changed (i.e., affinity), since dequeue_task_scx(),
464 	 * which triggers this callback, may run on a CPU different from
465 	 * the task's assigned CPU.
466 	 *
467 	 * Therefore, always use scx_bpf_task_cpu(@p) to retrieve the CPU
468 	 * the task was running on.
469 	 *
470 	 * See ->runnable() for explanation on the task state notifiers. If
471 	 * !@runnable, ->quiescent() will be invoked after this operation
472 	 * returns.
473 	 */
474 	void (*stopping)(struct task_struct *p, bool runnable);
475 
476 	/**
477 	 * @quiescent: A task is becoming not runnable on its associated CPU
478 	 * @p: task becoming not runnable
479 	 * @deq_flags: %SCX_DEQ_*
480 	 *
481 	 * See ->runnable() for explanation on the task state notifiers.
482 	 *
483 	 * @p is becoming quiescent on the CPU because it's
484 	 *
485 	 * - sleeping (%SCX_DEQ_SLEEP)
486 	 * - being moved to another CPU
487 	 * - being temporarily taken off the queue for an attribute change
488 	 *   (%SCX_DEQ_SAVE)
489 	 *
490 	 * This and ->dequeue() are related but not coupled. This operation
491 	 * notifies @p's state transition and may not be preceded by ->dequeue()
492 	 * e.g. when @p is being dispatched to a remote CPU.
493 	 */
494 	void (*quiescent)(struct task_struct *p, u64 deq_flags);
495 
496 	/**
497 	 * @yield: Yield CPU
498 	 * @from: yielding task
499 	 * @to: optional yield target task
500 	 *
501 	 * If @to is NULL, @from is yielding the CPU to other runnable tasks.
502 	 * The BPF scheduler should ensure that other available tasks are
503 	 * dispatched before the yielding task. Return value is ignored in this
504 	 * case.
505 	 *
506 	 * If @to is not-NULL, @from wants to yield the CPU to @to. If the bpf
507 	 * scheduler can implement the request, return %true; otherwise, %false.
508 	 */
509 	bool (*yield)(struct task_struct *from, struct task_struct *to);
510 
511 	/**
512 	 * @core_sched_before: Task ordering for core-sched
513 	 * @a: task A
514 	 * @b: task B
515 	 *
516 	 * Used by core-sched to determine the ordering between two tasks. See
517 	 * Documentation/admin-guide/hw-vuln/core-scheduling.rst for details on
518 	 * core-sched.
519 	 *
520 	 * Both @a and @b are runnable and may or may not currently be queued on
521 	 * the BPF scheduler. Should return %true if @a should run before @b.
522 	 * %false if there's no required ordering or @b should run before @a.
523 	 *
524 	 * If not specified, the default is ordering them according to when they
525 	 * became runnable.
526 	 */
527 	bool (*core_sched_before)(struct task_struct *a, struct task_struct *b);
528 
529 	/**
530 	 * @set_weight: Set task weight
531 	 * @p: task to set weight for
532 	 * @weight: new weight [1..10000]
533 	 *
534 	 * Update @p's weight to @weight.
535 	 */
536 	void (*set_weight)(struct task_struct *p, u32 weight);
537 
538 	/**
539 	 * @set_cpumask: Set CPU affinity
540 	 * @p: task to set CPU affinity for
541 	 * @cpumask: cpumask of cpus that @p can run on
542 	 *
543 	 * Update @p's CPU affinity to @cpumask.
544 	 */
545 	void (*set_cpumask)(struct task_struct *p,
546 			    const struct cpumask *cpumask);
547 
548 	/**
549 	 * @update_idle: Update the idle state of a CPU
550 	 * @cpu: CPU to update the idle state for
551 	 * @idle: whether entering or exiting the idle state
552 	 *
553 	 * This operation is called when @rq's CPU goes or leaves the idle
554 	 * state. By default, implementing this operation disables the built-in
555 	 * idle CPU tracking and the following helpers become unavailable:
556 	 *
557 	 * - scx_bpf_select_cpu_dfl()
558 	 * - scx_bpf_select_cpu_and()
559 	 * - scx_bpf_test_and_clear_cpu_idle()
560 	 * - scx_bpf_pick_idle_cpu()
561 	 *
562 	 * The user also must implement ops.select_cpu() as the default
563 	 * implementation relies on scx_bpf_select_cpu_dfl().
564 	 *
565 	 * Specify the %SCX_OPS_KEEP_BUILTIN_IDLE flag to keep the built-in idle
566 	 * tracking.
567 	 */
568 	void (*update_idle)(s32 cpu, bool idle);
569 
570 	/**
571 	 * @init_task: Initialize a task to run in a BPF scheduler
572 	 * @p: task to initialize for BPF scheduling
573 	 * @args: init arguments, see the struct definition
574 	 *
575 	 * Either we're loading a BPF scheduler or a new task is being forked.
576 	 * Initialize @p for BPF scheduling. This operation may block and can
577 	 * be used for allocations, and is called exactly once for a task.
578 	 *
579 	 * Return 0 for success, -errno for failure. An error return while
580 	 * loading will abort loading of the BPF scheduler. During a fork, it
581 	 * will abort that specific fork.
582 	 */
583 	s32 (*init_task)(struct task_struct *p, struct scx_init_task_args *args);
584 
585 	/**
586 	 * @exit_task: Exit a previously-running task from the system
587 	 * @p: task to exit
588 	 * @args: exit arguments, see the struct definition
589 	 *
590 	 * @p is exiting or the BPF scheduler is being unloaded. Perform any
591 	 * necessary cleanup for @p.
592 	 */
593 	void (*exit_task)(struct task_struct *p, struct scx_exit_task_args *args);
594 
595 	/**
596 	 * @enable: Enable BPF scheduling for a task
597 	 * @p: task to enable BPF scheduling for
598 	 *
599 	 * Enable @p for BPF scheduling. enable() is called on @p any time it
600 	 * enters SCX, and is always paired with a matching disable().
601 	 */
602 	void (*enable)(struct task_struct *p);
603 
604 	/**
605 	 * @disable: Disable BPF scheduling for a task
606 	 * @p: task to disable BPF scheduling for
607 	 *
608 	 * @p is exiting, leaving SCX or the BPF scheduler is being unloaded.
609 	 * Disable BPF scheduling for @p. A disable() call is always matched
610 	 * with a prior enable() call.
611 	 */
612 	void (*disable)(struct task_struct *p);
613 
614 	/**
615 	 * @dump: Dump BPF scheduler state on error
616 	 * @ctx: debug dump context
617 	 *
618 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump.
619 	 */
620 	void (*dump)(struct scx_dump_ctx *ctx);
621 
622 	/**
623 	 * @dump_cpu: Dump BPF scheduler state for a CPU on error
624 	 * @ctx: debug dump context
625 	 * @cpu: CPU to generate debug dump for
626 	 * @idle: @cpu is currently idle without any runnable tasks
627 	 *
628 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
629 	 * @cpu. If @idle is %true and this operation doesn't produce any
630 	 * output, @cpu is skipped for dump.
631 	 */
632 	void (*dump_cpu)(struct scx_dump_ctx *ctx, s32 cpu, bool idle);
633 
634 	/**
635 	 * @dump_task: Dump BPF scheduler state for a runnable task on error
636 	 * @ctx: debug dump context
637 	 * @p: runnable task to generate debug dump for
638 	 *
639 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
640 	 * @p.
641 	 */
642 	void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p);
643 
644 #ifdef CONFIG_EXT_GROUP_SCHED
645 	/**
646 	 * @cgroup_init: Initialize a cgroup
647 	 * @cgrp: cgroup being initialized
648 	 * @args: init arguments, see the struct definition
649 	 *
650 	 * Initialize @cgrp for sched_ext, delivered to @cgrp's sched either
651 	 * when the BPF scheduler is being loaded or when @cgrp is created. This
652 	 * operation may block.
653 	 *
654 	 * Cgroup handovers also generate these ops: an enabling sub-scheduler
655 	 * receives ops.cgroup_init() for every cgroup in its subtree while the
656 	 * previous sched receives ops.cgroup_exit(), and disabling reverses the
657 	 * two.
658 	 *
659 	 * When the BPF scheduler is being loaded or cgroups are being handed
660 	 * over, @cgrp may already have been removed by userspace: a removed
661 	 * cgroup stays schedulable until its dying tasks finish their final
662 	 * context switches.
663 	 *
664 	 * Return 0 for success, -errno for failure. An error return while
665 	 * loading will abort loading of the BPF scheduler. During cgroup
666 	 * creation, it will abort the specific cgroup creation.
667 	 */
668 	s32 (*cgroup_init)(struct cgroup *cgrp,
669 			   struct scx_cgroup_init_args *args);
670 
671 	/**
672 	 * @cgroup_exit: Exit a cgroup
673 	 * @cgrp: cgroup being exited
674 	 *
675 	 * Exit @cgrp for sched_ext, delivered to the sched whose
676 	 * ops.cgroup_init() it pairs with, either when the BPF scheduler is
677 	 * being unloaded or when @cgrp is destroyed. This operation may block.
678 	 *
679 	 * For a destroyed @cgrp, delivery follows the last scheduling event on
680 	 * it: a removed cgroup stays schedulable until its dying tasks finish
681 	 * their final context switches.
682 	 */
683 	void (*cgroup_exit)(struct cgroup *cgrp);
684 
685 	/**
686 	 * @cgroup_prep_move: Prepare a task to be moved to a different cgroup
687 	 * @p: task being moved
688 	 * @from: cgroup @p is being moved from
689 	 * @to: cgroup @p is being moved to
690 	 *
691 	 * Prepare @p for move from cgroup @from to @to. This operation may
692 	 * block and can be used for allocations.
693 	 *
694 	 * The cgroup_move ops are delivered to @p's sched, and only for moves
695 	 * that don't re-home @p. A re-homing move is reported through
696 	 * ops.exit_task() and ops.init_task() instead. @from and @to can
697 	 * reference cgroups the sched never received ops.cgroup_init() for, as
698 	 * the cpu controller can be coarser than the sub-scheduler topology.
699 	 *
700 	 * Return 0 for success, -errno for failure. An error return aborts the
701 	 * migration.
702 	 */
703 	s32 (*cgroup_prep_move)(struct task_struct *p,
704 				struct cgroup *from, struct cgroup *to);
705 
706 	/**
707 	 * @cgroup_move: Commit cgroup move
708 	 * @p: task being moved
709 	 * @from: cgroup @p is being moved from
710 	 * @to: cgroup @p is being moved to
711 	 *
712 	 * Commit the move. @p is dequeued during this operation.
713 	 */
714 	void (*cgroup_move)(struct task_struct *p,
715 			    struct cgroup *from, struct cgroup *to);
716 
717 	/**
718 	 * @cgroup_cancel_move: Cancel cgroup move
719 	 * @p: task whose cgroup move is being canceled
720 	 * @from: cgroup @p was being moved from
721 	 * @to: cgroup @p was being moved to
722 	 *
723 	 * @p was cgroup_prep_move()'d but failed before reaching cgroup_move().
724 	 * Undo the preparation.
725 	 */
726 	void (*cgroup_cancel_move)(struct task_struct *p,
727 				   struct cgroup *from, struct cgroup *to);
728 
729 	/**
730 	 * @cgroup_set_weight: A cgroup's weight is being changed
731 	 * @cgrp: cgroup whose weight is being updated
732 	 * @weight: new weight [1..10000]
733 	 *
734 	 * Update @cgrp's weight to @weight.
735 	 *
736 	 * Knobs of a cgroup belong to the parent, so the set_* ops are
737 	 * delivered to @cgrp's parent's sched. That sched may never have seen
738 	 * ops.cgroup_init() for @cgrp - at a sub-scheduler attach point, the
739 	 * parent sched tracks @cgrp through ops.sub_attach() instead.
740 	 */
741 	void (*cgroup_set_weight)(struct cgroup *cgrp, u32 weight);
742 
743 	/**
744 	 * @cgroup_set_bandwidth: A cgroup's bandwidth is being changed
745 	 * @cgrp: cgroup whose bandwidth is being updated
746 	 * @period_us: bandwidth control period
747 	 * @quota_us: bandwidth control quota
748 	 * @burst_us: bandwidth control burst
749 	 *
750 	 * Update @cgrp's bandwidth control parameters. This is from the cpu.max
751 	 * cgroup interface.
752 	 *
753 	 * @quota_us / @period_us determines the CPU bandwidth @cgrp is entitled
754 	 * to. For example, if @period_us is 1_000_000 and @quota_us is
755 	 * 2_500_000. @cgrp is entitled to 2.5 CPUs. @burst_us can be
756 	 * interpreted in the same fashion and specifies how much @cgrp can
757 	 * burst temporarily. The specific control mechanism and thus the
758 	 * interpretation of @period_us and burstiness is up to the BPF
759 	 * scheduler.
760 	 *
761 	 * Delivery follows the same rule as cgroup_set_weight().
762 	 */
763 	void (*cgroup_set_bandwidth)(struct cgroup *cgrp,
764 				     u64 period_us, u64 quota_us, u64 burst_us);
765 
766 	/**
767 	 * @cgroup_set_idle: A cgroup's idle state is being changed
768 	 * @cgrp: cgroup whose idle state is being updated
769 	 * @idle: whether the cgroup is entering or exiting idle state
770 	 *
771 	 * Update @cgrp's idle state to @idle. This callback is invoked when
772 	 * a cgroup transitions between idle and non-idle states, allowing the
773 	 * BPF scheduler to adjust its behavior accordingly.
774 	 *
775 	 * Delivery follows the same rule as cgroup_set_weight().
776 	 */
777 	void (*cgroup_set_idle)(struct cgroup *cgrp, bool idle);
778 
779 #endif	/* CONFIG_EXT_GROUP_SCHED */
780 
781 	/**
782 	 * @sub_attach: Attach a sub-scheduler
783 	 * @args: argument container, see the struct definition
784 	 *
785 	 * Return 0 to accept the sub-scheduler. -errno to reject.
786 	 */
787 	s32 (*sub_attach)(struct scx_sub_attach_args *args);
788 
789 	/**
790 	 * @sub_detach: Detach a sub-scheduler
791 	 * @args: argument container, see the struct definition
792 	 */
793 	void (*sub_detach)(struct scx_sub_detach_args *args);
794 
795 	/**
796 	 * @sub_caps_updated: Caps on this sub-sched's shard changed
797 	 * @cmask: cids whose caps changed (cmask->base identifies the shard)
798 	 * @caps: SCX_CAP_* that changed
799 	 *
800 	 * Invoked after grant or revoke modifies caps on a shard. There can be
801 	 * only one in-flight invocation per shard. @cmask and @caps coalesce
802 	 * all changes since the last delivery. Direction (set vs cleared) isn't
803 	 * encoded. Query current state with scx_bpf_sub_caps().
804 	 *
805 	 * Delivered asynchronously after the change is recorded, and may run
806 	 * before it takes effect on any given cpu. Use it to track which caps
807 	 * the sub-sched holds and propagate to its own children, not to decide
808 	 * if a task can run on a cpu now. sub_ecaps_updated() reports that per
809 	 * cpu, once it is in effect.
810 	 *
811 	 * May call scx_bpf_sub_grant() / scx_bpf_sub_revoke() on children.
812 	 */
813 	void (*sub_caps_updated)(const struct scx_cmask *cmask, u64 caps);
814 
815 	/**
816 	 * @sub_ecaps_updated: This sub-sched's effective caps on a cid changed
817 	 * @cid: the cid whose effective caps changed
818 	 * @before: effective caps as of the last delivery
819 	 * @after: effective caps now
820 	 *
821 	 * Invoked when this sub-sched's effective caps on @cid change, once the
822 	 * change is in effect on the cpu. Runs in dispatch context with rq lock
823 	 * held, and can perform all operations allowed in ops.dispatch()
824 	 * including inserting/moving tasks.
825 	 */
826 	void (*sub_ecaps_updated)(s32 cid, u64 before, u64 after);
827 
828 	/*
829 	 * All online ops must come before ops.cpu_online().
830 	 */
831 
832 	/**
833 	 * @cpu_online: A CPU became online
834 	 * @cpu: CPU which just came up
835 	 *
836 	 * @cpu just came online. @cpu will not call ops.enqueue() or
837 	 * ops.dispatch(), nor run tasks associated with other CPUs beforehand.
838 	 */
839 	void (*cpu_online)(s32 cpu);
840 
841 	/**
842 	 * @cpu_offline: A CPU is going offline
843 	 * @cpu: CPU which is going offline
844 	 *
845 	 * @cpu is going offline. @cpu will not call ops.enqueue() or
846 	 * ops.dispatch(), nor run tasks associated with other CPUs afterwards.
847 	 */
848 	void (*cpu_offline)(s32 cpu);
849 
850 	/*
851 	 * All CPU hotplug ops must come before ops.init_cids().
852 	 */
853 
854 	/**
855 	 * @init_cids: Finalize the cid layout (cid-form only)
856 	 *
857 	 * Runs after the default cid layout is built, before caps and shards
858 	 * are finalized. A cid-form scheduler may call scx_bpf_cid_override()
859 	 * here for a custom layout. Ignored for cpu-form schedulers.
860 	 */
861 	s32 (*init_cids)(void);
862 
863 	/**
864 	 * @init: Initialize the BPF scheduler
865 	 */
866 	s32 (*init)(void);
867 
868 	/**
869 	 * @exit: Clean up after the BPF scheduler
870 	 * @info: Exit info
871 	 *
872 	 * ops.exit() is also called on ops.init() failure, which is a bit
873 	 * unusual. This is to allow rich reporting through @info on how
874 	 * ops.init() failed.
875 	 */
876 	void (*exit)(struct scx_exit_info *info);
877 
878 	/*
879 	 * Data fields must comes after all ops fields.
880 	 */
881 
882 	/**
883 	 * @dispatch_max_batch: Max nr of tasks that dispatch() can dispatch
884 	 */
885 	u32 dispatch_max_batch;
886 
887 	/**
888 	 * @flags: %SCX_OPS_* flags
889 	 */
890 	u64 flags;
891 
892 	/**
893 	 * @timeout_ms: The maximum amount of time, in milliseconds, that a
894 	 * runnable task should be able to wait before being scheduled. The
895 	 * maximum timeout may not exceed the default timeout of 30 seconds.
896 	 *
897 	 * Defaults to the maximum allowed timeout value of 30 seconds.
898 	 */
899 	u32 timeout_ms;
900 
901 	/**
902 	 * @exit_dump_len: scx_exit_info.dump buffer length. If 0, the default
903 	 * value of 32768 is used.
904 	 */
905 	u32 exit_dump_len;
906 
907 	/**
908 	 * @hotplug_seq: A sequence number that may be set by the scheduler to
909 	 * detect when a hotplug event has occurred during the loading process.
910 	 * If 0, no detection occurs. Otherwise, the scheduler will fail to
911 	 * load if the sequence number does not match @scx_hotplug_seq on the
912 	 * enable path.
913 	 */
914 	u64 hotplug_seq;
915 
916 	/**
917 	 * @cid_shard_size: Target number of CIDs per shard
918 	 *
919 	 * Shards are contiguous CID ranges used as operation and locking
920 	 * domains for sub-scheduling. Each LLC is divided into ceil(nr_cpus /
921 	 * @cid_shard_size) shards, then cores are distributed across them
922 	 * evenly. If one core has more logical CPUs than @cid_shard_size, its
923 	 * shard will become larger than @cid_shard_size. Values above
924 	 * SCX_CID_SHARD_MAX_CPUS are capped. 0 means use the default (24).
925 	 */
926 	u32 cid_shard_size;
927 
928 	/**
929 	 * @rescue_bandwidth_ppt: Rescue execution bandwidth in parts per thousand
930 	 *
931 	 * The fraction of each CPU's time that may be consumed running tasks
932 	 * from its rescue DSQ. A higher bandwidth admits and escalates rescues
933 	 * faster, see @rescue_quantum_us.
934 	 *
935 	 * Only the root scheduler's value is used. 0 means the default of 20
936 	 * (2%). May not exceed 250 (25%). %SCX_RESCUE_DISABLE disables rescue -
937 	 * %SCX_ENQ_RESCUE inserts are then rejected like any other insert
938 	 * lacking the caps.
939 	 */
940 	u32 rescue_bandwidth_ppt;
941 
942 	/**
943 	 * @rescue_quantum_us: Rescue execution quantum in microseconds
944 	 *
945 	 * How much CPU time each rescue gets. Rescues run one at a time per CPU
946 	 * and admissions are paced to keep rescue execution within
947 	 * @rescue_bandwidth_ppt - with the defaults, one 5ms rescue every
948 	 * 250ms. A crowded queue round-robins on the quantum divided across the
949 	 * waiters, floored at 1ms. A stuck rescue eventually escalates to
950 	 * forced execution. A larger quantum interrupts the CPU less often but
951 	 * for longer and spaces rescues further apart.
952 	 *
953 	 * Only the root scheduler's value is used. 0 means the default (5000).
954 	 * Non-zero values must be within [1000, 100000]. Values too short for
955 	 * the kernel to meter are lifted silently.
956 	 */
957 	u32 rescue_quantum_us;
958 
959 	/**
960 	 * @sub_cgroup_id: When >1, attach the scheduler as a sub-scheduler
961 	 * on the specified cgroup.
962 	 */
963 	u64 sub_cgroup_id;
964 
965 	/**
966 	 * @name: BPF scheduler's name
967 	 *
968 	 * Must be a non-zero valid BPF object name including only isalnum(),
969 	 * '_' and '.' chars. Shows up in kernel.sched_ext_ops sysctl while the
970 	 * BPF scheduler is enabled.
971 	 */
972 	char name[SCX_OPS_NAME_LEN];
973 
974 	/* internal use only, must be NULL */
975 	void __rcu *priv;
976 
977 	/*
978 	 * Deprecated callbacks. Kept at the end of the struct so the cid-form
979 	 * struct (sched_ext_ops_cid) can omit them without affecting the
980 	 * shared field offsets. Use SCX_ENQ_IMMED instead. Sitting past
981 	 * SCX_OPI_END means has_op doesn't cover them, so SCX_HAS_OP() cannot
982 	 * be used; callers must test sch->ops.cpu_acquire / cpu_release
983 	 * directly.
984 	 */
985 
986 	/**
987 	 * @cpu_acquire: A CPU is becoming available to the BPF scheduler
988 	 * @cpu: The CPU being acquired by the BPF scheduler.
989 	 * @args: Acquire arguments, see the struct definition.
990 	 *
991 	 * A CPU that was previously released from the BPF scheduler is now once
992 	 * again under its control. Deprecated; use SCX_ENQ_IMMED instead.
993 	 */
994 	void (*cpu_acquire)(s32 cpu, struct scx_cpu_acquire_args *args);
995 
996 	/**
997 	 * @cpu_release: A CPU is taken away from the BPF scheduler
998 	 * @cpu: The CPU being released by the BPF scheduler.
999 	 * @args: Release arguments, see the struct definition.
1000 	 *
1001 	 * The specified CPU is no longer under the control of the BPF
1002 	 * scheduler. This could be because it was preempted by a higher
1003 	 * priority sched_class, though there may be other reasons as well. The
1004 	 * caller should consult @args->reason to determine the cause.
1005 	 * Deprecated; use SCX_ENQ_IMMED instead.
1006 	 */
1007 	void (*cpu_release)(s32 cpu, struct scx_cpu_release_args *args);
1008 };
1009 
1010 /**
1011  * struct sched_ext_ops_cid - cid-form alternative to struct sched_ext_ops
1012  *
1013  * Mirrors struct sched_ext_ops with cpu/cpumask substituted with cid/cmask
1014  * where applicable. Layout up to and including @priv matches sched_ext_ops
1015  * byte-for-byte (verified by BUILD_BUG_ON checks at scx_init() time) so
1016  * shared field offsets work for both struct types in bpf_scx_init_member()
1017  * and bpf_scx_check_member(). The deprecated cpu_acquire/cpu_release
1018  * callbacks at the tail of sched_ext_ops are omitted here entirely.
1019  *
1020  * Differences from sched_ext_ops:
1021  *   - select_cpu       -> select_cid (returns cid)
1022  *   - dispatch         -> dispatch (cpu arg is now cid)
1023  *   - update_idle      -> update_idle (cpu arg is now cid)
1024  *   - set_cpumask      -> set_cmask (cmask instead of cpumask)
1025  *   - cpu_online       -> cid_online
1026  *   - cpu_offline      -> cid_offline
1027  *   - dump_cpu         -> dump_cid
1028  *   - cgroup_*         -> cpuctl_* (they track the cgroup cpu controller)
1029  *   - cpu_acquire/cpu_release  -> not present (deprecated in sched_ext_ops)
1030  *
1031  * BPF schedulers using this type cannot call cpu-form scx_bpf_* kfuncs;
1032  * use the cid-form variants instead. Enforced at BPF verifier time via
1033  * scx_kfunc_context_filter() branching on prog->aux->st_ops.
1034  *
1035  * See sched_ext_ops for callback documentation.
1036  */
1037 struct sched_ext_ops_cid {
1038 	s32 (*select_cid)(struct task_struct *p, s32 prev_cid, u64 wake_flags);
1039 	void (*enqueue)(struct task_struct *p, u64 enq_flags);
1040 	void (*dequeue)(struct task_struct *p, u64 deq_flags);
1041 	void (*dispatch)(s32 cid, struct task_struct *prev);
1042 	void (*tick)(struct task_struct *p);
1043 	void (*runnable)(struct task_struct *p, u64 enq_flags);
1044 	void (*running)(struct task_struct *p);
1045 	void (*stopping)(struct task_struct *p, bool runnable);
1046 	void (*quiescent)(struct task_struct *p, u64 deq_flags);
1047 	bool (*yield)(struct task_struct *from, struct task_struct *to);
1048 	bool (*core_sched_before)(struct task_struct *a,
1049 				   struct task_struct *b);
1050 	void (*set_weight)(struct task_struct *p, u32 weight);
1051 	void (*set_cmask)(struct task_struct *p,
1052 			   const struct scx_cmask *cmask__arena);
1053 	void (*update_idle)(s32 cid, bool idle);
1054 	s32 (*init_task)(struct task_struct *p,
1055 			  struct scx_init_task_args *args);
1056 	void (*exit_task)(struct task_struct *p,
1057 			   struct scx_exit_task_args *args);
1058 	void (*enable)(struct task_struct *p);
1059 	void (*disable)(struct task_struct *p);
1060 	void (*dump)(struct scx_dump_ctx *ctx);
1061 	void (*dump_cid)(struct scx_dump_ctx *ctx, s32 cid, bool idle);
1062 	void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p);
1063 #ifdef CONFIG_EXT_GROUP_SCHED
1064 	s32 (*cpuctl_init)(struct cgroup *cgrp, struct scx_cgroup_init_args *args);
1065 	void (*cpuctl_exit)(struct cgroup *cgrp);
1066 	s32 (*cpuctl_prep_move)(struct task_struct *p, struct cgroup *from,
1067 				struct cgroup *to);
1068 	void (*cpuctl_move)(struct task_struct *p, struct cgroup *from, struct cgroup *to);
1069 	void (*cpuctl_cancel_move)(struct task_struct *p, struct cgroup *from,
1070 				   struct cgroup *to);
1071 	void (*cpuctl_set_weight)(struct cgroup *cgrp, u32 weight);
1072 	void (*cpuctl_set_bandwidth)(struct cgroup *cgrp, u64 period_us, u64 quota_us,
1073 				     u64 burst_us);
1074 	void (*cpuctl_set_idle)(struct cgroup *cgrp, bool idle);
1075 #endif	/* CONFIG_EXT_GROUP_SCHED */
1076 	s32 (*sub_attach)(struct scx_sub_attach_args *args);
1077 	void (*sub_detach)(struct scx_sub_detach_args *args);
1078 	void (*sub_caps_updated)(const struct scx_cmask *cmask__arena, u64 caps);
1079 	void (*sub_ecaps_updated)(s32 cid, u64 before, u64 after);
1080 	void (*cid_online)(s32 cid);
1081 	void (*cid_offline)(s32 cid);
1082 	s32 (*init_cids)(void);
1083 	s32 (*init)(void);
1084 	void (*exit)(struct scx_exit_info *info);
1085 
1086 	/* Data fields - must match sched_ext_ops layout exactly */
1087 	u32 dispatch_max_batch;
1088 	u64 flags;
1089 	u32 timeout_ms;
1090 	u32 exit_dump_len;
1091 	u64 hotplug_seq;
1092 	u32 cid_shard_size;
1093 	u32 rescue_bandwidth_ppt;
1094 	u32 rescue_quantum_us;
1095 	u64 sub_cgroup_id;
1096 	char name[SCX_OPS_NAME_LEN];
1097 
1098 	/* internal use only, must be NULL */
1099 	void __rcu *priv;
1100 
1101 	/* layout end anchor for the BUILD_BUG_ON in scx_init(); keep last */
1102 	char __end[0];
1103 };
1104 
1105 enum scx_opi {
1106 	SCX_OPI_BEGIN			= 0,
1107 	SCX_OPI_NORMAL_BEGIN		= 0,
1108 	SCX_OPI_NORMAL_END		= SCX_OP_IDX(cpu_online),
1109 	SCX_OPI_CPU_HOTPLUG_BEGIN	= SCX_OP_IDX(cpu_online),
1110 	SCX_OPI_CPU_HOTPLUG_END		= SCX_OP_IDX(init_cids),
1111 	SCX_OPI_END			= SCX_OP_IDX(init_cids),
1112 };
1113 
1114 /*
1115  * Collection of event counters. Event types are placed in descending order.
1116  */
1117 struct scx_event_stats {
1118 	/*
1119 	 * If ops.select_cpu() returns a CPU which can't be used by the task,
1120 	 * the core scheduler code silently picks a fallback CPU.
1121 	 */
1122 	s64		SCX_EV_SELECT_CPU_FALLBACK;
1123 
1124 	/*
1125 	 * When dispatching to a local DSQ, the CPU may have gone offline in
1126 	 * the meantime. In this case, the task is bounced to the global DSQ.
1127 	 */
1128 	s64		SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE;
1129 
1130 	/*
1131 	 * If SCX_OPS_ENQ_LAST is not set, the number of times that a task
1132 	 * continued to run because there were no other tasks on the CPU.
1133 	 */
1134 	s64		SCX_EV_DISPATCH_KEEP_LAST;
1135 
1136 	/*
1137 	 * If SCX_OPS_ENQ_EXITING is not set, the number of times that a task
1138 	 * is dispatched to a local DSQ when exiting.
1139 	 */
1140 	s64		SCX_EV_ENQ_SKIP_EXITING;
1141 
1142 	/*
1143 	 * If SCX_OPS_ENQ_MIGRATION_DISABLED is not set, the number of times a
1144 	 * migration disabled task skips ops.enqueue() and is dispatched to its
1145 	 * local DSQ.
1146 	 */
1147 	s64		SCX_EV_ENQ_SKIP_MIGRATION_DISABLED;
1148 
1149 	/*
1150 	 * The number of times a task, enqueued on a local DSQ with
1151 	 * SCX_ENQ_IMMED, was re-enqueued because the CPU was not available for
1152 	 * immediate execution.
1153 	 */
1154 	s64		SCX_EV_REENQ_IMMED;
1155 
1156 	/*
1157 	 * The number of times a reenqueue (%SCX_ENQ_REENQ) led to another
1158 	 * reenqueue without the task running in between. This count climbing
1159 	 * rapidly indicates that the BPF scheduler keeps re-deciding placements
1160 	 * it can't honor. A single task reenqueued more than
1161 	 * %SCX_REENQ_MAX_REPEAT times gets its owning scheduler ejected.
1162 	 */
1163 	s64		SCX_EV_REENQ_REPEAT;
1164 
1165 	/*
1166 	 * Total number of times a task's time slice was refilled with the
1167 	 * default value (SCX_SLICE_DFL).
1168 	 */
1169 	s64		SCX_EV_REFILL_SLICE_DFL;
1170 
1171 	/*
1172 	 * The number of times an out-of-band slice request exceeded the maximum
1173 	 * representable value and was clamped.
1174 	 */
1175 	s64		SCX_EV_SLICE_CLAMPED;
1176 
1177 	/*
1178 	 * The number of times a slice extension was denied because the
1179 	 * scheduler lacked baseline cpu access on the task's cpu.
1180 	 */
1181 	s64		SCX_EV_SLICE_DENIED;
1182 
1183 	/*
1184 	 * The total duration of bypass modes in nanoseconds.
1185 	 */
1186 	s64		SCX_EV_BYPASS_DURATION;
1187 
1188 	/*
1189 	 * The number of tasks dispatched in the bypassing mode.
1190 	 */
1191 	s64		SCX_EV_BYPASS_DISPATCH;
1192 
1193 	/*
1194 	 * The number of times the bypassing mode has been activated.
1195 	 */
1196 	s64		SCX_EV_BYPASS_ACTIVATE;
1197 
1198 	/*
1199 	 * The number of times the scheduler attempted to insert a task that it
1200 	 * doesn't own into a DSQ. Such attempts are ignored.
1201 	 *
1202 	 * As BPF schedulers are allowed to ignore dequeues, it's difficult to
1203 	 * tell whether such an attempt is from a scheduler malfunction or an
1204 	 * ignored dequeue around sub-sched enabling. If this count keeps going
1205 	 * up regardless of sub-sched enabling, it likely indicates a bug in the
1206 	 * scheduler.
1207 	 */
1208 	s64		SCX_EV_INSERT_NOT_OWNED;
1209 
1210 	/*
1211 	 * The number of times tasks from bypassing descendants are scheduled
1212 	 * from sub_bypass_dsq's.
1213 	 */
1214 	s64		SCX_EV_SUB_BYPASS_DISPATCH;
1215 
1216 	/*
1217 	 * The number of times a migration-disabled task lacking the cap for its
1218 	 * cid was allowed onto the local DSQ. It must run on its pinned CPU, so
1219 	 * it can't be rejected. The violation is counted here.
1220 	 */
1221 	s64		SCX_EV_SUB_FORCED_ADMIT;
1222 
1223 	/*
1224 	 * The number of times a preempting kick was refused because the
1225 	 * sub-sched lacked SCX_CAP_PREEMPT for a task outside its subtree. The
1226 	 * kick degrades to a plain reschedule.
1227 	 */
1228 	s64		SCX_EV_SUB_PREEMPT_DENIED;
1229 
1230 	/*
1231 	 * The number of times a kick was skipped because the sub-sched lacked
1232 	 * baseline access on the target cid. The preempt-part degradation of a
1233 	 * delivered kick is counted in SCX_EV_SUB_PREEMPT_DENIED instead.
1234 	 */
1235 	s64		SCX_EV_SUB_KICK_DENIED;
1236 
1237 	/*
1238 	 * The number of times a local DSQ reenq was dropped because the
1239 	 * sub-sched lacked baseline access on the target cid.
1240 	 */
1241 	s64		SCX_EV_SUB_REENQ_DENIED;
1242 
1243 	/*
1244 	 * The number of times scx_bpf_cidperf_set() was denied because the
1245 	 * sub-sched lacked SCX_CAP_PERF on the target cid.
1246 	 */
1247 	s64		SCX_EV_SUB_CIDPERF_DENIED;
1248 
1249 	/*
1250 	 * The number of times an insert carrying %SCX_ENQ_RESCUE lacked the
1251 	 * caps for its cid and the task entered the rescue path.
1252 	 */
1253 	s64		SCX_EV_SUB_RESCUE;
1254 };
1255 
1256 #define SCX_EVENTS_LIST(SCX_EVENT)					\
1257 	SCX_EVENT(SCX_EV_SELECT_CPU_FALLBACK);				\
1258 	SCX_EVENT(SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);			\
1259 	SCX_EVENT(SCX_EV_DISPATCH_KEEP_LAST);				\
1260 	SCX_EVENT(SCX_EV_ENQ_SKIP_EXITING);				\
1261 	SCX_EVENT(SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);			\
1262 	SCX_EVENT(SCX_EV_REENQ_IMMED);					\
1263 	SCX_EVENT(SCX_EV_REENQ_REPEAT);					\
1264 	SCX_EVENT(SCX_EV_REFILL_SLICE_DFL);				\
1265 	SCX_EVENT(SCX_EV_SLICE_CLAMPED);				\
1266 	SCX_EVENT(SCX_EV_SLICE_DENIED);					\
1267 	SCX_EVENT(SCX_EV_BYPASS_DURATION);				\
1268 	SCX_EVENT(SCX_EV_BYPASS_DISPATCH);				\
1269 	SCX_EVENT(SCX_EV_BYPASS_ACTIVATE);				\
1270 	SCX_EVENT(SCX_EV_INSERT_NOT_OWNED);				\
1271 	SCX_EVENT(SCX_EV_SUB_BYPASS_DISPATCH);				\
1272 	SCX_EVENT(SCX_EV_SUB_FORCED_ADMIT);				\
1273 	SCX_EVENT(SCX_EV_SUB_PREEMPT_DENIED);				\
1274 	SCX_EVENT(SCX_EV_SUB_KICK_DENIED);				\
1275 	SCX_EVENT(SCX_EV_SUB_REENQ_DENIED);				\
1276 	SCX_EVENT(SCX_EV_SUB_CIDPERF_DENIED);				\
1277 	SCX_EVENT(SCX_EV_SUB_RESCUE)
1278 
1279 struct scx_sched;
1280 
1281 enum scx_sched_pcpu_flags {
1282 	SCX_SCHED_PCPU_BYPASSING	= 1LLU << 0,
1283 };
1284 
1285 /* dispatch buf */
1286 struct scx_dsp_buf_ent {
1287 	struct task_struct	*task;
1288 	unsigned long		qseq;
1289 	u64			dsq_id;
1290 	u64			slice;
1291 	u64			vtime;
1292 	u64			enq_flags;
1293 };
1294 
1295 struct scx_dsp_ctx {
1296 	struct rq		*rq;
1297 	u32			cursor;
1298 	u32			nr_tasks;
1299 	struct scx_dsp_buf_ent	buf[];
1300 };
1301 
1302 struct scx_deferred_reenq_local {
1303 	struct list_head	node;
1304 	u64			flags;
1305 };
1306 
1307 struct scx_sched_pcpu {
1308 	struct scx_sched	*sch;
1309 	u64			flags;	/* protected by rq lock */
1310 
1311 	/*
1312 	 * Kick state owned by this cpu for this sched. scx_kick_cpu() records
1313 	 * targets here and links @to_kick_node onto the cpu's
1314 	 * rq->scx.sched_pcpus_to_kick. The cpu's single kick irq_work walks
1315 	 * that list and kicks each sched's targets on its behalf. Per-sched so
1316 	 * a kick stays attributed to its scheduler.
1317 	 */
1318 	cpumask_var_t		cpus_to_kick;
1319 	cpumask_var_t		cpus_to_kick_if_idle;
1320 	cpumask_var_t		cpus_to_preempt;
1321 	cpumask_var_t		cpus_to_wait;
1322 	struct list_head	to_kick_node;
1323 
1324 #ifdef CONFIG_EXT_SUB_SCHED
1325 	/*
1326 	 * pshard->caps[cap_bit] is the set of cids the sched holds that one
1327 	 * cap on. ecaps is its transpose: the set of SCX_CAP_* bits the sched
1328 	 * effectively holds on this cpu, with implied caps folded in, so that
1329 	 * the hot-path check is a single read.
1330 	 *
1331 	 * While pshard->caps[] under pshard->lock is the target configuration,
1332 	 * ecaps is the effective copy owned by the cpu. It is written under the
1333 	 * rq lock while processing rq->ecaps_to_sync. Can also be read with
1334 	 * READ_ONCE() outside rq lock.
1335 	 *
1336 	 * See queue_sync_ecaps() and scx_process_sync_ecaps().
1337 	 */
1338 	u64			ecaps;
1339 	struct llist_node	ecaps_to_sync_node;
1340 	/* owed a forced update_idle() re-notify on this cpu */
1341 	bool			idle_renotify;
1342 	/* effective caps as of the last sub_ecaps_updated() delivery */
1343 	u64			reported_ecaps;
1344 
1345 	/*
1346 	 * Decaying rescue runtime consumed on this cpu, see
1347 	 * scx_rescue_decay_avg(). Overload on this cpu ejects the sub with the
1348 	 * largest value. Accessed only under this cpu's rq lock.
1349 	 */
1350 	u64			rescue_avg;
1351 	u64			rescue_avg_at;	/* last decay, jiffies_64 */
1352 #endif
1353 
1354 	/*
1355 	 * The event counters are in a per-CPU variable to minimize the
1356 	 * accounting overhead. A system-wide view on the event counter is
1357 	 * constructed when requested by scx_bpf_events().
1358 	 */
1359 	struct scx_event_stats	event_stats;
1360 
1361 	struct scx_deferred_reenq_local deferred_reenq_local;
1362 	struct scx_dispatch_q	bypass_dsq;
1363 #ifdef CONFIG_EXT_SUB_SCHED
1364 	u32			bypass_host_seq;
1365 #endif
1366 
1367 	/* must be the last entry - contains flex array */
1368 	struct scx_dsp_ctx	dsp_ctx;
1369 };
1370 
1371 struct scx_sched_pnode {
1372 	struct scx_dispatch_q	global_dsq;
1373 };
1374 
1375 /*
1376  * Sub-sched capability delegation.
1377  *
1378  * Caps are per-cid permissions parents delegate to direct children via
1379  * scx_bpf_sub_grant() / scx_bpf_sub_revoke(). A child's cap set is always a
1380  * subset of its parent's. A sub-sched checks its caps locally, and cross-sched
1381  * communication is needed only when the delegation set itself changes.
1382  *
1383  * Caps are used to implement sub-sched scheduling on the enqueue path. Picking
1384  * a cid for a task at a leaf depends on which cids the leaf is allowed to use.
1385  * Resolving that programmatically on every enqueue would mean a cross-sched
1386  * round-trip call chain, possibly retrying if the request can't be granted
1387  * as-is.
1388  *
1389  * The dispatch path is different - it runs as top-down recursion via
1390  * scx_bpf_sub_dispatch(): a sched's dispatch op invokes a child's dispatch op
1391  * on the local rq, and the subtree dispatches in a single pass.
1392  *
1393  * Locking is per shard. cid space is split into shards, and each sub-sched has
1394  * its own pshard->lock for each shard. Operations are broken up on shard
1395  * boundaries. Different shards never contend. Shards are expected to be
1396  * topology-aligned and likely to serve as the locality unit when cids are
1397  * allocated to schedulers, so per-shard lock granularity scales naturally with
1398  * the allocation pattern.
1399  *
1400  * ENQ_IMMED  insert an IMMED task onto the cid's local DSQ
1401  *            - kick the cid's cpu (except SCX_KICK_PREEMPT)
1402  *
1403  * ENQ        insert any task onto the cid's local DSQ (implies ENQ_IMMED)
1404  *
1405  * PREEMPT    preempt any task running on the cid regardless of the owning
1406  *            sched (implies ENQ). Preempting a task in the sched's own subtree
1407  *            doesn't require any cap.
1408  *            - SCX_ENQ_PREEMPT inserts
1409  *            - SCX_KICK_PREEMPT kicks
1410  *
1411  * PERF       control the cid's cpu power/perf management state, currently the
1412  *            cpufreq target set through scx_bpf_cidperf_set(). Hardware
1413  *            control is a separate axis from queue access: PERF neither
1414  *            implies nor is implied by the caps above.
1415  *
1416  * Implied caps apply to the holder's own use of a cid, not to delegation.
1417  * scx_bpf_sub_grant() delegates literally-held caps, so a cap held only through
1418  * implication is usable but cannot be re-delegated to a child. When granting a
1419  * cap, it usually makes sense to delegate its implied caps explicitly alongside
1420  * it.
1421  */
1422 enum scx_cap_flags {
1423 	__SCX_CAP_ENQ_IMMED		= 0,
1424 	__SCX_CAP_ENQ			= 1,
1425 	__SCX_CAP_PREEMPT		= 2,
1426 	__SCX_CAP_PERF			= 3,
1427 
1428 	__SCX_NR_CAPS,
1429 	__SCX_CAP_ALL			= BIT_U64(__SCX_NR_CAPS) - 1,
1430 
1431 	SCX_CAP_ENQ_IMMED		= BIT_U64(__SCX_CAP_ENQ_IMMED),
1432 	SCX_CAP_ENQ			= BIT_U64(__SCX_CAP_ENQ),
1433 	SCX_CAP_PREEMPT			= BIT_U64(__SCX_CAP_PREEMPT),
1434 	SCX_CAP_PERF			= BIT_U64(__SCX_CAP_PERF),
1435 
1436 	/* alias for minimal cap to make any use of a cpu */
1437 	SCX_CAP_BASE			= SCX_CAP_ENQ_IMMED,
1438 
1439 	/* caps whose loss strands queued tasks, see scx_process_sync_ecaps() */
1440 	SCX_CAPS_REENQ_ON_LOSS		= SCX_CAP_ENQ_IMMED | SCX_CAP_ENQ,
1441 };
1442 
1443 #ifdef CONFIG_EXT_SUB_SCHED
1444 /* iterate set bits in a u64 cap mask */
1445 #define scx_for_each_cap_bit(cap_bit, caps)				\
1446 	for (u64 __caps = (caps);					\
1447 	     __caps && ((cap_bit) = __ffs64(__caps), true);		\
1448 	     __caps &= __caps - 1)
1449 
1450 /*
1451  * Sub-cap update notifier.
1452  *
1453  * ops_cid.sub_caps_updated() notifies sub-scheds when their cap state changes
1454  * so they can refresh internal state without polling scx_bpf_sub_caps() per
1455  * enqueue.
1456  *
1457  * Three constraints shape the design:
1458  *
1459  *   1. Static memory. Deliveries use a fixed-size buffer, both for runtime
1460  *      efficiency and so notifications can't be lost under memory pressure.
1461  *
1462  *   2. High-frequency updates. Grant/revoke can mutate caps in bursts, and the
1463  *      notifier path must absorb that without amplifying it.
1464  *
1465  *   3. Recursive grant/revoke from the callback. A child receiving a
1466  *      notification can call grant/revoke on its own children, which can
1467  *      cascade recursively down its subtree.
1468  *
1469  * (1) and (2) lead to coalescing into a fixed payload. Each delivery carries a
1470  * single (cmask, caps) pair covering every change since the previous one.
1471  * Direction (set vs cleared) isn't encoded as it doesn't fit in the fixed-size
1472  * summary. The callback queries scx_bpf_sub_caps() for current state. Only one
1473  * delivery is in flight per shard. Further changes fold into the same buffer
1474  * and ship as the next callback, so a shard's callbacks fire in order.
1475  *
1476  * (3) leads to deferred delivery. Events accumulate during grant/revoke and are
1477  * delivered after the shard lock is released.
1478  */
1479 struct scx_caps_updated {
1480 	raw_spinlock_t		lock;
1481 	u64			caps;
1482 	struct scx_cmask	*cmask_arena_out;
1483 	struct list_head	node_in_flight;
1484 	/* Kernel-side accumulator. Access as &cu->cmask. */
1485 	TRAILING_OVERLAP(struct scx_cmask, cmask, bits,
1486 			 u64 _bits[SCX_CMASK_NR_WORDS(SCX_CID_SHARD_MAX_CPUS)];
1487 	);
1488 };
1489 
1490 struct scx_pshard {
1491 	raw_spinlock_t		lock;		/* serializes caps */
1492 	struct scx_sched	*sch;		/* backpointer */
1493 	struct scx_caps_updated	caps_updated;
1494 
1495 	/*
1496 	 * Per-cap cmask, inline via TRAILING_OVERLAP so cmask.bits[] overlaps
1497 	 * the trailing _bits[] storage. Access as &caps[i].cmask. See
1498 	 * scx_sched_pcpu->ecaps.
1499 	 */
1500 	TRAILING_OVERLAP(struct scx_cmask, cmask, bits,
1501 			 u64 _bits[SCX_CMASK_NR_WORDS(SCX_CID_SHARD_MAX_CPUS)];
1502 	) caps[__SCX_NR_CAPS];
1503 
1504 	/*
1505 	 * Shard geometry captured at alloc. cmask_arena_out's own header is
1506 	 * bpf-writable and the live shard range can change before the
1507 	 * rcu-deferred free, so re-init and size cmask_arena_out from these
1508 	 * trusted copies instead.
1509 	 */
1510 	u32			base;
1511 	u32			nr_cids;
1512 };
1513 #endif
1514 
1515 struct scx_sched {
1516 	/*
1517 	 * cpu-form and cid-form ops share field offsets up to .priv (verified
1518 	 * by BUILD_BUG_ON in scx_init()). The anonymous union lets the kernel
1519 	 * access either view of the same storage without function-pointer
1520 	 * casts: use .ops for cpu-form and shared fields, .ops_cid for the
1521 	 * cid-renamed callbacks (set_cmask, select_cid, cid_online, ...).
1522 	 */
1523 	union {
1524 		struct sched_ext_ops		ops;
1525 		struct sched_ext_ops_cid	ops_cid;
1526 	};
1527 	bool			is_cid_type;	/* true if registered via bpf_sched_ext_ops_cid */
1528 	bool			dead;		/* set after ops.exit(), gates scx_prog_sched() */
1529 
1530 	/*
1531 	 * Arena map auto-discovered from member progs at struct_ops attach.
1532 	 * cid-form schedulers must use exactly one arena across all member
1533 	 * progs. NULL on cpu-form.
1534 	 *
1535 	 * @arena_pool sub-allocates @arena_map. Each gen_pool chunk is added
1536 	 * at the kernel-side mapping address. @arena_kern_base is the start
1537 	 * of the arena's kern_vm range. See scx_arena_to_kaddr().
1538 	 */
1539 	struct bpf_map		*arena_map;
1540 	struct gen_pool		*arena_pool;
1541 	uintptr_t		arena_kern_base;
1542 
1543 	/*
1544 	 * Per-CPU arena cmask used by scx_call_op_set_cpumask() to hand a cmask
1545 	 * to ops_cid.set_cmask(). The kernel writes through the stored kern_va
1546 	 * and passes it to the callback's __arena argument.
1547 	 */
1548 	struct scx_cmask * __percpu *set_cmask_scratch;
1549 
1550 	DECLARE_BITMAP(has_op, SCX_OPI_END);
1551 
1552 	/*
1553 	 * Dispatch queues.
1554 	 *
1555 	 * The global DSQ (%SCX_DSQ_GLOBAL) is split per-node for scalability.
1556 	 * This is to avoid live-locking in bypass mode where all tasks are
1557 	 * dispatched to %SCX_DSQ_GLOBAL and all CPUs consume from it. If
1558 	 * per-node split isn't sufficient, it can be further split.
1559 	 */
1560 	struct rhashtable	dsq_hash;
1561 	struct scx_sched_pnode	**pnode;
1562 #ifdef CONFIG_EXT_SUB_SCHED
1563 	struct scx_pshard	**pshard;	/* indexed by shard_idx */
1564 #endif
1565 	struct scx_sched_pcpu __percpu *pcpu;
1566 
1567 	u64			slice_dfl;
1568 	u64			bypass_timestamp;
1569 	s32			bypass_depth;
1570 
1571 	/* bypass dispatch path enable state, see scx_bypass_dsp_enabled() */
1572 	unsigned long		bypass_dsp_claim;
1573 	atomic_t		bypass_dsp_enable_depth;
1574 
1575 	bool			aborting;
1576 	bool			dump_disabled;	/* protected by scx_dump_lock */
1577 	u32			dsp_max_batch;
1578 	s32			level;
1579 
1580 #ifdef CONFIG_EXT_SUB_SCHED
1581 	/*
1582 	 * pshard[] size captured at enable for the async RCU free path -
1583 	 * scx_nr_cid_shards may be rewritten by a later enable's
1584 	 * scx_cid_publish_tables() before free runs. While sch is active, use
1585 	 * the global.
1586 	 */
1587 	u32			nr_pshards;
1588 #endif
1589 
1590 	/*
1591 	 * Updates to the following warned bitfields can race causing RMW issues
1592 	 * but it doesn't really matter.
1593 	 */
1594 	bool			warned_zero_slice:1;
1595 	bool			warned_unassoc_progs:1;
1596 
1597 	struct list_head	all;
1598 
1599 	/* unique instance id, monotonic and never reused */
1600 	u64			id;
1601 
1602 #ifdef CONFIG_EXT_SUB_SCHED
1603 	struct rhash_head	hash_node;
1604 
1605 	struct list_head	children;
1606 	struct list_head	sibling;
1607 	struct cgroup		*cgrp;
1608 	char			*cgrp_path;
1609 	struct kset		*sub_kset;
1610 
1611 	bool			linked;		/* on ->children, see scx_link_sched() */
1612 	bool			sub_attached;
1613 #endif	/* CONFIG_EXT_SUB_SCHED */
1614 
1615 	/*
1616 	 * The maximum amount of time in jiffies that a task may be runnable
1617 	 * without being scheduled on a CPU. If this timeout is exceeded, it
1618 	 * will trigger scx_error().
1619 	 */
1620 	unsigned long		watchdog_timeout;
1621 
1622 	atomic_t		exit_kind;
1623 	struct scx_exit_info	*exit_info;
1624 
1625 	struct kobject		kobj;
1626 
1627 	struct kthread_worker	*helper;
1628 	struct irq_work		disable_irq_work;
1629 	struct kthread_work	disable_work;
1630 	struct irq_work		propagate_exit_irq_work; /* see scx_claim_exit() */
1631 	struct timer_list	bypass_lb_timer;
1632 	cpumask_var_t		bypass_lb_donee_cpumask;
1633 	cpumask_var_t		bypass_lb_resched_cpumask;
1634 	cpumask_var_t		stall_cpus;
1635 	struct rcu_work		rcu_work;
1636 
1637 	/* all ancestors including self */
1638 	struct scx_sched	*ancestors[];
1639 };
1640 
1641 /**
1642  * scx_arena_to_kaddr - Translate a BPF-arena pointer to its kernel address
1643  * @sch: scheduler whose arena hosts @bpf_ptr
1644  * @bpf_ptr: BPF-arena pointer, only the low 32 bits are used
1645  *
1646  * The (u32) cast normalizes any input into the arena's 4 GiB kern_vm range,
1647  * which combined with scratch-page fault recovery makes the returned pointer
1648  * safe to dereference up to GUARD_SZ / 2 past the intended object. Accesses
1649  * larger than GUARD_SZ / 2 must be explicitly bounds-checked.
1650  */
1651 static inline void *scx_arena_to_kaddr(struct scx_sched *sch, const void *bpf_ptr)
1652 {
1653 	return (void *)(sch->arena_kern_base + (u32)(uintptr_t)bpf_ptr);
1654 }
1655 
1656 enum scx_wake_flags {
1657 	/* expose select WF_* flags as enums */
1658 	SCX_WAKE_FORK		= WF_FORK,
1659 	SCX_WAKE_TTWU		= WF_TTWU,
1660 	SCX_WAKE_SYNC		= WF_SYNC,
1661 };
1662 
1663 enum scx_enq_flags {
1664 	/* expose select ENQUEUE_* flags as enums */
1665 	SCX_ENQ_WAKEUP		= ENQUEUE_WAKEUP,
1666 	SCX_ENQ_HEAD		= ENQUEUE_HEAD,
1667 	SCX_ENQ_CPU_SELECTED	= ENQUEUE_RQ_SELECTED,
1668 
1669 	/* high 32bits are SCX specific */
1670 
1671 	/*
1672 	 * Set the following to trigger preemption when calling
1673 	 * scx_bpf_dsq_insert() with a local dsq as the target. The slice of the
1674 	 * current task is cleared to zero and the CPU is kicked into the
1675 	 * scheduling path. Implies %SCX_ENQ_HEAD.
1676 	 */
1677 	SCX_ENQ_PREEMPT		= 1LLU << 32,
1678 
1679 	/*
1680 	 * Only allowed on local DSQs. Guarantees that the task either gets
1681 	 * on the CPU immediately and stays on it, or gets reenqueued back
1682 	 * to the BPF scheduler. It will never linger on a local DSQ or be
1683 	 * silently put back after preemption.
1684 	 *
1685 	 * The protection persists until the next fresh enqueue - it
1686 	 * survives SAVE/RESTORE cycles, slice extensions and preemption.
1687 	 * If the task can't stay on the CPU for any reason, it gets
1688 	 * reenqueued back to the BPF scheduler.
1689 	 *
1690 	 * Exiting and migration-disabled tasks bypass ops.enqueue() and
1691 	 * are placed directly on a local DSQ without IMMED protection
1692 	 * unless %SCX_OPS_ENQ_EXITING and %SCX_OPS_ENQ_MIGRATION_DISABLED
1693 	 * are set respectively.
1694 	 */
1695 	SCX_ENQ_IMMED		= 1LLU << 33,
1696 
1697 	/*
1698 	 * Only allowed on local DSQs. If the insert lacks the caps for the
1699 	 * target cid, divert the task to the CPU's rescue path instead of
1700 	 * rejecting and reenqueueing, e.g. when the task's affinity is
1701 	 * restricted to cids the scheduler doesn't hold. The kernel runs
1702 	 * rescued tasks on the target CPU. Rescue execution is guaranteed to
1703 	 * make forward progress and is bandwidth-limited, see the
1704 	 * rescue_bandwidth_ppt and rescue_quantum_us ops fields.
1705 	 */
1706 	SCX_ENQ_RESCUE		= 1LLU << 34,
1707 
1708 	/*
1709 	 * The task being enqueued was previously enqueued on a DSQ, but was
1710 	 * removed and is being re-enqueued. See SCX_TASK_REENQ_* flags to find
1711 	 * out why a given task is being reenqueued.
1712 	 */
1713 	SCX_ENQ_REENQ		= 1LLU << 40,
1714 
1715 	/*
1716 	 * The task being enqueued is the only task available for the cpu. By
1717 	 * default, ext core keeps executing such tasks but when
1718 	 * %SCX_OPS_ENQ_LAST is specified, they're ops.enqueue()'d with the
1719 	 * %SCX_ENQ_LAST flag set.
1720 	 *
1721 	 * The BPF scheduler is responsible for triggering a follow-up
1722 	 * scheduling event. Otherwise, Execution may stall.
1723 	 */
1724 	SCX_ENQ_LAST		= 1LLU << 41,
1725 
1726 	/* high 8 bits are internal */
1727 	__SCX_ENQ_INTERNAL_MASK	= 0xffLLU << 56,
1728 
1729 	SCX_ENQ_CLEAR_OPSS	= 1LLU << 56,
1730 	SCX_ENQ_DSQ_PRIQ	= 1LLU << 57,
1731 	SCX_ENQ_NESTED		= 1LLU << 58,
1732 	SCX_ENQ_GDSQ_FALLBACK	= 1LLU << 59,	/* fell back to global DSQ */
1733 	SCX_ENQ_IGNORE_CAPS	= 1LLU << 60,	/* admit to local DSQ ignoring caps */
1734 	SCX_ENQ_APPLY_SLICE	= 1LLU << 61,	/* apply carried slice/vtime at insertion */
1735 	SCX_ENQ_SLICE_DFL	= 1LLU << 62,	/* carried slice is a default refill */
1736 };
1737 
1738 enum scx_deq_flags {
1739 	/* expose select DEQUEUE_* flags as enums */
1740 	SCX_DEQ_SLEEP		= DEQUEUE_SLEEP,
1741 
1742 	/* high 32bits are SCX specific */
1743 
1744 	/*
1745 	 * The generic core-sched layer decided to execute the task even though
1746 	 * it hasn't been dispatched yet. Dequeue from the BPF side.
1747 	 */
1748 	SCX_DEQ_CORE_SCHED_EXEC	= 1LLU << 32,
1749 
1750 	/*
1751 	 * The task is being dequeued due to a property change (e.g.,
1752 	 * sched_setaffinity(), sched_setscheduler(), set_user_nice(),
1753 	 * etc.).
1754 	 */
1755 	SCX_DEQ_SCHED_CHANGE	= 1LLU << 33,
1756 };
1757 
1758 enum scx_reenq_flags {
1759 	/* low 16bits determine which tasks should be reenqueued */
1760 	SCX_REENQ_ANY		= 1LLU << 0,	/* all tasks */
1761 
1762 	/* internal: kernel-issued on cap revoke, not accepted from BPF */
1763 	SCX_REENQ_CAP_REVOKE	= 1LLU << 1,
1764 
1765 	__SCX_REENQ_FILTER_MASK	= 0xffffLLU,
1766 
1767 	__SCX_REENQ_USER_MASK	= SCX_REENQ_ANY,
1768 
1769 	/* bits 32-35 used by task_should_reenq() */
1770 	SCX_REENQ_TSR_RQ_OPEN	= 1LLU << 32,
1771 	SCX_REENQ_TSR_NOT_FIRST	= 1LLU << 33,
1772 
1773 	__SCX_REENQ_TSR_MASK	= 0xfLLU << 32,
1774 };
1775 
1776 enum scx_pick_idle_cpu_flags {
1777 	SCX_PICK_IDLE_CORE	= 1LLU << 0,	/* pick a CPU whose SMT siblings are also idle */
1778 	SCX_PICK_IDLE_IN_NODE	= 1LLU << 1,	/* pick a CPU in the same target NUMA node */
1779 };
1780 
1781 enum scx_kick_flags {
1782 	/*
1783 	 * Kick the target CPU if idle. Guarantees that the target CPU goes
1784 	 * through at least one full scheduling cycle before going idle. If the
1785 	 * target CPU can be determined to be currently not idle and going to go
1786 	 * through a scheduling cycle before going idle, noop.
1787 	 */
1788 	SCX_KICK_IDLE		= 1LLU << 0,
1789 
1790 	/*
1791 	 * Preempt the current task and execute the dispatch path. If the
1792 	 * current task of the target CPU is an SCX task, its ->scx.slice is
1793 	 * cleared to zero before the scheduling path is invoked so that the
1794 	 * task expires and the dispatch path is invoked.
1795 	 */
1796 	SCX_KICK_PREEMPT	= 1LLU << 1,
1797 
1798 	/*
1799 	 * The scx_bpf_kick_cpu() call will return after the current SCX task of
1800 	 * the target CPU switches out. This can be used to implement e.g. core
1801 	 * scheduling. This has no effect if the current task on the target CPU
1802 	 * is not on SCX.
1803 	 */
1804 	SCX_KICK_WAIT		= 1LLU << 2,
1805 };
1806 
1807 enum scx_tg_flags {
1808 	SCX_TG_ONLINE		= 1U << 0,
1809 	SCX_TG_INITED		= 1U << 1,
1810 	SCX_TG_SUB_INIT		= 1U << 2,	/* see scx_cgroup_claim_subtree() */
1811 };
1812 
1813 enum scx_enable_state {
1814 	SCX_ENABLING,
1815 	SCX_ENABLED,
1816 	SCX_DISABLING,
1817 	SCX_DISABLED,
1818 };
1819 
1820 static const char *scx_enable_state_str[] = {
1821 	[SCX_ENABLING]		= "enabling",
1822 	[SCX_ENABLED]		= "enabled",
1823 	[SCX_DISABLING]		= "disabling",
1824 	[SCX_DISABLED]		= "disabled",
1825 };
1826 
1827 /*
1828  * Task Ownership State Machine (sched_ext_entity->ops_state)
1829  *
1830  * The sched_ext core uses this state machine to track task ownership
1831  * between the SCX core and the BPF scheduler. This allows the BPF
1832  * scheduler to dispatch tasks without strict ordering requirements, while
1833  * the SCX core safely rejects invalid dispatches.
1834  *
1835  * State Transitions
1836  *
1837  *       .------------> NONE (owned by SCX core)
1838  *       |               |           ^
1839  *       |       enqueue |           | direct dispatch
1840  *       |               v           |
1841  *       |           QUEUEING -------'
1842  *       |               |
1843  *       |       enqueue |
1844  *       |     completes |
1845  *       |               v
1846  *       |            QUEUED (owned by BPF scheduler)
1847  *       |               |
1848  *       |      dispatch |
1849  *       |               |
1850  *       |               v
1851  *       |          DISPATCHING
1852  *       |               |
1853  *       |      dispatch |
1854  *       |     completes |
1855  *       `---------------'
1856  *
1857  * State Descriptions
1858  *
1859  * - %SCX_OPSS_NONE:
1860  *     Task is owned by the SCX core. It's either on a run queue, running,
1861  *     or being manipulated by the core scheduler. The BPF scheduler has no
1862  *     claim on this task.
1863  *
1864  * - %SCX_OPSS_QUEUEING:
1865  *     Transitional state while transferring a task from the SCX core to
1866  *     the BPF scheduler. The task's rq lock is held during this state.
1867  *     Since QUEUEING is both entered and exited under the rq lock, dequeue
1868  *     can never observe this state (it would be a BUG). When finishing a
1869  *     dispatch, if the task is still in %SCX_OPSS_QUEUEING the completion
1870  *     path busy-waits for it to leave this state (via wait_ops_state())
1871  *     before retrying.
1872  *
1873  * - %SCX_OPSS_QUEUED:
1874  *     Task is owned by the BPF scheduler. It's on a DSQ (dispatch queue)
1875  *     and the BPF scheduler is responsible for dispatching it. A QSEQ
1876  *     (queue sequence number) is embedded in this state to detect
1877  *     dispatch/dequeue races: if a task is dequeued and re-enqueued, the
1878  *     QSEQ changes and any in-flight dispatch operations targeting the old
1879  *     QSEQ are safely ignored.
1880  *
1881  * - %SCX_OPSS_DISPATCHING:
1882  *     Transitional state while transferring a task from the BPF scheduler
1883  *     back to the SCX core. This state indicates the BPF scheduler has
1884  *     selected the task for execution. When dequeue needs to take the task
1885  *     off a DSQ and it is still in %SCX_OPSS_DISPATCHING, the dequeue path
1886  *     busy-waits for it to leave this state (via wait_ops_state()) before
1887  *     proceeding. Exits to %SCX_OPSS_NONE when dispatch completes.
1888  *
1889  * Memory Ordering
1890  *
1891  * Transitions out of %SCX_OPSS_QUEUEING and %SCX_OPSS_DISPATCHING into
1892  * %SCX_OPSS_NONE or %SCX_OPSS_QUEUED must use atomic_long_set_release()
1893  * and waiters must use atomic_long_read_acquire(). This ensures proper
1894  * synchronization between concurrent operations.
1895  *
1896  * Cross-CPU Task Migration
1897  *
1898  * When moving a task in the %SCX_OPSS_DISPATCHING state, we can't simply
1899  * grab the target CPU's rq lock because a concurrent dequeue might be
1900  * waiting on %SCX_OPSS_DISPATCHING while holding the source rq lock
1901  * (deadlock).
1902  *
1903  * The sched_ext core uses a "lock dancing" protocol coordinated by
1904  * p->scx.holding_cpu. When moving a task to a different rq:
1905  *
1906  *   1. Set p->scx.holding_cpu to the current CPU
1907  *   2. Set task state to %SCX_OPSS_NONE; dequeue waits while DISPATCHING
1908  *      is set, so clearing DISPATCHING first prevents the circular wait
1909  *      (safe to lock the rq we need)
1910  *   3. Unlock the current CPU's rq
1911  *   4. Lock src_rq (where the task currently lives)
1912  *   5. Verify p->scx.holding_cpu == current CPU, if not, dequeue won the
1913  *      race (dequeue clears holding_cpu to -1 when it takes the task), in
1914  *      this case migration is aborted
1915  *   6. If src_rq == dst_rq: clear holding_cpu and enqueue directly
1916  *      into dst_rq's local DSQ (no lock swap needed)
1917  *   7. Otherwise, verify under src_rq lock that the task can be moved to dst_rq
1918  *      (CPU affinity, migration_disabled, etc.). If not, clear holding_cpu,
1919  *      leave the task on src_rq, and enqueue it on the fallback DSQ.
1920  *   8. Otherwise (i.e. if the task can be moved to dst_rq), call
1921  *      move_remote_task_to_local_dsq(), which releases src_rq, locks dst_rq,
1922  *      and performs the deactivate/activate migration cycle
1923  *      (dst_rq is held on return)
1924  *   9. Unlock dst_rq and re-lock the current CPU's rq to restore
1925  *      the lock state expected by the caller
1926  *
1927  * If any verification fails, abort the migration.
1928  *
1929  * This state tracking allows the BPF scheduler to try to dispatch any task
1930  * at any time regardless of its state. The SCX core can safely
1931  * reject/ignore invalid dispatches, simplifying the BPF scheduler
1932  * implementation.
1933  */
1934 enum scx_ops_state {
1935 	SCX_OPSS_NONE,		/* owned by the SCX core */
1936 	SCX_OPSS_QUEUEING,	/* in transit to the BPF scheduler */
1937 	SCX_OPSS_QUEUED,	/* owned by the BPF scheduler */
1938 	SCX_OPSS_DISPATCHING,	/* in transit back to the SCX core */
1939 
1940 	/*
1941 	 * QSEQ brands each QUEUED instance so that, when dispatch races
1942 	 * dequeue/requeue, the dispatcher can tell whether it still has a claim
1943 	 * on the task being dispatched.
1944 	 *
1945 	 * As some 32bit archs can't do 64bit store_release/load_acquire,
1946 	 * p->scx.ops_state is atomic_long_t which leaves 30 bits for QSEQ on
1947 	 * 32bit machines. The dispatch race window QSEQ protects is very narrow
1948 	 * and runs with IRQ disabled. 30 bits should be sufficient.
1949 	 */
1950 	SCX_OPSS_QSEQ_SHIFT	= 2,
1951 };
1952 
1953 /* Use macros to ensure that the type is unsigned long for the masks */
1954 #define SCX_OPSS_STATE_MASK	((1LU << SCX_OPSS_QSEQ_SHIFT) - 1)
1955 #define SCX_OPSS_QSEQ_MASK	(~SCX_OPSS_STATE_MASK)
1956 
1957 /*
1958  * SCX task iterator.
1959  */
1960 struct scx_task_iter {
1961 	struct sched_ext_entity		cursor;
1962 	struct task_struct		*locked_task;
1963 	struct rq			*rq;
1964 	struct rq_flags			rf;
1965 	u32				cnt;
1966 	bool				list_locked;
1967 #ifdef CONFIG_EXT_SUB_SCHED
1968 	struct cgroup			*cgrp;
1969 	struct cgroup_subsys_state	*css_pos;
1970 	struct css_task_iter		css_iter;
1971 #endif
1972 };
1973 
1974 /*
1975  * scx_enable() is offloaded to a dedicated system-wide RT kthread to avoid
1976  * starvation. During the READY -> ENABLED task switching loop, the calling
1977  * thread's sched_class gets switched from fair to ext. As fair has higher
1978  * priority than ext, the calling thread can be indefinitely starved under
1979  * fair-class saturation, leading to a system hang.
1980  */
1981 struct scx_enable_cmd {
1982 	struct kthread_work	work;
1983 	union {
1984 		struct sched_ext_ops		*ops;
1985 		struct sched_ext_ops_cid	*ops_cid;
1986 	};
1987 	bool			is_cid_type;
1988 	struct bpf_map		*arena_map;	/* arena ref to transfer to sch */
1989 	int			ret;
1990 };
1991 
1992 /* string formatting from BPF */
1993 struct scx_bstr_buf {
1994 	u64			data[MAX_BPRINTF_VARARGS];
1995 	char			line[SCX_EXIT_MSG_LEN];
1996 };
1997 
1998 extern struct scx_sched __rcu *scx_root;
1999 DECLARE_PER_CPU(struct rq *, scx_locked_rq_state);
2000 
2001 /*
2002  * True when the currently loaded scheduler hierarchy is cid-form. All scheds
2003  * in a hierarchy share one form, so this single key tells callsites which
2004  * view to use without per-sch dereferences. Use scx_is_cid_type() to test.
2005  */
2006 DECLARE_STATIC_KEY_FALSE(__scx_is_cid_type);
2007 
2008 int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id);
2009 
2010 bool scx_cpu_valid(struct scx_sched *sch, s32 cpu, const char *where);
2011 
2012 __printf(5, 0) bool scx_vexit(struct scx_sched *sch, enum scx_exit_kind kind,
2013 			      s64 exit_code, s32 exit_cpu, const char *fmt,
2014 			      va_list args);
2015 __printf(5, 6) bool __scx_exit(struct scx_sched *sch, enum scx_exit_kind kind,
2016 			       s64 exit_code, s32 exit_cpu, const char *fmt, ...);
2017 
2018 u32 scx_get_task_state(const struct task_struct *p);
2019 void scx_set_task_state(struct task_struct *p, u32 state);
2020 void scx_task_iter_start(struct scx_task_iter *iter, struct cgroup *cgrp);
2021 void scx_task_iter_unlock(struct scx_task_iter *iter);
2022 void scx_task_iter_stop(struct scx_task_iter *iter);
2023 struct task_struct *scx_task_iter_next_locked(struct scx_task_iter *iter);
2024 bool scx_set_task_slice(struct task_struct *p, u64 slice);
2025 void scx_task_slice_ended(struct rq *rq, struct task_struct *p);
2026 void scx_task_unlink_from_dsq(struct task_struct *p, struct scx_dispatch_q *dsq);
2027 void scx_dispatch_dequeue(struct rq *rq, struct task_struct *p);
2028 void scx_do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags,
2029 			 int sticky_cpu);
2030 void scx_move_local_task_to_local_dsq(struct scx_sched *sch, struct task_struct *p,
2031 				      u64 enq_flags, struct scx_dispatch_q *src_dsq,
2032 				      struct rq *dst_rq);
2033 bool scx_consume_dispatch_q(struct scx_sched *sch, struct rq *rq,
2034 			    struct scx_dispatch_q *dsq, u64 enq_flags);
2035 bool scx_consume_global_dsq(struct scx_sched *sch, struct rq *rq);
2036 bool scx_rq_online(struct rq *rq);
2037 void scx_flush_dispatch_buf(struct scx_sched *sch, struct rq *rq);
2038 s32 scx_init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id, struct scx_sched *sch);
2039 __printf(2, 3) void scx_dump_line(struct seq_buf *s, const char *fmt, ...);
2040 void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags);
2041 u64 __scx_bpf_now(struct rq *rq);
2042 void schedule_dsq_reenq(struct scx_sched *sch, struct scx_dispatch_q *dsq,
2043 			u64 reenq_flags, struct rq *locked_rq);
2044 int __scx_init_task(struct scx_sched *sch, struct task_struct *p,
2045 		    struct cgroup *cgrp, bool fork);
2046 void scx_enable_task(struct scx_sched *sch, struct task_struct *p);
2047 void __scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p);
2048 void scx_sub_init_cancel_task(struct scx_sched *sch, struct task_struct *p);
2049 void scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p);
2050 #if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED)
2051 void scx_cgroup_lock(void);
2052 void scx_cgroup_unlock(void);
2053 #endif
2054 s32 scx_set_cmask_scratch_alloc(struct scx_sched *sch);
2055 void scx_disable_bypass_dsp(struct scx_sched *sch);
2056 void scx_bypass(struct scx_sched *sch, bool bypass);
2057 s32 scx_link_sched(struct scx_sched *sch);
2058 void scx_unlink_sched(struct scx_sched *sch);
2059 void scx_disable_dump(struct scx_sched *sch);
2060 void scx_log_sched_disable(struct scx_sched *sch);
2061 void scx_flush_disable_work(struct scx_sched *sch);
2062 struct scx_sched *scx_alloc_and_add_sched(struct scx_enable_cmd *cmd,
2063 					  struct cgroup *cgrp,
2064 					  struct scx_sched *parent);
2065 int scx_validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops);
2066 int scx_sched_sysfs_add(struct scx_sched *sch);
2067 bool scx_is_descendant(struct scx_sched *sch, struct scx_sched *ancestor);
2068 __printf(5, 0) bool scx_exit_bstr(struct scx_sched *sch, enum scx_exit_kind kind,
2069 				  s64 exit_code, struct scx_sched *fmt_blame,
2070 				  char *fmt, unsigned long long *data, u32 data__sz);
2071 
2072 extern raw_spinlock_t scx_sched_lock;
2073 extern struct mutex scx_enable_mutex;
2074 extern struct percpu_rw_semaphore scx_fork_rwsem;
2075 extern bool scx_cgroup_enabled;
2076 extern struct list_head scx_sched_all;
2077 #ifdef CONFIG_EXT_SUB_SCHED
2078 extern const struct rhashtable_params scx_sched_hash_params;
2079 extern struct rhashtable scx_sched_hash;
2080 extern struct scx_sched *scx_enabling_sub_sched;
2081 #endif
2082 
2083 #define scx_exit(sch, kind, exit_code, fmt, args...)				\
2084 	__scx_exit(sch, kind, exit_code, raw_smp_processor_id(), fmt, ##args)
2085 #define scx_error(sch, fmt, args...)						\
2086 	scx_exit((sch), SCX_EXIT_ERROR, 0, fmt, ##args)
2087 
2088 /**
2089  * scx_root_protected_live - Root sched for paths that only run while live
2090  *
2091  * scx_root is published before the scheduler goes live and cleared only after
2092  * it is fully drained, so a path that only executes while the scheduler is live
2093  * can never race an update. Return the root sched with a plain load, never
2094  * %NULL.
2095  */
2096 static inline struct scx_sched *scx_root_protected_live(void)
2097 {
2098 	return rcu_dereference_protected(scx_root, true);
2099 }
2100 
2101 /**
2102  * scx_root_protected - Root sched for contexts that exclude its updates
2103  *
2104  * Both scx_root updates run under the locks checked below, so holding one
2105  * excludes them. Return the root sched with a plain load, %NULL if no scheduler
2106  * is loaded.
2107  */
2108 static inline struct scx_sched *scx_root_protected(void)
2109 {
2110 	return rcu_dereference_protected(scx_root,
2111 					 lockdep_is_cpus_held() ||
2112 					 lockdep_is_held(&scx_enable_mutex));
2113 }
2114 
2115 static inline struct scx_dispatch_q *scx_bypass_dsq(struct scx_sched *sch, s32 cpu)
2116 {
2117 	return &per_cpu_ptr(sch->pcpu, cpu)->bypass_dsq;
2118 }
2119 
2120 /**
2121  * scx_bypass_dsp_enabled - Check if bypass dispatch path is enabled
2122  * @sch: scheduler to check
2123  *
2124  * When a descendant scheduler enters bypass mode, bypassed tasks are scheduled
2125  * by the nearest non-bypassing ancestor, or the root scheduler if all ancestors
2126  * are bypassing. In the former case, the ancestor is not itself bypassing but
2127  * its bypass DSQs will be populated with bypassed tasks from descendants. Thus,
2128  * the ancestor's bypass dispatch path must be active even though its own
2129  * bypass_depth remains zero.
2130  *
2131  * This function checks bypass_dsp_enable_depth which is managed separately from
2132  * bypass_depth to enable this decoupling. See enable_bypass_dsp() and
2133  * scx_disable_bypass_dsp().
2134  */
2135 static inline bool scx_bypass_dsp_enabled(struct scx_sched *sch)
2136 {
2137 	return unlikely(atomic_read(&sch->bypass_dsp_enable_depth));
2138 }
2139 
2140 /**
2141  * scx_ops_sanitize_err - Sanitize a -errno value
2142  * @sch: scx_sched to error out on error
2143  * @ops_name: operation to blame on failure
2144  * @err: -errno value to sanitize
2145  *
2146  * Verify @err is a valid -errno. If not, trigger scx_error() and return
2147  * -%EPROTO. This is necessary because returning a rogue -errno up the chain can
2148  * cause misbehaviors. For an example, a large negative return from
2149  * ops.init_task() triggers an oops when passed up the call chain because the
2150  * value fails IS_ERR() test after being encoded with ERR_PTR() and then is
2151  * handled as a pointer.
2152  */
2153 static inline int scx_ops_sanitize_err(struct scx_sched *sch, const char *ops_name, s32 err)
2154 {
2155 	if (err < 0 && err >= -MAX_ERRNO)
2156 		return err;
2157 
2158 	scx_error(sch, "ops.%s() returned an invalid errno %d", ops_name, err);
2159 	return -EPROTO;
2160 }
2161 
2162 static inline void scx_schedule_reenq_local(struct rq *rq, u64 reenq_flags)
2163 {
2164 	struct scx_sched *root = rcu_dereference_sched(scx_root);
2165 
2166 	if (WARN_ON_ONCE(!root))
2167 		return;
2168 
2169 	schedule_dsq_reenq(root, &rq->scx.local_dsq, reenq_flags, rq);
2170 }
2171 
2172 /*
2173  * Return the rq currently locked from an scx callback, or NULL if no rq is
2174  * locked.
2175  */
2176 static inline struct rq *scx_locked_rq(void)
2177 {
2178 	return __this_cpu_read(scx_locked_rq_state);
2179 }
2180 
2181 static inline void update_locked_rq(struct rq *rq)
2182 {
2183 	/*
2184 	 * Check whether @rq is actually locked. This can help expose bugs
2185 	 * or incorrect assumptions about the context in which a kfunc or
2186 	 * callback is executed.
2187 	 */
2188 	if (rq)
2189 		lockdep_assert_rq_held(rq);
2190 	__this_cpu_write(scx_locked_rq_state, rq);
2191 }
2192 
2193 #define SCX_HAS_OP(sch, op)	test_bit(SCX_OP_IDX(op), (sch)->has_op)
2194 
2195 /*
2196  * SCX ops can recurse via scx_bpf_sub_dispatch() - the inner call must not
2197  * clobber the outer's scx_locked_rq_state. Save it on entry, restore on exit.
2198  *
2199  * @ops is the ops table to dispatch through: ops for the cpu form, ops_cid
2200  * for the cid form.
2201  */
2202 #define __SCX_CALL_OP(sch, ops, op, locked_rq, args...)				\
2203 do {										\
2204 	struct rq *__prev_locked_rq;						\
2205 										\
2206 	if (locked_rq) {							\
2207 		__prev_locked_rq = scx_locked_rq();				\
2208 		update_locked_rq(locked_rq);					\
2209 	}									\
2210 	(sch)->ops.op(args);							\
2211 	if (locked_rq)								\
2212 		update_locked_rq(__prev_locked_rq);				\
2213 } while (0)
2214 
2215 #define SCX_CALL_OP(sch, op, locked_rq, args...)				\
2216 	__SCX_CALL_OP(sch, ops, op, locked_rq, ##args)
2217 
2218 #define SCX_CALL_OP_RET(sch, op, locked_rq, args...)				\
2219 ({										\
2220 	struct rq *__prev_locked_rq;						\
2221 	__typeof__((sch)->ops.op(args)) __ret;					\
2222 										\
2223 	if (locked_rq) {							\
2224 		__prev_locked_rq = scx_locked_rq();				\
2225 		update_locked_rq(locked_rq);					\
2226 	}									\
2227 	__ret = (sch)->ops.op(args);						\
2228 	if (locked_rq)								\
2229 		update_locked_rq(__prev_locked_rq);				\
2230 	__ret;									\
2231 })
2232 
2233 /*
2234  * SCX_CALL_OP_TASK*() invokes an SCX op that takes one or two task arguments
2235  * and records them in current->scx.kf_tasks[] for the duration of the call. A
2236  * kfunc invoked from inside such an op can then use
2237  * scx_kf_arg_task_ok() to verify that its task argument is one of
2238  * those subject tasks.
2239  *
2240  * Every SCX_CALL_OP_TASK*() call site invokes its op with @p's rq lock held -
2241  * either via the @locked_rq argument here, or (for ops.select_cpu()) via @p's
2242  * pi_lock held by try_to_wake_up() with rq tracking via scx_rq.in_select_cpu.
2243  * So if kf_tasks[] is set, @p's scheduler-protected fields are stable.
2244  *
2245  * kf_tasks[] can not stack, so task-based SCX ops must not nest. The
2246  * WARN_ON_ONCE() in each macro catches a re-entry of any of the three variants
2247  * while a previous one is still in progress.
2248  */
2249 #define __SCX_CALL_OP_TASK(sch, ops, op, locked_rq, task, args...)		\
2250 do {										\
2251 	WARN_ON_ONCE(current->scx.kf_tasks[0]);					\
2252 	current->scx.kf_tasks[0] = task;					\
2253 	__SCX_CALL_OP((sch), ops, op, locked_rq, task, ##args);			\
2254 	current->scx.kf_tasks[0] = NULL;					\
2255 } while (0)
2256 
2257 /*
2258  * A per-task op runs on @task's owner - WARN if @sch isn't it. Sites that must
2259  * target a different scheduler call __SCX_CALL_OP_TASK() directly.
2260  */
2261 #define SCX_CALL_OP_TASK(sch, op, locked_rq, task, args...)			\
2262 do {										\
2263 	WARN_ON_ONCE(scx_has_subs() && (sch) != scx_task_sched_rcu(task));	\
2264 	__SCX_CALL_OP_TASK((sch), ops, op, locked_rq, task, ##args);		\
2265 } while (0)
2266 
2267 /*
2268  * Dispatch a task op through the cid-form ops_cid table. Only set_cmask() needs
2269  * this: it takes an arena cmask address instead of a cpumask, so it cannot be
2270  * invoked via its cpu-form set_cpumask() slot.
2271  */
2272 #define SCX_CALL_CID_OP_TASK(sch, op, locked_rq, task, args...)			\
2273 	__SCX_CALL_OP_TASK(sch, ops_cid, op, locked_rq, task, ##args)
2274 
2275 #define SCX_CALL_OP_TASK_RET(sch, op, locked_rq, task, args...)			\
2276 ({										\
2277 	__typeof__((sch)->ops.op(task, ##args)) __ret;				\
2278 	WARN_ON_ONCE(scx_has_subs() && (sch) != scx_task_sched_rcu(task));	\
2279 	WARN_ON_ONCE(current->scx.kf_tasks[0]);					\
2280 	current->scx.kf_tasks[0] = task;					\
2281 	__ret = SCX_CALL_OP_RET((sch), op, locked_rq, task, ##args);		\
2282 	current->scx.kf_tasks[0] = NULL;					\
2283 	__ret;									\
2284 })
2285 
2286 #define SCX_CALL_OP_2TASKS_RET(sch, op, locked_rq, task0, task1, args...)	\
2287 ({										\
2288 	__typeof__((sch)->ops.op(task0, task1, ##args)) __ret;			\
2289 	WARN_ON_ONCE(current->scx.kf_tasks[0]);					\
2290 	current->scx.kf_tasks[0] = task0;					\
2291 	current->scx.kf_tasks[1] = task1;					\
2292 	__ret = SCX_CALL_OP_RET((sch), op, locked_rq, task0, task1, ##args);	\
2293 	current->scx.kf_tasks[0] = NULL;					\
2294 	current->scx.kf_tasks[1] = NULL;					\
2295 	__ret;									\
2296 })
2297 
2298 /* see SCX_CALL_OP_TASK() */
2299 static __always_inline bool scx_kf_arg_task_ok(struct scx_sched *sch,
2300 					       struct task_struct *p)
2301 {
2302 	if (unlikely((p != current->scx.kf_tasks[0] &&
2303 		      p != current->scx.kf_tasks[1]))) {
2304 		scx_error(sch, "called on a task not being operated on");
2305 		return false;
2306 	}
2307 
2308 	return true;
2309 }
2310 
2311 static inline bool scx_bypassing(struct scx_sched *sch, s32 cpu)
2312 {
2313 	return unlikely(per_cpu_ptr(sch->pcpu, cpu)->flags &
2314 			SCX_SCHED_PCPU_BYPASSING);
2315 }
2316 
2317 #ifdef CONFIG_EXT_SUB_SCHED
2318 DECLARE_STATIC_KEY_FALSE(__scx_has_subs);
2319 
2320 /**
2321  * scx_has_subs - Whether any sub-scheduler exists
2322  *
2323  * Gates the sub-sched portions of hot paths so that a root-only system doesn't
2324  * pay for them. See scx_sub_enable_workfn() and scx_sched_free_rcu_work().
2325  */
2326 static inline bool scx_has_subs(void)
2327 {
2328 	return static_branch_unlikely(&__scx_has_subs);
2329 }
2330 
2331 /**
2332  * scx_task_sched - Find scx_sched scheduling a task
2333  * @p: task of interest
2334  *
2335  * Return @p's scheduler instance. Must be called with @p's pi_lock or rq lock
2336  * held.
2337  */
2338 static inline struct scx_sched *scx_task_sched(const struct task_struct *p)
2339 {
2340 	return rcu_dereference_protected(p->scx.sched,
2341 					 lockdep_is_held(&p->pi_lock) ||
2342 					 lockdep_is_held(__rq_lockp(task_rq(p))));
2343 }
2344 
2345 /**
2346  * scx_task_sched_rcu - Find scx_sched scheduling a task
2347  * @p: task of interest
2348  *
2349  * Return @p's scheduler instance. The returned scx_sched is RCU protected.
2350  */
2351 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p)
2352 {
2353 	return rcu_dereference_all(p->scx.sched);
2354 }
2355 
2356 /**
2357  * scx_task_on_sched - Is a task on the specified sched?
2358  * @sch: sched to test against
2359  * @p: task of interest
2360  *
2361  * Returns %true if @p is on @sch, %false otherwise.
2362  */
2363 static inline bool scx_task_on_sched(struct scx_sched *sch,
2364 				     const struct task_struct *p)
2365 {
2366 	return rcu_access_pointer(p->scx.sched) == sch;
2367 }
2368 
2369 /**
2370  * scx_prog_sched - Find scx_sched associated with a BPF prog
2371  * @aux: aux passed in from BPF to a kfunc
2372  *
2373  * To be called from kfuncs. Return the scheduler instance associated with the
2374  * BPF program given the implicit kfunc argument aux. The returned scx_sched is
2375  * RCU protected.
2376  */
2377 static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux)
2378 {
2379 	struct sched_ext_ops *ops;
2380 	struct scx_sched *sch, *root;
2381 
2382 	ops = bpf_prog_get_assoc_struct_ops(aux);
2383 	if (likely(ops)) {
2384 		sch = rcu_dereference_all(ops->priv);
2385 		if (sch && unlikely(READ_ONCE(sch->dead)))
2386 			return NULL;
2387 		return sch;
2388 	}
2389 
2390 	root = rcu_dereference_all(scx_root);
2391 	if (root) {
2392 		if (unlikely(READ_ONCE(root->dead)))
2393 			return NULL;
2394 		/*
2395 		 * COMPAT-v6.19: Schedulers built before sub-sched support was
2396 		 * introduced may have unassociated non-struct_ops programs.
2397 		 */
2398 		if (!root->ops.sub_attach)
2399 			return root;
2400 
2401 		if (!root->warned_unassoc_progs) {
2402 			printk_deferred(KERN_WARNING "sched_ext: Unassociated program %s (id %d)\n",
2403 					aux->name, aux->id);
2404 			root->warned_unassoc_progs = true;
2405 		}
2406 	}
2407 
2408 	return NULL;
2409 }
2410 
2411 /**
2412  * scx_parent - Find the parent sched
2413  * @sch: sched to find the parent of
2414  *
2415  * Returns the parent scheduler or %NULL if @sch is root.
2416  */
2417 static inline struct scx_sched *scx_parent(struct scx_sched *sch)
2418 {
2419 	if (sch->level)
2420 		return sch->ancestors[sch->level - 1];
2421 	else
2422 		return NULL;
2423 }
2424 
2425 #else	/* CONFIG_EXT_SUB_SCHED */
2426 static inline bool scx_has_subs(void) { return false; }
2427 
2428 static inline struct scx_sched *scx_task_sched(const struct task_struct *p)
2429 {
2430 	return rcu_dereference_protected(scx_root,
2431 					 lockdep_is_held(&p->pi_lock) ||
2432 					 lockdep_is_held(__rq_lockp(task_rq(p))));
2433 }
2434 
2435 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p)
2436 {
2437 	return rcu_dereference_all(scx_root);
2438 }
2439 
2440 static inline bool scx_task_on_sched(struct scx_sched *sch,
2441 				     const struct task_struct *p)
2442 {
2443 	return true;
2444 }
2445 
2446 static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux)
2447 {
2448 	struct scx_sched *root = rcu_dereference_all(scx_root);
2449 
2450 	if (root && unlikely(READ_ONCE(root->dead)))
2451 		return NULL;
2452 	return root;
2453 }
2454 
2455 static inline struct scx_sched *scx_parent(struct scx_sched *sch) { return NULL; }
2456 
2457 #endif	/* CONFIG_EXT_SUB_SCHED */
2458 
2459 #endif /* _KERNEL_SCHED_EXT_INTERNAL_H */
2460