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