xref: /linux/kernel/sched/ext_internal.h (revision 2e05f2fd0dd72aa8aa56cf355e1e39a3f565b4ca)
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 #define SCX_OP_IDX(op)		(offsetof(struct sched_ext_ops, op) / sizeof(void (*)(void)))
9 #define SCX_MOFF_IDX(moff)	((moff) / sizeof(void (*)(void)))
10 
11 enum scx_exit_kind {
12 	SCX_EXIT_NONE,
13 	SCX_EXIT_DONE,
14 
15 	SCX_EXIT_UNREG = 64,	/* user-space initiated unregistration */
16 	SCX_EXIT_UNREG_BPF,	/* BPF-initiated unregistration */
17 	SCX_EXIT_UNREG_KERN,	/* kernel-initiated unregistration */
18 	SCX_EXIT_SYSRQ,		/* requested by 'S' sysrq */
19 	SCX_EXIT_PARENT,	/* parent exiting */
20 
21 	SCX_EXIT_ERROR = 1024,	/* runtime error, error msg contains details */
22 	SCX_EXIT_ERROR_BPF,	/* ERROR but triggered through scx_bpf_error() */
23 	SCX_EXIT_ERROR_STALL,	/* watchdog detected stalled runnable tasks */
24 };
25 
26 /*
27  * An exit code can be specified when exiting with scx_bpf_exit() or scx_exit(),
28  * corresponding to exit_kind UNREG_BPF and UNREG_KERN respectively. The codes
29  * are 64bit of the format:
30  *
31  *   Bits: [63  ..  48 47   ..  32 31 .. 0]
32  *         [ SYS ACT ] [ SYS RSN ] [ USR  ]
33  *
34  *   SYS ACT: System-defined exit actions
35  *   SYS RSN: System-defined exit reasons
36  *   USR    : User-defined exit codes and reasons
37  *
38  * Using the above, users may communicate intention and context by ORing system
39  * actions and/or system reasons with a user-defined exit code.
40  */
41 enum scx_exit_code {
42 	/* Reasons */
43 	SCX_ECODE_RSN_HOTPLUG	= 1LLU << 32,
44 	SCX_ECODE_RSN_CGROUP_OFFLINE = 2LLU << 32,
45 
46 	/* Actions */
47 	SCX_ECODE_ACT_RESTART	= 1LLU << 48,
48 };
49 
50 enum scx_exit_flags {
51 	/*
52 	 * ops.exit() may be called even if the loading failed before ops.init()
53 	 * finishes successfully. This is because ops.exit() allows rich exit
54 	 * info communication. The following flag indicates whether ops.init()
55 	 * finished successfully.
56 	 */
57 	SCX_EFLAG_INITIALIZED   = 1LLU << 0,
58 };
59 
60 /*
61  * scx_exit_info is passed to ops.exit() to describe why the BPF scheduler is
62  * being disabled.
63  */
64 struct scx_exit_info {
65 	/* %SCX_EXIT_* - broad category of the exit reason */
66 	enum scx_exit_kind	kind;
67 
68 	/*
69 	 * CPU that initiated the exit, valid once @kind has been set.
70 	 * Negative if the exit path didn't identify a CPU.
71 	 */
72 	s32			exit_cpu;
73 
74 	/* exit code if gracefully exiting */
75 	s64			exit_code;
76 
77 	/* %SCX_EFLAG_* */
78 	u64			flags;
79 
80 	/* textual representation of the above */
81 	const char		*reason;
82 
83 	/* backtrace if exiting due to an error */
84 	unsigned long		*bt;
85 	u32			bt_len;
86 
87 	/* informational message */
88 	char			*msg;
89 
90 	/* debug dump */
91 	char			*dump;
92 };
93 
94 /* sched_ext_ops.flags */
95 enum scx_ops_flags {
96 	/*
97 	 * Keep built-in idle tracking even if ops.update_idle() is implemented.
98 	 */
99 	SCX_OPS_KEEP_BUILTIN_IDLE	= 1LLU << 0,
100 
101 	/*
102 	 * By default, if there are no other task to run on the CPU, ext core
103 	 * keeps running the current task even after its slice expires. If this
104 	 * flag is specified, such tasks are passed to ops.enqueue() with
105 	 * %SCX_ENQ_LAST. See the comment above %SCX_ENQ_LAST for more info.
106 	 */
107 	SCX_OPS_ENQ_LAST		= 1LLU << 1,
108 
109 	/*
110 	 * An exiting task may schedule after PF_EXITING is set. In such cases,
111 	 * bpf_task_from_pid() may not be able to find the task and if the BPF
112 	 * scheduler depends on pid lookup for dispatching, the task will be
113 	 * lost leading to various issues including RCU grace period stalls.
114 	 *
115 	 * To mask this problem, by default, unhashed tasks are automatically
116 	 * dispatched to the local DSQ on enqueue. If the BPF scheduler doesn't
117 	 * depend on pid lookups and wants to handle these tasks directly, the
118 	 * following flag can be used. With %SCX_OPS_TID_TO_TASK,
119 	 * scx_bpf_tid_to_task() can find exiting tasks reliably.
120 	 */
121 	SCX_OPS_ENQ_EXITING		= 1LLU << 2,
122 
123 	/*
124 	 * If set, only tasks with policy set to SCHED_EXT are attached to
125 	 * sched_ext. If clear, SCHED_NORMAL tasks are also included.
126 	 */
127 	SCX_OPS_SWITCH_PARTIAL		= 1LLU << 3,
128 
129 	/*
130 	 * A migration disabled task can only execute on its current CPU. By
131 	 * default, such tasks are automatically put on the CPU's local DSQ with
132 	 * the default slice on enqueue. If this ops flag is set, they also go
133 	 * through ops.enqueue().
134 	 *
135 	 * A migration disabled task never invokes ops.select_cpu() as it can
136 	 * only select the current CPU. Also, p->cpus_ptr will only contain its
137 	 * current CPU while p->nr_cpus_allowed keeps tracking p->user_cpus_ptr
138 	 * and thus may disagree with cpumask_weight(p->cpus_ptr).
139 	 */
140 	SCX_OPS_ENQ_MIGRATION_DISABLED	= 1LLU << 4,
141 
142 	/*
143 	 * Queued wakeup (ttwu_queue) is a wakeup optimization that invokes
144 	 * ops.enqueue() on the ops.select_cpu() selected or the wakee's
145 	 * previous CPU via IPI (inter-processor interrupt) to reduce cacheline
146 	 * transfers. When this optimization is enabled, ops.select_cpu() is
147 	 * skipped in some cases (when racing against the wakee switching out).
148 	 * As the BPF scheduler may depend on ops.select_cpu() being invoked
149 	 * during wakeups, queued wakeup is disabled by default.
150 	 *
151 	 * If this ops flag is set, queued wakeup optimization is enabled and
152 	 * the BPF scheduler must be able to handle ops.enqueue() invoked on the
153 	 * wakee's CPU without preceding ops.select_cpu() even for tasks which
154 	 * may be executed on multiple CPUs.
155 	 */
156 	SCX_OPS_ALLOW_QUEUED_WAKEUP	= 1LLU << 5,
157 
158 	/*
159 	 * If set, enable per-node idle cpumasks. If clear, use a single global
160 	 * flat idle cpumask.
161 	 */
162 	SCX_OPS_BUILTIN_IDLE_PER_NODE	= 1LLU << 6,
163 
164 	/*
165 	 * If set, %SCX_ENQ_IMMED is assumed to be set on all local DSQ
166 	 * enqueues.
167 	 */
168 	SCX_OPS_ALWAYS_ENQ_IMMED	= 1LLU << 7,
169 
170 	/*
171 	 * Maintain a mapping from p->scx.tid to task_struct so the BPF
172 	 * scheduler can recover task pointers from stored tids via
173 	 * scx_bpf_tid_to_task().
174 	 *
175 	 * Only the root scheduler turns this on. A sub-sched may set the flag
176 	 * to declare a dependency on the lookup; if the root scheduler hasn't
177 	 * enabled it, attaching the sub-sched is rejected.
178 	 */
179 	SCX_OPS_TID_TO_TASK		= 1LLU << 8,
180 
181 	SCX_OPS_ALL_FLAGS		= SCX_OPS_KEEP_BUILTIN_IDLE |
182 					  SCX_OPS_ENQ_LAST |
183 					  SCX_OPS_ENQ_EXITING |
184 					  SCX_OPS_ENQ_MIGRATION_DISABLED |
185 					  SCX_OPS_ALLOW_QUEUED_WAKEUP |
186 					  SCX_OPS_SWITCH_PARTIAL |
187 					  SCX_OPS_BUILTIN_IDLE_PER_NODE |
188 					  SCX_OPS_ALWAYS_ENQ_IMMED |
189 					  SCX_OPS_TID_TO_TASK,
190 
191 	/* high 8 bits are internal, don't include in SCX_OPS_ALL_FLAGS */
192 	__SCX_OPS_INTERNAL_MASK		= 0xffLLU << 56,
193 
194 	SCX_OPS_HAS_CPU_PREEMPT		= 1LLU << 56,
195 };
196 
197 /* argument container for ops.init_task() */
198 struct scx_init_task_args {
199 	/*
200 	 * Set if ops.init_task() is being invoked on the fork path, as opposed
201 	 * to the scheduler transition path.
202 	 */
203 	bool			fork;
204 #ifdef CONFIG_EXT_GROUP_SCHED
205 	/* the cgroup the task is joining */
206 	struct cgroup		*cgroup;
207 #endif
208 };
209 
210 /* argument container for ops.exit_task() */
211 struct scx_exit_task_args {
212 	/* Whether the task exited before running on sched_ext. */
213 	bool cancelled;
214 };
215 
216 /* argument container for ops.cgroup_init() */
217 struct scx_cgroup_init_args {
218 	/* the weight of the cgroup [1..10000] */
219 	u32			weight;
220 
221 	/* bandwidth control parameters from cpu.max and cpu.max.burst */
222 	u64			bw_period_us;
223 	u64			bw_quota_us;
224 	u64			bw_burst_us;
225 };
226 
227 enum scx_cpu_preempt_reason {
228 	/* next task is being scheduled by &sched_class_rt */
229 	SCX_CPU_PREEMPT_RT,
230 	/* next task is being scheduled by &sched_class_dl */
231 	SCX_CPU_PREEMPT_DL,
232 	/* next task is being scheduled by &sched_class_stop */
233 	SCX_CPU_PREEMPT_STOP,
234 	/* unknown reason for SCX being preempted */
235 	SCX_CPU_PREEMPT_UNKNOWN,
236 };
237 
238 /*
239  * Argument container for ops.cpu_acquire(). Currently empty, but may be
240  * expanded in the future.
241  */
242 struct scx_cpu_acquire_args {};
243 
244 /* argument container for ops.cpu_release() */
245 struct scx_cpu_release_args {
246 	/* the reason the CPU was preempted */
247 	enum scx_cpu_preempt_reason reason;
248 
249 	/* the task that's going to be scheduled on the CPU */
250 	struct task_struct	*task;
251 };
252 
253 /* informational context provided to dump operations */
254 struct scx_dump_ctx {
255 	enum scx_exit_kind	kind;
256 	s64			exit_code;
257 	const char		*reason;
258 	u64			at_ns;
259 	u64			at_jiffies;
260 };
261 
262 /* argument container for ops.sub_attach() */
263 struct scx_sub_attach_args {
264 	struct sched_ext_ops	*ops;
265 	char			*cgroup_path;
266 };
267 
268 /* argument container for ops.sub_detach() */
269 struct scx_sub_detach_args {
270 	struct sched_ext_ops	*ops;
271 	char			*cgroup_path;
272 };
273 
274 /**
275  * struct sched_ext_ops - Operation table for BPF scheduler implementation
276  *
277  * A BPF scheduler can implement an arbitrary scheduling policy by
278  * implementing and loading operations in this table. Note that a userland
279  * scheduling policy can also be implemented using the BPF scheduler
280  * as a shim layer.
281  */
282 struct sched_ext_ops {
283 	/**
284 	 * @select_cpu: Pick the target CPU for a task which is being woken up
285 	 * @p: task being woken up
286 	 * @prev_cpu: the cpu @p was on before sleeping
287 	 * @wake_flags: SCX_WAKE_*
288 	 *
289 	 * Decision made here isn't final. @p may be moved to any CPU while it
290 	 * is getting dispatched for execution later. However, as @p is not on
291 	 * the rq at this point, getting the eventual execution CPU right here
292 	 * saves a small bit of overhead down the line.
293 	 *
294 	 * If an idle CPU is returned, the CPU is kicked and will try to
295 	 * dispatch. While an explicit custom mechanism can be added,
296 	 * select_cpu() serves as the default way to wake up idle CPUs.
297 	 *
298 	 * @p may be inserted into a DSQ directly by calling
299 	 * scx_bpf_dsq_insert(). If so, the ops.enqueue() will be skipped.
300 	 * Directly inserting into %SCX_DSQ_LOCAL will put @p in the local DSQ
301 	 * of the CPU returned by this operation.
302 	 *
303 	 * Note that select_cpu() is never called for tasks that can only run
304 	 * on a single CPU or tasks with migration disabled, as they don't have
305 	 * the option to select a different CPU. See select_task_rq() for
306 	 * details.
307 	 */
308 	s32 (*select_cpu)(struct task_struct *p, s32 prev_cpu, u64 wake_flags);
309 
310 	/**
311 	 * @enqueue: Enqueue a task on the BPF scheduler
312 	 * @p: task being enqueued
313 	 * @enq_flags: %SCX_ENQ_*
314 	 *
315 	 * @p is ready to run. Insert directly into a DSQ by calling
316 	 * scx_bpf_dsq_insert() or enqueue on the BPF scheduler. If not directly
317 	 * inserted, the bpf scheduler owns @p and if it fails to dispatch @p,
318 	 * the task will stall.
319 	 *
320 	 * If @p was inserted into a DSQ from ops.select_cpu(), this callback is
321 	 * skipped.
322 	 */
323 	void (*enqueue)(struct task_struct *p, u64 enq_flags);
324 
325 	/**
326 	 * @dequeue: Remove a task from the BPF scheduler
327 	 * @p: task being dequeued
328 	 * @deq_flags: %SCX_DEQ_*
329 	 *
330 	 * Remove @p from the BPF scheduler. This is usually called to isolate
331 	 * the task while updating its scheduling properties (e.g. priority).
332 	 *
333 	 * The ext core keeps track of whether the BPF side owns a given task or
334 	 * not and can gracefully ignore spurious dispatches from BPF side,
335 	 * which makes it safe to not implement this method. However, depending
336 	 * on the scheduling logic, this can lead to confusing behaviors - e.g.
337 	 * scheduling position not being updated across a priority change.
338 	 */
339 	void (*dequeue)(struct task_struct *p, u64 deq_flags);
340 
341 	/**
342 	 * @dispatch: Dispatch tasks from the BPF scheduler and/or user DSQs
343 	 * @cpu: CPU to dispatch tasks for
344 	 * @prev: previous task being switched out
345 	 *
346 	 * Called when a CPU's local dsq is empty. The operation should dispatch
347 	 * one or more tasks from the BPF scheduler into the DSQs using
348 	 * scx_bpf_dsq_insert() and/or move from user DSQs into the local DSQ
349 	 * using scx_bpf_dsq_move_to_local().
350 	 *
351 	 * The maximum number of times scx_bpf_dsq_insert() can be called
352 	 * without an intervening scx_bpf_dsq_move_to_local() is specified by
353 	 * ops.dispatch_max_batch. See the comments on top of the two functions
354 	 * for more details.
355 	 *
356 	 * When not %NULL, @prev is an SCX task with its slice depleted. If
357 	 * @prev is still runnable as indicated by set %SCX_TASK_QUEUED in
358 	 * @prev->scx.flags, it is not enqueued yet and will be enqueued after
359 	 * ops.dispatch() returns. To keep executing @prev, return without
360 	 * dispatching or moving any tasks. Also see %SCX_OPS_ENQ_LAST.
361 	 */
362 	void (*dispatch)(s32 cpu, struct task_struct *prev);
363 
364 	/**
365 	 * @tick: Periodic tick
366 	 * @p: task running currently
367 	 *
368 	 * This operation is called every 1/HZ seconds on CPUs which are
369 	 * executing an SCX task. Setting @p->scx.slice to 0 will trigger an
370 	 * immediate dispatch cycle on the CPU.
371 	 */
372 	void (*tick)(struct task_struct *p);
373 
374 	/**
375 	 * @runnable: A task is becoming runnable on its associated CPU
376 	 * @p: task becoming runnable
377 	 * @enq_flags: %SCX_ENQ_*
378 	 *
379 	 * This and the following three functions can be used to track a task's
380 	 * execution state transitions. A task becomes ->runnable() on a CPU,
381 	 * and then goes through one or more ->running() and ->stopping() pairs
382 	 * as it runs on the CPU, and eventually becomes ->quiescent() when it's
383 	 * done running on the CPU.
384 	 *
385 	 * @p is becoming runnable on the CPU because it's
386 	 *
387 	 * - waking up (%SCX_ENQ_WAKEUP)
388 	 * - being moved from another CPU
389 	 * - being restored after temporarily taken off the queue for an
390 	 *   attribute change.
391 	 *
392 	 * This and ->enqueue() are related but not coupled. This operation
393 	 * notifies @p's state transition and may not be followed by ->enqueue()
394 	 * e.g. when @p is being dispatched to a remote CPU, or when @p is
395 	 * being enqueued on a CPU experiencing a hotplug event. Likewise, a
396 	 * task may be ->enqueue()'d without being preceded by this operation
397 	 * e.g. after exhausting its slice.
398 	 */
399 	void (*runnable)(struct task_struct *p, u64 enq_flags);
400 
401 	/**
402 	 * @running: A task is starting to run on its associated CPU
403 	 * @p: task starting to run
404 	 *
405 	 * Note that this callback may be called from a CPU other than the
406 	 * one the task is going to run on. This can happen when a task
407 	 * property is changed (i.e., affinity), since scx_next_task_scx(),
408 	 * which triggers this callback, may run on a CPU different from
409 	 * the task's assigned CPU.
410 	 *
411 	 * Therefore, always use scx_bpf_task_cpu(@p) to determine the
412 	 * target CPU the task is going to use.
413 	 *
414 	 * See ->runnable() for explanation on the task state notifiers.
415 	 */
416 	void (*running)(struct task_struct *p);
417 
418 	/**
419 	 * @stopping: A task is stopping execution
420 	 * @p: task stopping to run
421 	 * @runnable: is task @p still runnable?
422 	 *
423 	 * Note that this callback may be called from a CPU other than the
424 	 * one the task was running on. This can happen when a task
425 	 * property is changed (i.e., affinity), since dequeue_task_scx(),
426 	 * which triggers this callback, may run on a CPU different from
427 	 * the task's assigned CPU.
428 	 *
429 	 * Therefore, always use scx_bpf_task_cpu(@p) to retrieve the CPU
430 	 * the task was running on.
431 	 *
432 	 * See ->runnable() for explanation on the task state notifiers. If
433 	 * !@runnable, ->quiescent() will be invoked after this operation
434 	 * returns.
435 	 */
436 	void (*stopping)(struct task_struct *p, bool runnable);
437 
438 	/**
439 	 * @quiescent: A task is becoming not runnable on its associated CPU
440 	 * @p: task becoming not runnable
441 	 * @deq_flags: %SCX_DEQ_*
442 	 *
443 	 * See ->runnable() for explanation on the task state notifiers.
444 	 *
445 	 * @p is becoming quiescent on the CPU because it's
446 	 *
447 	 * - sleeping (%SCX_DEQ_SLEEP)
448 	 * - being moved to another CPU
449 	 * - being temporarily taken off the queue for an attribute change
450 	 *   (%SCX_DEQ_SAVE)
451 	 *
452 	 * This and ->dequeue() are related but not coupled. This operation
453 	 * notifies @p's state transition and may not be preceded by ->dequeue()
454 	 * e.g. when @p is being dispatched to a remote CPU.
455 	 */
456 	void (*quiescent)(struct task_struct *p, u64 deq_flags);
457 
458 	/**
459 	 * @yield: Yield CPU
460 	 * @from: yielding task
461 	 * @to: optional yield target task
462 	 *
463 	 * If @to is NULL, @from is yielding the CPU to other runnable tasks.
464 	 * The BPF scheduler should ensure that other available tasks are
465 	 * dispatched before the yielding task. Return value is ignored in this
466 	 * case.
467 	 *
468 	 * If @to is not-NULL, @from wants to yield the CPU to @to. If the bpf
469 	 * scheduler can implement the request, return %true; otherwise, %false.
470 	 */
471 	bool (*yield)(struct task_struct *from, struct task_struct *to);
472 
473 	/**
474 	 * @core_sched_before: Task ordering for core-sched
475 	 * @a: task A
476 	 * @b: task B
477 	 *
478 	 * Used by core-sched to determine the ordering between two tasks. See
479 	 * Documentation/admin-guide/hw-vuln/core-scheduling.rst for details on
480 	 * core-sched.
481 	 *
482 	 * Both @a and @b are runnable and may or may not currently be queued on
483 	 * the BPF scheduler. Should return %true if @a should run before @b.
484 	 * %false if there's no required ordering or @b should run before @a.
485 	 *
486 	 * If not specified, the default is ordering them according to when they
487 	 * became runnable.
488 	 */
489 	bool (*core_sched_before)(struct task_struct *a, struct task_struct *b);
490 
491 	/**
492 	 * @set_weight: Set task weight
493 	 * @p: task to set weight for
494 	 * @weight: new weight [1..10000]
495 	 *
496 	 * Update @p's weight to @weight.
497 	 */
498 	void (*set_weight)(struct task_struct *p, u32 weight);
499 
500 	/**
501 	 * @set_cpumask: Set CPU affinity
502 	 * @p: task to set CPU affinity for
503 	 * @cpumask: cpumask of cpus that @p can run on
504 	 *
505 	 * Update @p's CPU affinity to @cpumask.
506 	 */
507 	void (*set_cpumask)(struct task_struct *p,
508 			    const struct cpumask *cpumask);
509 
510 	/**
511 	 * @update_idle: Update the idle state of a CPU
512 	 * @cpu: CPU to update the idle state for
513 	 * @idle: whether entering or exiting the idle state
514 	 *
515 	 * This operation is called when @rq's CPU goes or leaves the idle
516 	 * state. By default, implementing this operation disables the built-in
517 	 * idle CPU tracking and the following helpers become unavailable:
518 	 *
519 	 * - scx_bpf_select_cpu_dfl()
520 	 * - scx_bpf_select_cpu_and()
521 	 * - scx_bpf_test_and_clear_cpu_idle()
522 	 * - scx_bpf_pick_idle_cpu()
523 	 *
524 	 * The user also must implement ops.select_cpu() as the default
525 	 * implementation relies on scx_bpf_select_cpu_dfl().
526 	 *
527 	 * Specify the %SCX_OPS_KEEP_BUILTIN_IDLE flag to keep the built-in idle
528 	 * tracking.
529 	 */
530 	void (*update_idle)(s32 cpu, bool idle);
531 
532 	/**
533 	 * @init_task: Initialize a task to run in a BPF scheduler
534 	 * @p: task to initialize for BPF scheduling
535 	 * @args: init arguments, see the struct definition
536 	 *
537 	 * Either we're loading a BPF scheduler or a new task is being forked.
538 	 * Initialize @p for BPF scheduling. This operation may block and can
539 	 * be used for allocations, and is called exactly once for a task.
540 	 *
541 	 * Return 0 for success, -errno for failure. An error return while
542 	 * loading will abort loading of the BPF scheduler. During a fork, it
543 	 * will abort that specific fork.
544 	 */
545 	s32 (*init_task)(struct task_struct *p, struct scx_init_task_args *args);
546 
547 	/**
548 	 * @exit_task: Exit a previously-running task from the system
549 	 * @p: task to exit
550 	 * @args: exit arguments, see the struct definition
551 	 *
552 	 * @p is exiting or the BPF scheduler is being unloaded. Perform any
553 	 * necessary cleanup for @p.
554 	 */
555 	void (*exit_task)(struct task_struct *p, struct scx_exit_task_args *args);
556 
557 	/**
558 	 * @enable: Enable BPF scheduling for a task
559 	 * @p: task to enable BPF scheduling for
560 	 *
561 	 * Enable @p for BPF scheduling. enable() is called on @p any time it
562 	 * enters SCX, and is always paired with a matching disable().
563 	 */
564 	void (*enable)(struct task_struct *p);
565 
566 	/**
567 	 * @disable: Disable BPF scheduling for a task
568 	 * @p: task to disable BPF scheduling for
569 	 *
570 	 * @p is exiting, leaving SCX or the BPF scheduler is being unloaded.
571 	 * Disable BPF scheduling for @p. A disable() call is always matched
572 	 * with a prior enable() call.
573 	 */
574 	void (*disable)(struct task_struct *p);
575 
576 	/**
577 	 * @dump: Dump BPF scheduler state on error
578 	 * @ctx: debug dump context
579 	 *
580 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump.
581 	 */
582 	void (*dump)(struct scx_dump_ctx *ctx);
583 
584 	/**
585 	 * @dump_cpu: Dump BPF scheduler state for a CPU on error
586 	 * @ctx: debug dump context
587 	 * @cpu: CPU to generate debug dump for
588 	 * @idle: @cpu is currently idle without any runnable tasks
589 	 *
590 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
591 	 * @cpu. If @idle is %true and this operation doesn't produce any
592 	 * output, @cpu is skipped for dump.
593 	 */
594 	void (*dump_cpu)(struct scx_dump_ctx *ctx, s32 cpu, bool idle);
595 
596 	/**
597 	 * @dump_task: Dump BPF scheduler state for a runnable task on error
598 	 * @ctx: debug dump context
599 	 * @p: runnable task to generate debug dump for
600 	 *
601 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
602 	 * @p.
603 	 */
604 	void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p);
605 
606 #ifdef CONFIG_EXT_GROUP_SCHED
607 	/**
608 	 * @cgroup_init: Initialize a cgroup
609 	 * @cgrp: cgroup being initialized
610 	 * @args: init arguments, see the struct definition
611 	 *
612 	 * Either the BPF scheduler is being loaded or @cgrp created, initialize
613 	 * @cgrp for sched_ext. This operation may block.
614 	 *
615 	 * Return 0 for success, -errno for failure. An error return while
616 	 * loading will abort loading of the BPF scheduler. During cgroup
617 	 * creation, it will abort the specific cgroup creation.
618 	 */
619 	s32 (*cgroup_init)(struct cgroup *cgrp,
620 			   struct scx_cgroup_init_args *args);
621 
622 	/**
623 	 * @cgroup_exit: Exit a cgroup
624 	 * @cgrp: cgroup being exited
625 	 *
626 	 * Either the BPF scheduler is being unloaded or @cgrp destroyed, exit
627 	 * @cgrp for sched_ext. This operation my block.
628 	 */
629 	void (*cgroup_exit)(struct cgroup *cgrp);
630 
631 	/**
632 	 * @cgroup_prep_move: Prepare a task to be moved to a different cgroup
633 	 * @p: task being moved
634 	 * @from: cgroup @p is being moved from
635 	 * @to: cgroup @p is being moved to
636 	 *
637 	 * Prepare @p for move from cgroup @from to @to. This operation may
638 	 * block and can be used for allocations.
639 	 *
640 	 * Return 0 for success, -errno for failure. An error return aborts the
641 	 * migration.
642 	 */
643 	s32 (*cgroup_prep_move)(struct task_struct *p,
644 				struct cgroup *from, struct cgroup *to);
645 
646 	/**
647 	 * @cgroup_move: Commit cgroup move
648 	 * @p: task being moved
649 	 * @from: cgroup @p is being moved from
650 	 * @to: cgroup @p is being moved to
651 	 *
652 	 * Commit the move. @p is dequeued during this operation.
653 	 */
654 	void (*cgroup_move)(struct task_struct *p,
655 			    struct cgroup *from, struct cgroup *to);
656 
657 	/**
658 	 * @cgroup_cancel_move: Cancel cgroup move
659 	 * @p: task whose cgroup move is being canceled
660 	 * @from: cgroup @p was being moved from
661 	 * @to: cgroup @p was being moved to
662 	 *
663 	 * @p was cgroup_prep_move()'d but failed before reaching cgroup_move().
664 	 * Undo the preparation.
665 	 */
666 	void (*cgroup_cancel_move)(struct task_struct *p,
667 				   struct cgroup *from, struct cgroup *to);
668 
669 	/**
670 	 * @cgroup_set_weight: A cgroup's weight is being changed
671 	 * @cgrp: cgroup whose weight is being updated
672 	 * @weight: new weight [1..10000]
673 	 *
674 	 * Update @cgrp's weight to @weight.
675 	 */
676 	void (*cgroup_set_weight)(struct cgroup *cgrp, u32 weight);
677 
678 	/**
679 	 * @cgroup_set_bandwidth: A cgroup's bandwidth is being changed
680 	 * @cgrp: cgroup whose bandwidth is being updated
681 	 * @period_us: bandwidth control period
682 	 * @quota_us: bandwidth control quota
683 	 * @burst_us: bandwidth control burst
684 	 *
685 	 * Update @cgrp's bandwidth control parameters. This is from the cpu.max
686 	 * cgroup interface.
687 	 *
688 	 * @quota_us / @period_us determines the CPU bandwidth @cgrp is entitled
689 	 * to. For example, if @period_us is 1_000_000 and @quota_us is
690 	 * 2_500_000. @cgrp is entitled to 2.5 CPUs. @burst_us can be
691 	 * interpreted in the same fashion and specifies how much @cgrp can
692 	 * burst temporarily. The specific control mechanism and thus the
693 	 * interpretation of @period_us and burstiness is up to the BPF
694 	 * scheduler.
695 	 */
696 	void (*cgroup_set_bandwidth)(struct cgroup *cgrp,
697 				     u64 period_us, u64 quota_us, u64 burst_us);
698 
699 	/**
700 	 * @cgroup_set_idle: A cgroup's idle state is being changed
701 	 * @cgrp: cgroup whose idle state is being updated
702 	 * @idle: whether the cgroup is entering or exiting idle state
703 	 *
704 	 * Update @cgrp's idle state to @idle. This callback is invoked when
705 	 * a cgroup transitions between idle and non-idle states, allowing the
706 	 * BPF scheduler to adjust its behavior accordingly.
707 	 */
708 	void (*cgroup_set_idle)(struct cgroup *cgrp, bool idle);
709 
710 #endif	/* CONFIG_EXT_GROUP_SCHED */
711 
712 	/**
713 	 * @sub_attach: Attach a sub-scheduler
714 	 * @args: argument container, see the struct definition
715 	 *
716 	 * Return 0 to accept the sub-scheduler. -errno to reject.
717 	 */
718 	s32 (*sub_attach)(struct scx_sub_attach_args *args);
719 
720 	/**
721 	 * @sub_detach: Detach a sub-scheduler
722 	 * @args: argument container, see the struct definition
723 	 */
724 	void (*sub_detach)(struct scx_sub_detach_args *args);
725 
726 	/*
727 	 * All online ops must come before ops.cpu_online().
728 	 */
729 
730 	/**
731 	 * @cpu_online: A CPU became online
732 	 * @cpu: CPU which just came up
733 	 *
734 	 * @cpu just came online. @cpu will not call ops.enqueue() or
735 	 * ops.dispatch(), nor run tasks associated with other CPUs beforehand.
736 	 */
737 	void (*cpu_online)(s32 cpu);
738 
739 	/**
740 	 * @cpu_offline: A CPU is going offline
741 	 * @cpu: CPU which is going offline
742 	 *
743 	 * @cpu is going offline. @cpu will not call ops.enqueue() or
744 	 * ops.dispatch(), nor run tasks associated with other CPUs afterwards.
745 	 */
746 	void (*cpu_offline)(s32 cpu);
747 
748 	/*
749 	 * All CPU hotplug ops must come before ops.init().
750 	 */
751 
752 	/**
753 	 * @init: Initialize the BPF scheduler
754 	 */
755 	s32 (*init)(void);
756 
757 	/**
758 	 * @exit: Clean up after the BPF scheduler
759 	 * @info: Exit info
760 	 *
761 	 * ops.exit() is also called on ops.init() failure, which is a bit
762 	 * unusual. This is to allow rich reporting through @info on how
763 	 * ops.init() failed.
764 	 */
765 	void (*exit)(struct scx_exit_info *info);
766 
767 	/*
768 	 * Data fields must comes after all ops fields.
769 	 */
770 
771 	/**
772 	 * @dispatch_max_batch: Max nr of tasks that dispatch() can dispatch
773 	 */
774 	u32 dispatch_max_batch;
775 
776 	/**
777 	 * @flags: %SCX_OPS_* flags
778 	 */
779 	u64 flags;
780 
781 	/**
782 	 * @timeout_ms: The maximum amount of time, in milliseconds, that a
783 	 * runnable task should be able to wait before being scheduled. The
784 	 * maximum timeout may not exceed the default timeout of 30 seconds.
785 	 *
786 	 * Defaults to the maximum allowed timeout value of 30 seconds.
787 	 */
788 	u32 timeout_ms;
789 
790 	/**
791 	 * @exit_dump_len: scx_exit_info.dump buffer length. If 0, the default
792 	 * value of 32768 is used.
793 	 */
794 	u32 exit_dump_len;
795 
796 	/**
797 	 * @hotplug_seq: A sequence number that may be set by the scheduler to
798 	 * detect when a hotplug event has occurred during the loading process.
799 	 * If 0, no detection occurs. Otherwise, the scheduler will fail to
800 	 * load if the sequence number does not match @scx_hotplug_seq on the
801 	 * enable path.
802 	 */
803 	u64 hotplug_seq;
804 
805 	/**
806 	 * @cgroup_id: When >1, attach the scheduler as a sub-scheduler on the
807 	 * specified cgroup.
808 	 */
809 	u64 sub_cgroup_id;
810 
811 	/**
812 	 * @name: BPF scheduler's name
813 	 *
814 	 * Must be a non-zero valid BPF object name including only isalnum(),
815 	 * '_' and '.' chars. Shows up in kernel.sched_ext_ops sysctl while the
816 	 * BPF scheduler is enabled.
817 	 */
818 	char name[SCX_OPS_NAME_LEN];
819 
820 	/* internal use only, must be NULL */
821 	void __rcu *priv;
822 
823 	/*
824 	 * Deprecated callbacks. Kept at the end of the struct so the cid-form
825 	 * struct (sched_ext_ops_cid) can omit them without affecting the
826 	 * shared field offsets. Use SCX_ENQ_IMMED instead. Sitting past
827 	 * SCX_OPI_END means has_op doesn't cover them, so SCX_HAS_OP() cannot
828 	 * be used; callers must test sch->ops.cpu_acquire / cpu_release
829 	 * directly.
830 	 */
831 
832 	/**
833 	 * @cpu_acquire: A CPU is becoming available to the BPF scheduler
834 	 * @cpu: The CPU being acquired by the BPF scheduler.
835 	 * @args: Acquire arguments, see the struct definition.
836 	 *
837 	 * A CPU that was previously released from the BPF scheduler is now once
838 	 * again under its control. Deprecated; use SCX_ENQ_IMMED instead.
839 	 */
840 	void (*cpu_acquire)(s32 cpu, struct scx_cpu_acquire_args *args);
841 
842 	/**
843 	 * @cpu_release: A CPU is taken away from the BPF scheduler
844 	 * @cpu: The CPU being released by the BPF scheduler.
845 	 * @args: Release arguments, see the struct definition.
846 	 *
847 	 * The specified CPU is no longer under the control of the BPF
848 	 * scheduler. This could be because it was preempted by a higher
849 	 * priority sched_class, though there may be other reasons as well. The
850 	 * caller should consult @args->reason to determine the cause.
851 	 * Deprecated; use SCX_ENQ_IMMED instead.
852 	 */
853 	void (*cpu_release)(s32 cpu, struct scx_cpu_release_args *args);
854 };
855 
856 /**
857  * struct sched_ext_ops_cid - cid-form alternative to struct sched_ext_ops
858  *
859  * Mirrors struct sched_ext_ops with cpu/cpumask substituted with cid/cmask
860  * where applicable. Layout up to and including @priv matches sched_ext_ops
861  * byte-for-byte (verified by BUILD_BUG_ON checks at scx_init() time) so
862  * shared field offsets work for both struct types in bpf_scx_init_member()
863  * and bpf_scx_check_member(). The deprecated cpu_acquire/cpu_release
864  * callbacks at the tail of sched_ext_ops are omitted here entirely.
865  *
866  * Differences from sched_ext_ops:
867  *   - select_cpu       -> select_cid (returns cid)
868  *   - dispatch         -> dispatch (cpu arg is now cid)
869  *   - update_idle      -> update_idle (cpu arg is now cid)
870  *   - set_cpumask      -> set_cmask (cmask instead of cpumask)
871  *   - cpu_online       -> cid_online
872  *   - cpu_offline      -> cid_offline
873  *   - dump_cpu         -> dump_cid
874  *   - cpu_acquire/cpu_release  -> not present (deprecated in sched_ext_ops)
875  *
876  * BPF schedulers using this type cannot call cpu-form scx_bpf_* kfuncs;
877  * use the cid-form variants instead. Enforced at BPF verifier time via
878  * scx_kfunc_context_filter() branching on prog->aux->st_ops.
879  *
880  * See sched_ext_ops for callback documentation.
881  */
882 struct sched_ext_ops_cid {
883 	s32 (*select_cid)(struct task_struct *p, s32 prev_cid, u64 wake_flags);
884 	void (*enqueue)(struct task_struct *p, u64 enq_flags);
885 	void (*dequeue)(struct task_struct *p, u64 deq_flags);
886 	void (*dispatch)(s32 cid, struct task_struct *prev);
887 	void (*tick)(struct task_struct *p);
888 	void (*runnable)(struct task_struct *p, u64 enq_flags);
889 	void (*running)(struct task_struct *p);
890 	void (*stopping)(struct task_struct *p, bool runnable);
891 	void (*quiescent)(struct task_struct *p, u64 deq_flags);
892 	bool (*yield)(struct task_struct *from, struct task_struct *to);
893 	bool (*core_sched_before)(struct task_struct *a,
894 				   struct task_struct *b);
895 	void (*set_weight)(struct task_struct *p, u32 weight);
896 	void (*set_cmask)(struct task_struct *p,
897 			   const struct scx_cmask *cmask);
898 	void (*update_idle)(s32 cid, bool idle);
899 	s32 (*init_task)(struct task_struct *p,
900 			  struct scx_init_task_args *args);
901 	void (*exit_task)(struct task_struct *p,
902 			   struct scx_exit_task_args *args);
903 	void (*enable)(struct task_struct *p);
904 	void (*disable)(struct task_struct *p);
905 	void (*dump)(struct scx_dump_ctx *ctx);
906 	void (*dump_cid)(struct scx_dump_ctx *ctx, s32 cid, bool idle);
907 	void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p);
908 #ifdef CONFIG_EXT_GROUP_SCHED
909 	s32 (*cgroup_init)(struct cgroup *cgrp,
910 			    struct scx_cgroup_init_args *args);
911 	void (*cgroup_exit)(struct cgroup *cgrp);
912 	s32 (*cgroup_prep_move)(struct task_struct *p,
913 				 struct cgroup *from, struct cgroup *to);
914 	void (*cgroup_move)(struct task_struct *p,
915 			     struct cgroup *from, struct cgroup *to);
916 	void (*cgroup_cancel_move)(struct task_struct *p,
917 				    struct cgroup *from, struct cgroup *to);
918 	void (*cgroup_set_weight)(struct cgroup *cgrp, u32 weight);
919 	void (*cgroup_set_bandwidth)(struct cgroup *cgrp,
920 				      u64 period_us, u64 quota_us, u64 burst_us);
921 	void (*cgroup_set_idle)(struct cgroup *cgrp, bool idle);
922 #endif	/* CONFIG_EXT_GROUP_SCHED */
923 	s32 (*sub_attach)(struct scx_sub_attach_args *args);
924 	void (*sub_detach)(struct scx_sub_detach_args *args);
925 	void (*cid_online)(s32 cid);
926 	void (*cid_offline)(s32 cid);
927 	s32 (*init)(void);
928 	void (*exit)(struct scx_exit_info *info);
929 
930 	/* Data fields - must match sched_ext_ops layout exactly */
931 	u32 dispatch_max_batch;
932 	u64 flags;
933 	u32 timeout_ms;
934 	u32 exit_dump_len;
935 	u64 hotplug_seq;
936 	u64 sub_cgroup_id;
937 	char name[SCX_OPS_NAME_LEN];
938 
939 	/* internal use only, must be NULL */
940 	void __rcu *priv;
941 
942 	/* layout end anchor for the BUILD_BUG_ON in scx_init(); keep last */
943 	char __end[0];
944 };
945 
946 enum scx_opi {
947 	SCX_OPI_BEGIN			= 0,
948 	SCX_OPI_NORMAL_BEGIN		= 0,
949 	SCX_OPI_NORMAL_END		= SCX_OP_IDX(cpu_online),
950 	SCX_OPI_CPU_HOTPLUG_BEGIN	= SCX_OP_IDX(cpu_online),
951 	SCX_OPI_CPU_HOTPLUG_END		= SCX_OP_IDX(init),
952 	SCX_OPI_END			= SCX_OP_IDX(init),
953 };
954 
955 /*
956  * Collection of event counters. Event types are placed in descending order.
957  */
958 struct scx_event_stats {
959 	/*
960 	 * If ops.select_cpu() returns a CPU which can't be used by the task,
961 	 * the core scheduler code silently picks a fallback CPU.
962 	 */
963 	s64		SCX_EV_SELECT_CPU_FALLBACK;
964 
965 	/*
966 	 * When dispatching to a local DSQ, the CPU may have gone offline in
967 	 * the meantime. In this case, the task is bounced to the global DSQ.
968 	 */
969 	s64		SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE;
970 
971 	/*
972 	 * If SCX_OPS_ENQ_LAST is not set, the number of times that a task
973 	 * continued to run because there were no other tasks on the CPU.
974 	 */
975 	s64		SCX_EV_DISPATCH_KEEP_LAST;
976 
977 	/*
978 	 * If SCX_OPS_ENQ_EXITING is not set, the number of times that a task
979 	 * is dispatched to a local DSQ when exiting.
980 	 */
981 	s64		SCX_EV_ENQ_SKIP_EXITING;
982 
983 	/*
984 	 * If SCX_OPS_ENQ_MIGRATION_DISABLED is not set, the number of times a
985 	 * migration disabled task skips ops.enqueue() and is dispatched to its
986 	 * local DSQ.
987 	 */
988 	s64		SCX_EV_ENQ_SKIP_MIGRATION_DISABLED;
989 
990 	/*
991 	 * The number of times a task, enqueued on a local DSQ with
992 	 * SCX_ENQ_IMMED, was re-enqueued because the CPU was not available for
993 	 * immediate execution.
994 	 */
995 	s64		SCX_EV_REENQ_IMMED;
996 
997 	/*
998 	 * The number of times a reenq of local DSQ caused another reenq of
999 	 * local DSQ. This can happen when %SCX_ENQ_IMMED races against a higher
1000 	 * priority class task even if the BPF scheduler always satisfies the
1001 	 * prerequisites for %SCX_ENQ_IMMED at the time of enqueue. However,
1002 	 * that scenario is very unlikely and this count going up regularly
1003 	 * indicates that the BPF scheduler is handling %SCX_ENQ_REENQ
1004 	 * incorrectly causing recursive reenqueues.
1005 	 */
1006 	s64		SCX_EV_REENQ_LOCAL_REPEAT;
1007 
1008 	/*
1009 	 * Total number of times a task's time slice was refilled with the
1010 	 * default value (SCX_SLICE_DFL).
1011 	 */
1012 	s64		SCX_EV_REFILL_SLICE_DFL;
1013 
1014 	/*
1015 	 * The total duration of bypass modes in nanoseconds.
1016 	 */
1017 	s64		SCX_EV_BYPASS_DURATION;
1018 
1019 	/*
1020 	 * The number of tasks dispatched in the bypassing mode.
1021 	 */
1022 	s64		SCX_EV_BYPASS_DISPATCH;
1023 
1024 	/*
1025 	 * The number of times the bypassing mode has been activated.
1026 	 */
1027 	s64		SCX_EV_BYPASS_ACTIVATE;
1028 
1029 	/*
1030 	 * The number of times the scheduler attempted to insert a task that it
1031 	 * doesn't own into a DSQ. Such attempts are ignored.
1032 	 *
1033 	 * As BPF schedulers are allowed to ignore dequeues, it's difficult to
1034 	 * tell whether such an attempt is from a scheduler malfunction or an
1035 	 * ignored dequeue around sub-sched enabling. If this count keeps going
1036 	 * up regardless of sub-sched enabling, it likely indicates a bug in the
1037 	 * scheduler.
1038 	 */
1039 	s64		SCX_EV_INSERT_NOT_OWNED;
1040 
1041 	/*
1042 	 * The number of times tasks from bypassing descendants are scheduled
1043 	 * from sub_bypass_dsq's.
1044 	 */
1045 	s64		SCX_EV_SUB_BYPASS_DISPATCH;
1046 };
1047 
1048 struct scx_sched;
1049 
1050 enum scx_sched_pcpu_flags {
1051 	SCX_SCHED_PCPU_BYPASSING	= 1LLU << 0,
1052 };
1053 
1054 /* dispatch buf */
1055 struct scx_dsp_buf_ent {
1056 	struct task_struct	*task;
1057 	unsigned long		qseq;
1058 	u64			dsq_id;
1059 	u64			enq_flags;
1060 };
1061 
1062 struct scx_dsp_ctx {
1063 	struct rq		*rq;
1064 	u32			cursor;
1065 	u32			nr_tasks;
1066 	struct scx_dsp_buf_ent	buf[];
1067 };
1068 
1069 struct scx_deferred_reenq_local {
1070 	struct list_head	node;
1071 	u64			flags;
1072 	u64			seq;
1073 	u32			cnt;
1074 };
1075 
1076 struct scx_sched_pcpu {
1077 	struct scx_sched	*sch;
1078 	u64			flags;	/* protected by rq lock */
1079 
1080 	/*
1081 	 * The event counters are in a per-CPU variable to minimize the
1082 	 * accounting overhead. A system-wide view on the event counter is
1083 	 * constructed when requested by scx_bpf_events().
1084 	 */
1085 	struct scx_event_stats	event_stats;
1086 
1087 	struct scx_deferred_reenq_local deferred_reenq_local;
1088 	struct scx_dispatch_q	bypass_dsq;
1089 #ifdef CONFIG_EXT_SUB_SCHED
1090 	u32			bypass_host_seq;
1091 #endif
1092 
1093 	/* must be the last entry - contains flex array */
1094 	struct scx_dsp_ctx	dsp_ctx;
1095 };
1096 
1097 struct scx_sched_pnode {
1098 	struct scx_dispatch_q	global_dsq;
1099 };
1100 
1101 struct scx_sched {
1102 	/*
1103 	 * cpu-form and cid-form ops share field offsets up to .priv (verified
1104 	 * by BUILD_BUG_ON in scx_init()). The anonymous union lets the kernel
1105 	 * access either view of the same storage without function-pointer
1106 	 * casts: use .ops for cpu-form and shared fields, .ops_cid for the
1107 	 * cid-renamed callbacks (set_cmask, select_cid, cid_online, ...).
1108 	 */
1109 	union {
1110 		struct sched_ext_ops		ops;
1111 		struct sched_ext_ops_cid	ops_cid;
1112 	};
1113 	bool			is_cid_type;	/* true if registered via bpf_sched_ext_ops_cid */
1114 
1115 	/*
1116 	 * Arena map auto-discovered from member progs at struct_ops attach.
1117 	 * cid-form schedulers must use exactly one arena across all member
1118 	 * progs. NULL on cpu-form.
1119 	 *
1120 	 * @arena_pool sub-allocates @arena_map. Each gen_pool chunk is added
1121 	 * at the kernel-side mapping address. @arena_kern_base is the start
1122 	 * of the arena's kern_vm range. See scx_arena_to_kaddr() and
1123 	 * scx_kaddr_to_arena().
1124 	 */
1125 	struct bpf_map		*arena_map;
1126 	struct gen_pool		*arena_pool;
1127 	uintptr_t		arena_kern_base;
1128 
1129 	/*
1130 	 * Per-CPU arena cmask used by scx_call_op_set_cpumask() to hand a cmask
1131 	 * to ops_cid.set_cmask(). The kernel writes through the stored kern_va
1132 	 * and hands BPF its arena pointer via scx_kaddr_to_arena().
1133 	 */
1134 	struct scx_cmask * __percpu *set_cmask_scratch;
1135 
1136 	DECLARE_BITMAP(has_op, SCX_OPI_END);
1137 
1138 	/*
1139 	 * Dispatch queues.
1140 	 *
1141 	 * The global DSQ (%SCX_DSQ_GLOBAL) is split per-node for scalability.
1142 	 * This is to avoid live-locking in bypass mode where all tasks are
1143 	 * dispatched to %SCX_DSQ_GLOBAL and all CPUs consume from it. If
1144 	 * per-node split isn't sufficient, it can be further split.
1145 	 */
1146 	struct rhashtable	dsq_hash;
1147 	struct scx_sched_pnode	**pnode;
1148 	struct scx_sched_pcpu __percpu *pcpu;
1149 
1150 	u64			slice_dfl;
1151 	u64			bypass_timestamp;
1152 	s32			bypass_depth;
1153 
1154 	/* bypass dispatch path enable state, see bypass_dsp_enabled() */
1155 	unsigned long		bypass_dsp_claim;
1156 	atomic_t		bypass_dsp_enable_depth;
1157 
1158 	bool			aborting;
1159 	bool			dump_disabled;	/* protected by scx_dump_lock */
1160 	u32			dsp_max_batch;
1161 	s32			level;
1162 
1163 	/*
1164 	 * Updates to the following warned bitfields can race causing RMW issues
1165 	 * but it doesn't really matter.
1166 	 */
1167 	bool			warned_zero_slice:1;
1168 	bool			warned_deprecated_rq:1;
1169 	bool			warned_unassoc_progs:1;
1170 
1171 	struct list_head	all;
1172 
1173 #ifdef CONFIG_EXT_SUB_SCHED
1174 	struct rhash_head	hash_node;
1175 
1176 	struct list_head	children;
1177 	struct list_head	sibling;
1178 	struct cgroup		*cgrp;
1179 	char			*cgrp_path;
1180 	struct kset		*sub_kset;
1181 
1182 	bool			sub_attached;
1183 #endif	/* CONFIG_EXT_SUB_SCHED */
1184 
1185 	/*
1186 	 * The maximum amount of time in jiffies that a task may be runnable
1187 	 * without being scheduled on a CPU. If this timeout is exceeded, it
1188 	 * will trigger scx_error().
1189 	 */
1190 	unsigned long		watchdog_timeout;
1191 
1192 	atomic_t		exit_kind;
1193 	struct scx_exit_info	*exit_info;
1194 
1195 	struct kobject		kobj;
1196 
1197 	struct kthread_worker	*helper;
1198 	struct irq_work		disable_irq_work;
1199 	struct kthread_work	disable_work;
1200 	struct timer_list	bypass_lb_timer;
1201 	cpumask_var_t		bypass_lb_donee_cpumask;
1202 	cpumask_var_t		bypass_lb_resched_cpumask;
1203 	struct rcu_work		rcu_work;
1204 
1205 	/* all ancestors including self */
1206 	struct scx_sched	*ancestors[];
1207 };
1208 
1209 /**
1210  * scx_arena_to_kaddr - Translate a BPF-arena pointer to its kernel address
1211  * @sch: scheduler whose arena hosts @bpf_ptr
1212  * @bpf_ptr: BPF-arena pointer, only the low 32 bits are used
1213  *
1214  * The (u32) cast normalizes any input into the arena's 4 GiB kern_vm range,
1215  * which combined with scratch-page fault recovery makes the returned pointer
1216  * safe to dereference up to GUARD_SZ / 2 past the intended object. Accesses
1217  * larger than GUARD_SZ / 2 must be explicitly bounds-checked.
1218  */
1219 static inline void *scx_arena_to_kaddr(struct scx_sched *sch, const void *bpf_ptr)
1220 {
1221 	return (void *)(sch->arena_kern_base + (u32)(uintptr_t)bpf_ptr);
1222 }
1223 
1224 /**
1225  * scx_kaddr_to_arena - Translate a kernel arena address to its BPF form
1226  * @sch: scheduler whose arena hosts @kaddr
1227  * @kaddr: kernel-side arena address, supplied by trusted kernel code
1228  */
1229 static inline void *scx_kaddr_to_arena(struct scx_sched *sch, const void *kaddr)
1230 {
1231 	return (void *)((uintptr_t)kaddr - sch->arena_kern_base);
1232 }
1233 
1234 enum scx_wake_flags {
1235 	/* expose select WF_* flags as enums */
1236 	SCX_WAKE_FORK		= WF_FORK,
1237 	SCX_WAKE_TTWU		= WF_TTWU,
1238 	SCX_WAKE_SYNC		= WF_SYNC,
1239 };
1240 
1241 enum scx_enq_flags {
1242 	/* expose select ENQUEUE_* flags as enums */
1243 	SCX_ENQ_WAKEUP		= ENQUEUE_WAKEUP,
1244 	SCX_ENQ_HEAD		= ENQUEUE_HEAD,
1245 	SCX_ENQ_CPU_SELECTED	= ENQUEUE_RQ_SELECTED,
1246 
1247 	/* high 32bits are SCX specific */
1248 
1249 	/*
1250 	 * Set the following to trigger preemption when calling
1251 	 * scx_bpf_dsq_insert() with a local dsq as the target. The slice of the
1252 	 * current task is cleared to zero and the CPU is kicked into the
1253 	 * scheduling path. Implies %SCX_ENQ_HEAD.
1254 	 */
1255 	SCX_ENQ_PREEMPT		= 1LLU << 32,
1256 
1257 	/*
1258 	 * Only allowed on local DSQs. Guarantees that the task either gets
1259 	 * on the CPU immediately and stays on it, or gets reenqueued back
1260 	 * to the BPF scheduler. It will never linger on a local DSQ or be
1261 	 * silently put back after preemption.
1262 	 *
1263 	 * The protection persists until the next fresh enqueue - it
1264 	 * survives SAVE/RESTORE cycles, slice extensions and preemption.
1265 	 * If the task can't stay on the CPU for any reason, it gets
1266 	 * reenqueued back to the BPF scheduler.
1267 	 *
1268 	 * Exiting and migration-disabled tasks bypass ops.enqueue() and
1269 	 * are placed directly on a local DSQ without IMMED protection
1270 	 * unless %SCX_OPS_ENQ_EXITING and %SCX_OPS_ENQ_MIGRATION_DISABLED
1271 	 * are set respectively.
1272 	 */
1273 	SCX_ENQ_IMMED		= 1LLU << 33,
1274 
1275 	/*
1276 	 * The task being enqueued was previously enqueued on a DSQ, but was
1277 	 * removed and is being re-enqueued. See SCX_TASK_REENQ_* flags to find
1278 	 * out why a given task is being reenqueued.
1279 	 */
1280 	SCX_ENQ_REENQ		= 1LLU << 40,
1281 
1282 	/*
1283 	 * The task being enqueued is the only task available for the cpu. By
1284 	 * default, ext core keeps executing such tasks but when
1285 	 * %SCX_OPS_ENQ_LAST is specified, they're ops.enqueue()'d with the
1286 	 * %SCX_ENQ_LAST flag set.
1287 	 *
1288 	 * The BPF scheduler is responsible for triggering a follow-up
1289 	 * scheduling event. Otherwise, Execution may stall.
1290 	 */
1291 	SCX_ENQ_LAST		= 1LLU << 41,
1292 
1293 	/* high 8 bits are internal */
1294 	__SCX_ENQ_INTERNAL_MASK	= 0xffLLU << 56,
1295 
1296 	SCX_ENQ_CLEAR_OPSS	= 1LLU << 56,
1297 	SCX_ENQ_DSQ_PRIQ	= 1LLU << 57,
1298 	SCX_ENQ_NESTED		= 1LLU << 58,
1299 	SCX_ENQ_GDSQ_FALLBACK	= 1LLU << 59,	/* fell back to global DSQ */
1300 };
1301 
1302 enum scx_deq_flags {
1303 	/* expose select DEQUEUE_* flags as enums */
1304 	SCX_DEQ_SLEEP		= DEQUEUE_SLEEP,
1305 
1306 	/* high 32bits are SCX specific */
1307 
1308 	/*
1309 	 * The generic core-sched layer decided to execute the task even though
1310 	 * it hasn't been dispatched yet. Dequeue from the BPF side.
1311 	 */
1312 	SCX_DEQ_CORE_SCHED_EXEC	= 1LLU << 32,
1313 
1314 	/*
1315 	 * The task is being dequeued due to a property change (e.g.,
1316 	 * sched_setaffinity(), sched_setscheduler(), set_user_nice(),
1317 	 * etc.).
1318 	 */
1319 	SCX_DEQ_SCHED_CHANGE	= 1LLU << 33,
1320 };
1321 
1322 enum scx_reenq_flags {
1323 	/* low 16bits determine which tasks should be reenqueued */
1324 	SCX_REENQ_ANY		= 1LLU << 0,	/* all tasks */
1325 
1326 	__SCX_REENQ_FILTER_MASK	= 0xffffLLU,
1327 
1328 	__SCX_REENQ_USER_MASK	= SCX_REENQ_ANY,
1329 
1330 	/* bits 32-35 used by task_should_reenq() */
1331 	SCX_REENQ_TSR_RQ_OPEN	= 1LLU << 32,
1332 	SCX_REENQ_TSR_NOT_FIRST	= 1LLU << 33,
1333 
1334 	__SCX_REENQ_TSR_MASK	= 0xfLLU << 32,
1335 };
1336 
1337 enum scx_pick_idle_cpu_flags {
1338 	SCX_PICK_IDLE_CORE	= 1LLU << 0,	/* pick a CPU whose SMT siblings are also idle */
1339 	SCX_PICK_IDLE_IN_NODE	= 1LLU << 1,	/* pick a CPU in the same target NUMA node */
1340 };
1341 
1342 enum scx_kick_flags {
1343 	/*
1344 	 * Kick the target CPU if idle. Guarantees that the target CPU goes
1345 	 * through at least one full scheduling cycle before going idle. If the
1346 	 * target CPU can be determined to be currently not idle and going to go
1347 	 * through a scheduling cycle before going idle, noop.
1348 	 */
1349 	SCX_KICK_IDLE		= 1LLU << 0,
1350 
1351 	/*
1352 	 * Preempt the current task and execute the dispatch path. If the
1353 	 * current task of the target CPU is an SCX task, its ->scx.slice is
1354 	 * cleared to zero before the scheduling path is invoked so that the
1355 	 * task expires and the dispatch path is invoked.
1356 	 */
1357 	SCX_KICK_PREEMPT	= 1LLU << 1,
1358 
1359 	/*
1360 	 * The scx_bpf_kick_cpu() call will return after the current SCX task of
1361 	 * the target CPU switches out. This can be used to implement e.g. core
1362 	 * scheduling. This has no effect if the current task on the target CPU
1363 	 * is not on SCX.
1364 	 */
1365 	SCX_KICK_WAIT		= 1LLU << 2,
1366 };
1367 
1368 enum scx_tg_flags {
1369 	SCX_TG_ONLINE		= 1U << 0,
1370 	SCX_TG_INITED		= 1U << 1,
1371 };
1372 
1373 enum scx_enable_state {
1374 	SCX_ENABLING,
1375 	SCX_ENABLED,
1376 	SCX_DISABLING,
1377 	SCX_DISABLED,
1378 };
1379 
1380 static const char *scx_enable_state_str[] = {
1381 	[SCX_ENABLING]		= "enabling",
1382 	[SCX_ENABLED]		= "enabled",
1383 	[SCX_DISABLING]		= "disabling",
1384 	[SCX_DISABLED]		= "disabled",
1385 };
1386 
1387 /*
1388  * Task Ownership State Machine (sched_ext_entity->ops_state)
1389  *
1390  * The sched_ext core uses this state machine to track task ownership
1391  * between the SCX core and the BPF scheduler. This allows the BPF
1392  * scheduler to dispatch tasks without strict ordering requirements, while
1393  * the SCX core safely rejects invalid dispatches.
1394  *
1395  * State Transitions
1396  *
1397  *       .------------> NONE (owned by SCX core)
1398  *       |               |           ^
1399  *       |       enqueue |           | direct dispatch
1400  *       |               v           |
1401  *       |           QUEUEING -------'
1402  *       |               |
1403  *       |       enqueue |
1404  *       |     completes |
1405  *       |               v
1406  *       |            QUEUED (owned by BPF scheduler)
1407  *       |               |
1408  *       |      dispatch |
1409  *       |               |
1410  *       |               v
1411  *       |          DISPATCHING
1412  *       |               |
1413  *       |      dispatch |
1414  *       |     completes |
1415  *       `---------------'
1416  *
1417  * State Descriptions
1418  *
1419  * - %SCX_OPSS_NONE:
1420  *     Task is owned by the SCX core. It's either on a run queue, running,
1421  *     or being manipulated by the core scheduler. The BPF scheduler has no
1422  *     claim on this task.
1423  *
1424  * - %SCX_OPSS_QUEUEING:
1425  *     Transitional state while transferring a task from the SCX core to
1426  *     the BPF scheduler. The task's rq lock is held during this state.
1427  *     Since QUEUEING is both entered and exited under the rq lock, dequeue
1428  *     can never observe this state (it would be a BUG). When finishing a
1429  *     dispatch, if the task is still in %SCX_OPSS_QUEUEING the completion
1430  *     path busy-waits for it to leave this state (via wait_ops_state())
1431  *     before retrying.
1432  *
1433  * - %SCX_OPSS_QUEUED:
1434  *     Task is owned by the BPF scheduler. It's on a DSQ (dispatch queue)
1435  *     and the BPF scheduler is responsible for dispatching it. A QSEQ
1436  *     (queue sequence number) is embedded in this state to detect
1437  *     dispatch/dequeue races: if a task is dequeued and re-enqueued, the
1438  *     QSEQ changes and any in-flight dispatch operations targeting the old
1439  *     QSEQ are safely ignored.
1440  *
1441  * - %SCX_OPSS_DISPATCHING:
1442  *     Transitional state while transferring a task from the BPF scheduler
1443  *     back to the SCX core. This state indicates the BPF scheduler has
1444  *     selected the task for execution. When dequeue needs to take the task
1445  *     off a DSQ and it is still in %SCX_OPSS_DISPATCHING, the dequeue path
1446  *     busy-waits for it to leave this state (via wait_ops_state()) before
1447  *     proceeding. Exits to %SCX_OPSS_NONE when dispatch completes.
1448  *
1449  * Memory Ordering
1450  *
1451  * Transitions out of %SCX_OPSS_QUEUEING and %SCX_OPSS_DISPATCHING into
1452  * %SCX_OPSS_NONE or %SCX_OPSS_QUEUED must use atomic_long_set_release()
1453  * and waiters must use atomic_long_read_acquire(). This ensures proper
1454  * synchronization between concurrent operations.
1455  *
1456  * Cross-CPU Task Migration
1457  *
1458  * When moving a task in the %SCX_OPSS_DISPATCHING state, we can't simply
1459  * grab the target CPU's rq lock because a concurrent dequeue might be
1460  * waiting on %SCX_OPSS_DISPATCHING while holding the source rq lock
1461  * (deadlock).
1462  *
1463  * The sched_ext core uses a "lock dancing" protocol coordinated by
1464  * p->scx.holding_cpu. When moving a task to a different rq:
1465  *
1466  *   1. Verify task can be moved (CPU affinity, migration_disabled, etc.)
1467  *   2. Set p->scx.holding_cpu to the current CPU
1468  *   3. Set task state to %SCX_OPSS_NONE; dequeue waits while DISPATCHING
1469  *      is set, so clearing DISPATCHING first prevents the circular wait
1470  *      (safe to lock the rq we need)
1471  *   4. Unlock the current CPU's rq
1472  *   5. Lock src_rq (where the task currently lives)
1473  *   6. Verify p->scx.holding_cpu == current CPU, if not, dequeue won the
1474  *      race (dequeue clears holding_cpu to -1 when it takes the task), in
1475  *      this case migration is aborted
1476  *   7. If src_rq == dst_rq: clear holding_cpu and enqueue directly
1477  *      into dst_rq's local DSQ (no lock swap needed)
1478  *   8. Otherwise: call move_remote_task_to_local_dsq(), which releases
1479  *      src_rq, locks dst_rq, and performs the deactivate/activate
1480  *      migration cycle (dst_rq is held on return)
1481  *   9. Unlock dst_rq and re-lock the current CPU's rq to restore
1482  *      the lock state expected by the caller
1483  *
1484  * If any verification fails, abort the migration.
1485  *
1486  * This state tracking allows the BPF scheduler to try to dispatch any task
1487  * at any time regardless of its state. The SCX core can safely
1488  * reject/ignore invalid dispatches, simplifying the BPF scheduler
1489  * implementation.
1490  */
1491 enum scx_ops_state {
1492 	SCX_OPSS_NONE,		/* owned by the SCX core */
1493 	SCX_OPSS_QUEUEING,	/* in transit to the BPF scheduler */
1494 	SCX_OPSS_QUEUED,	/* owned by the BPF scheduler */
1495 	SCX_OPSS_DISPATCHING,	/* in transit back to the SCX core */
1496 
1497 	/*
1498 	 * QSEQ brands each QUEUED instance so that, when dispatch races
1499 	 * dequeue/requeue, the dispatcher can tell whether it still has a claim
1500 	 * on the task being dispatched.
1501 	 *
1502 	 * As some 32bit archs can't do 64bit store_release/load_acquire,
1503 	 * p->scx.ops_state is atomic_long_t which leaves 30 bits for QSEQ on
1504 	 * 32bit machines. The dispatch race window QSEQ protects is very narrow
1505 	 * and runs with IRQ disabled. 30 bits should be sufficient.
1506 	 */
1507 	SCX_OPSS_QSEQ_SHIFT	= 2,
1508 };
1509 
1510 /* Use macros to ensure that the type is unsigned long for the masks */
1511 #define SCX_OPSS_STATE_MASK	((1LU << SCX_OPSS_QSEQ_SHIFT) - 1)
1512 #define SCX_OPSS_QSEQ_MASK	(~SCX_OPSS_STATE_MASK)
1513 
1514 extern struct scx_sched __rcu *scx_root;
1515 DECLARE_PER_CPU(struct rq *, scx_locked_rq_state);
1516 
1517 /*
1518  * True when the currently loaded scheduler hierarchy is cid-form. All scheds
1519  * in a hierarchy share one form, so this single key tells callsites which
1520  * view to use without per-sch dereferences. Use scx_is_cid_type() to test.
1521  */
1522 DECLARE_STATIC_KEY_FALSE(__scx_is_cid_type);
1523 
1524 int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id);
1525 
1526 bool scx_cpu_valid(struct scx_sched *sch, s32 cpu, const char *where);
1527 
1528 __printf(5, 0) bool scx_vexit(struct scx_sched *sch, enum scx_exit_kind kind,
1529 			      s64 exit_code, s32 exit_cpu, const char *fmt,
1530 			      va_list args);
1531 __printf(5, 6) bool __scx_exit(struct scx_sched *sch, enum scx_exit_kind kind,
1532 			       s64 exit_code, s32 exit_cpu, const char *fmt, ...);
1533 
1534 #define scx_exit(sch, kind, exit_code, fmt, args...)				\
1535 	__scx_exit(sch, kind, exit_code, raw_smp_processor_id(), fmt, ##args)
1536 #define scx_error(sch, fmt, args...)						\
1537 	scx_exit((sch), SCX_EXIT_ERROR, 0, fmt, ##args)
1538 #define scx_verror(sch, fmt, args)						\
1539 	scx_vexit((sch), SCX_EXIT_ERROR, 0, raw_smp_processor_id(), fmt, args)
1540 
1541 /*
1542  * Return the rq currently locked from an scx callback, or NULL if no rq is
1543  * locked.
1544  */
1545 static inline struct rq *scx_locked_rq(void)
1546 {
1547 	return __this_cpu_read(scx_locked_rq_state);
1548 }
1549 
1550 static inline bool scx_bypassing(struct scx_sched *sch, s32 cpu)
1551 {
1552 	return unlikely(per_cpu_ptr(sch->pcpu, cpu)->flags &
1553 			SCX_SCHED_PCPU_BYPASSING);
1554 }
1555 
1556 #ifdef CONFIG_EXT_SUB_SCHED
1557 /**
1558  * scx_task_sched - Find scx_sched scheduling a task
1559  * @p: task of interest
1560  *
1561  * Return @p's scheduler instance. Must be called with @p's pi_lock or rq lock
1562  * held.
1563  */
1564 static inline struct scx_sched *scx_task_sched(const struct task_struct *p)
1565 {
1566 	return rcu_dereference_protected(p->scx.sched,
1567 					 lockdep_is_held(&p->pi_lock) ||
1568 					 lockdep_is_held(__rq_lockp(task_rq(p))));
1569 }
1570 
1571 /**
1572  * scx_task_sched_rcu - Find scx_sched scheduling a task
1573  * @p: task of interest
1574  *
1575  * Return @p's scheduler instance. The returned scx_sched is RCU protected.
1576  */
1577 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p)
1578 {
1579 	return rcu_dereference_all(p->scx.sched);
1580 }
1581 
1582 /**
1583  * scx_task_on_sched - Is a task on the specified sched?
1584  * @sch: sched to test against
1585  * @p: task of interest
1586  *
1587  * Returns %true if @p is on @sch, %false otherwise.
1588  */
1589 static inline bool scx_task_on_sched(struct scx_sched *sch,
1590 				     const struct task_struct *p)
1591 {
1592 	return rcu_access_pointer(p->scx.sched) == sch;
1593 }
1594 
1595 /**
1596  * scx_prog_sched - Find scx_sched associated with a BPF prog
1597  * @aux: aux passed in from BPF to a kfunc
1598  *
1599  * To be called from kfuncs. Return the scheduler instance associated with the
1600  * BPF program given the implicit kfunc argument aux. The returned scx_sched is
1601  * RCU protected.
1602  */
1603 static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux)
1604 {
1605 	struct sched_ext_ops *ops;
1606 	struct scx_sched *root;
1607 
1608 	ops = bpf_prog_get_assoc_struct_ops(aux);
1609 	if (likely(ops))
1610 		return rcu_dereference_all(ops->priv);
1611 
1612 	root = rcu_dereference_all(scx_root);
1613 	if (root) {
1614 		/*
1615 		 * COMPAT-v6.19: Schedulers built before sub-sched support was
1616 		 * introduced may have unassociated non-struct_ops programs.
1617 		 */
1618 		if (!root->ops.sub_attach)
1619 			return root;
1620 
1621 		if (!root->warned_unassoc_progs) {
1622 			printk_deferred(KERN_WARNING "sched_ext: Unassociated program %s (id %d)\n",
1623 					aux->name, aux->id);
1624 			root->warned_unassoc_progs = true;
1625 		}
1626 	}
1627 
1628 	return NULL;
1629 }
1630 #else	/* CONFIG_EXT_SUB_SCHED */
1631 static inline struct scx_sched *scx_task_sched(const struct task_struct *p)
1632 {
1633 	return rcu_dereference_protected(scx_root,
1634 					 lockdep_is_held(&p->pi_lock) ||
1635 					 lockdep_is_held(__rq_lockp(task_rq(p))));
1636 }
1637 
1638 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p)
1639 {
1640 	return rcu_dereference_all(scx_root);
1641 }
1642 
1643 static inline bool scx_task_on_sched(struct scx_sched *sch,
1644 				     const struct task_struct *p)
1645 {
1646 	return true;
1647 }
1648 
1649 static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux)
1650 {
1651 	return rcu_dereference_all(scx_root);
1652 }
1653 #endif	/* CONFIG_EXT_SUB_SCHED */
1654