xref: /linux/kernel/sched/ext_internal.h (revision bec10581e92289bdc3eed17e90200900ddb00594)
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 
10 enum scx_consts {
11 	SCX_DSP_DFL_MAX_BATCH		= 32,
12 	SCX_DSP_MAX_LOOPS		= 32,
13 	SCX_WATCHDOG_MAX_TIMEOUT	= 30 * HZ,
14 
15 	SCX_EXIT_BT_LEN			= 64,
16 	SCX_EXIT_MSG_LEN		= 1024,
17 	SCX_EXIT_DUMP_DFL_LEN		= 32768,
18 
19 	SCX_CPUPERF_ONE			= SCHED_CAPACITY_SCALE,
20 
21 	/*
22 	 * Iterating all tasks may take a while. Periodically drop
23 	 * scx_tasks_lock to avoid causing e.g. CSD and RCU stalls.
24 	 */
25 	SCX_TASK_ITER_BATCH		= 32,
26 
27 	SCX_BYPASS_HOST_NTH		= 2,
28 
29 	SCX_BYPASS_LB_DFL_INTV_US	= 500 * USEC_PER_MSEC,
30 	SCX_BYPASS_LB_DONOR_PCT		= 125,
31 	SCX_BYPASS_LB_MIN_DELTA_DIV	= 4,
32 	SCX_BYPASS_LB_BATCH		= 256,
33 
34 	SCX_SUB_MAX_DEPTH		= 4,
35 };
36 
37 enum scx_exit_kind {
38 	SCX_EXIT_NONE,
39 	SCX_EXIT_DONE,
40 
41 	SCX_EXIT_UNREG = 64,	/* user-space initiated unregistration */
42 	SCX_EXIT_UNREG_BPF,	/* BPF-initiated unregistration */
43 	SCX_EXIT_UNREG_KERN,	/* kernel-initiated unregistration */
44 	SCX_EXIT_SYSRQ,		/* requested by 'S' sysrq */
45 	SCX_EXIT_PARENT,	/* parent exiting */
46 
47 	SCX_EXIT_ERROR = 1024,	/* runtime error, error msg contains details */
48 	SCX_EXIT_ERROR_BPF,	/* ERROR but triggered through scx_bpf_error() */
49 	SCX_EXIT_ERROR_STALL,	/* watchdog detected stalled runnable tasks */
50 };
51 
52 /*
53  * An exit code can be specified when exiting with scx_bpf_exit() or scx_exit(),
54  * corresponding to exit_kind UNREG_BPF and UNREG_KERN respectively. The codes
55  * are 64bit of the format:
56  *
57  *   Bits: [63  ..  48 47   ..  32 31 .. 0]
58  *         [ SYS ACT ] [ SYS RSN ] [ USR  ]
59  *
60  *   SYS ACT: System-defined exit actions
61  *   SYS RSN: System-defined exit reasons
62  *   USR    : User-defined exit codes and reasons
63  *
64  * Using the above, users may communicate intention and context by ORing system
65  * actions and/or system reasons with a user-defined exit code.
66  */
67 enum scx_exit_code {
68 	/* Reasons */
69 	SCX_ECODE_RSN_HOTPLUG	= 1LLU << 32,
70 	SCX_ECODE_RSN_CGROUP_OFFLINE = 2LLU << 32,
71 
72 	/* Actions */
73 	SCX_ECODE_ACT_RESTART	= 1LLU << 48,
74 };
75 
76 enum scx_exit_flags {
77 	/*
78 	 * ops.exit() may be called even if the loading failed before ops.init()
79 	 * finishes successfully. This is because ops.exit() allows rich exit
80 	 * info communication. The following flag indicates whether ops.init()
81 	 * finished successfully.
82 	 */
83 	SCX_EFLAG_INITIALIZED   = 1LLU << 0,
84 };
85 
86 /*
87  * scx_exit_info is passed to ops.exit() to describe why the BPF scheduler is
88  * being disabled.
89  */
90 struct scx_exit_info {
91 	/* %SCX_EXIT_* - broad category of the exit reason */
92 	enum scx_exit_kind	kind;
93 
94 	/* exit code if gracefully exiting */
95 	s64			exit_code;
96 
97 	/* %SCX_EFLAG_* */
98 	u64			flags;
99 
100 	/* textual representation of the above */
101 	const char		*reason;
102 
103 	/* backtrace if exiting due to an error */
104 	unsigned long		*bt;
105 	u32			bt_len;
106 
107 	/* informational message */
108 	char			*msg;
109 
110 	/* debug dump */
111 	char			*dump;
112 };
113 
114 /* sched_ext_ops.flags */
115 enum scx_ops_flags {
116 	/*
117 	 * Keep built-in idle tracking even if ops.update_idle() is implemented.
118 	 */
119 	SCX_OPS_KEEP_BUILTIN_IDLE	= 1LLU << 0,
120 
121 	/*
122 	 * By default, if there are no other task to run on the CPU, ext core
123 	 * keeps running the current task even after its slice expires. If this
124 	 * flag is specified, such tasks are passed to ops.enqueue() with
125 	 * %SCX_ENQ_LAST. See the comment above %SCX_ENQ_LAST for more info.
126 	 */
127 	SCX_OPS_ENQ_LAST		= 1LLU << 1,
128 
129 	/*
130 	 * An exiting task may schedule after PF_EXITING is set. In such cases,
131 	 * bpf_task_from_pid() may not be able to find the task and if the BPF
132 	 * scheduler depends on pid lookup for dispatching, the task will be
133 	 * lost leading to various issues including RCU grace period stalls.
134 	 *
135 	 * To mask this problem, by default, unhashed tasks are automatically
136 	 * dispatched to the local DSQ on enqueue. If the BPF scheduler doesn't
137 	 * depend on pid lookups and wants to handle these tasks directly, the
138 	 * following flag can be used.
139 	 */
140 	SCX_OPS_ENQ_EXITING		= 1LLU << 2,
141 
142 	/*
143 	 * If set, only tasks with policy set to SCHED_EXT are attached to
144 	 * sched_ext. If clear, SCHED_NORMAL tasks are also included.
145 	 */
146 	SCX_OPS_SWITCH_PARTIAL		= 1LLU << 3,
147 
148 	/*
149 	 * A migration disabled task can only execute on its current CPU. By
150 	 * default, such tasks are automatically put on the CPU's local DSQ with
151 	 * the default slice on enqueue. If this ops flag is set, they also go
152 	 * through ops.enqueue().
153 	 *
154 	 * A migration disabled task never invokes ops.select_cpu() as it can
155 	 * only select the current CPU. Also, p->cpus_ptr will only contain its
156 	 * current CPU while p->nr_cpus_allowed keeps tracking p->user_cpus_ptr
157 	 * and thus may disagree with cpumask_weight(p->cpus_ptr).
158 	 */
159 	SCX_OPS_ENQ_MIGRATION_DISABLED	= 1LLU << 4,
160 
161 	/*
162 	 * Queued wakeup (ttwu_queue) is a wakeup optimization that invokes
163 	 * ops.enqueue() on the ops.select_cpu() selected or the wakee's
164 	 * previous CPU via IPI (inter-processor interrupt) to reduce cacheline
165 	 * transfers. When this optimization is enabled, ops.select_cpu() is
166 	 * skipped in some cases (when racing against the wakee switching out).
167 	 * As the BPF scheduler may depend on ops.select_cpu() being invoked
168 	 * during wakeups, queued wakeup is disabled by default.
169 	 *
170 	 * If this ops flag is set, queued wakeup optimization is enabled and
171 	 * the BPF scheduler must be able to handle ops.enqueue() invoked on the
172 	 * wakee's CPU without preceding ops.select_cpu() even for tasks which
173 	 * may be executed on multiple CPUs.
174 	 */
175 	SCX_OPS_ALLOW_QUEUED_WAKEUP	= 1LLU << 5,
176 
177 	/*
178 	 * If set, enable per-node idle cpumasks. If clear, use a single global
179 	 * flat idle cpumask.
180 	 */
181 	SCX_OPS_BUILTIN_IDLE_PER_NODE	= 1LLU << 6,
182 
183 	SCX_OPS_ALL_FLAGS		= SCX_OPS_KEEP_BUILTIN_IDLE |
184 					  SCX_OPS_ENQ_LAST |
185 					  SCX_OPS_ENQ_EXITING |
186 					  SCX_OPS_ENQ_MIGRATION_DISABLED |
187 					  SCX_OPS_ALLOW_QUEUED_WAKEUP |
188 					  SCX_OPS_SWITCH_PARTIAL |
189 					  SCX_OPS_BUILTIN_IDLE_PER_NODE,
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 	 * @cpu_acquire: A CPU is becoming available to the BPF scheduler
534 	 * @cpu: The CPU being acquired by the BPF scheduler.
535 	 * @args: Acquire arguments, see the struct definition.
536 	 *
537 	 * A CPU that was previously released from the BPF scheduler is now once
538 	 * again under its control.
539 	 */
540 	void (*cpu_acquire)(s32 cpu, struct scx_cpu_acquire_args *args);
541 
542 	/**
543 	 * @cpu_release: A CPU is taken away from the BPF scheduler
544 	 * @cpu: The CPU being released by the BPF scheduler.
545 	 * @args: Release arguments, see the struct definition.
546 	 *
547 	 * The specified CPU is no longer under the control of the BPF
548 	 * scheduler. This could be because it was preempted by a higher
549 	 * priority sched_class, though there may be other reasons as well. The
550 	 * caller should consult @args->reason to determine the cause.
551 	 */
552 	void (*cpu_release)(s32 cpu, struct scx_cpu_release_args *args);
553 
554 	/**
555 	 * @init_task: Initialize a task to run in a BPF scheduler
556 	 * @p: task to initialize for BPF scheduling
557 	 * @args: init arguments, see the struct definition
558 	 *
559 	 * Either we're loading a BPF scheduler or a new task is being forked.
560 	 * Initialize @p for BPF scheduling. This operation may block and can
561 	 * be used for allocations, and is called exactly once for a task.
562 	 *
563 	 * Return 0 for success, -errno for failure. An error return while
564 	 * loading will abort loading of the BPF scheduler. During a fork, it
565 	 * will abort that specific fork.
566 	 */
567 	s32 (*init_task)(struct task_struct *p, struct scx_init_task_args *args);
568 
569 	/**
570 	 * @exit_task: Exit a previously-running task from the system
571 	 * @p: task to exit
572 	 * @args: exit arguments, see the struct definition
573 	 *
574 	 * @p is exiting or the BPF scheduler is being unloaded. Perform any
575 	 * necessary cleanup for @p.
576 	 */
577 	void (*exit_task)(struct task_struct *p, struct scx_exit_task_args *args);
578 
579 	/**
580 	 * @enable: Enable BPF scheduling for a task
581 	 * @p: task to enable BPF scheduling for
582 	 *
583 	 * Enable @p for BPF scheduling. enable() is called on @p any time it
584 	 * enters SCX, and is always paired with a matching disable().
585 	 */
586 	void (*enable)(struct task_struct *p);
587 
588 	/**
589 	 * @disable: Disable BPF scheduling for a task
590 	 * @p: task to disable BPF scheduling for
591 	 *
592 	 * @p is exiting, leaving SCX or the BPF scheduler is being unloaded.
593 	 * Disable BPF scheduling for @p. A disable() call is always matched
594 	 * with a prior enable() call.
595 	 */
596 	void (*disable)(struct task_struct *p);
597 
598 	/**
599 	 * @dump: Dump BPF scheduler state on error
600 	 * @ctx: debug dump context
601 	 *
602 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump.
603 	 */
604 	void (*dump)(struct scx_dump_ctx *ctx);
605 
606 	/**
607 	 * @dump_cpu: Dump BPF scheduler state for a CPU on error
608 	 * @ctx: debug dump context
609 	 * @cpu: CPU to generate debug dump for
610 	 * @idle: @cpu is currently idle without any runnable tasks
611 	 *
612 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
613 	 * @cpu. If @idle is %true and this operation doesn't produce any
614 	 * output, @cpu is skipped for dump.
615 	 */
616 	void (*dump_cpu)(struct scx_dump_ctx *ctx, s32 cpu, bool idle);
617 
618 	/**
619 	 * @dump_task: Dump BPF scheduler state for a runnable task on error
620 	 * @ctx: debug dump context
621 	 * @p: runnable task to generate debug dump for
622 	 *
623 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
624 	 * @p.
625 	 */
626 	void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p);
627 
628 #ifdef CONFIG_EXT_GROUP_SCHED
629 	/**
630 	 * @cgroup_init: Initialize a cgroup
631 	 * @cgrp: cgroup being initialized
632 	 * @args: init arguments, see the struct definition
633 	 *
634 	 * Either the BPF scheduler is being loaded or @cgrp created, initialize
635 	 * @cgrp for sched_ext. This operation may block.
636 	 *
637 	 * Return 0 for success, -errno for failure. An error return while
638 	 * loading will abort loading of the BPF scheduler. During cgroup
639 	 * creation, it will abort the specific cgroup creation.
640 	 */
641 	s32 (*cgroup_init)(struct cgroup *cgrp,
642 			   struct scx_cgroup_init_args *args);
643 
644 	/**
645 	 * @cgroup_exit: Exit a cgroup
646 	 * @cgrp: cgroup being exited
647 	 *
648 	 * Either the BPF scheduler is being unloaded or @cgrp destroyed, exit
649 	 * @cgrp for sched_ext. This operation my block.
650 	 */
651 	void (*cgroup_exit)(struct cgroup *cgrp);
652 
653 	/**
654 	 * @cgroup_prep_move: Prepare a task to be moved to a different cgroup
655 	 * @p: task being moved
656 	 * @from: cgroup @p is being moved from
657 	 * @to: cgroup @p is being moved to
658 	 *
659 	 * Prepare @p for move from cgroup @from to @to. This operation may
660 	 * block and can be used for allocations.
661 	 *
662 	 * Return 0 for success, -errno for failure. An error return aborts the
663 	 * migration.
664 	 */
665 	s32 (*cgroup_prep_move)(struct task_struct *p,
666 				struct cgroup *from, struct cgroup *to);
667 
668 	/**
669 	 * @cgroup_move: Commit cgroup move
670 	 * @p: task being moved
671 	 * @from: cgroup @p is being moved from
672 	 * @to: cgroup @p is being moved to
673 	 *
674 	 * Commit the move. @p is dequeued during this operation.
675 	 */
676 	void (*cgroup_move)(struct task_struct *p,
677 			    struct cgroup *from, struct cgroup *to);
678 
679 	/**
680 	 * @cgroup_cancel_move: Cancel cgroup move
681 	 * @p: task whose cgroup move is being canceled
682 	 * @from: cgroup @p was being moved from
683 	 * @to: cgroup @p was being moved to
684 	 *
685 	 * @p was cgroup_prep_move()'d but failed before reaching cgroup_move().
686 	 * Undo the preparation.
687 	 */
688 	void (*cgroup_cancel_move)(struct task_struct *p,
689 				   struct cgroup *from, struct cgroup *to);
690 
691 	/**
692 	 * @cgroup_set_weight: A cgroup's weight is being changed
693 	 * @cgrp: cgroup whose weight is being updated
694 	 * @weight: new weight [1..10000]
695 	 *
696 	 * Update @cgrp's weight to @weight.
697 	 */
698 	void (*cgroup_set_weight)(struct cgroup *cgrp, u32 weight);
699 
700 	/**
701 	 * @cgroup_set_bandwidth: A cgroup's bandwidth is being changed
702 	 * @cgrp: cgroup whose bandwidth is being updated
703 	 * @period_us: bandwidth control period
704 	 * @quota_us: bandwidth control quota
705 	 * @burst_us: bandwidth control burst
706 	 *
707 	 * Update @cgrp's bandwidth control parameters. This is from the cpu.max
708 	 * cgroup interface.
709 	 *
710 	 * @quota_us / @period_us determines the CPU bandwidth @cgrp is entitled
711 	 * to. For example, if @period_us is 1_000_000 and @quota_us is
712 	 * 2_500_000. @cgrp is entitled to 2.5 CPUs. @burst_us can be
713 	 * interpreted in the same fashion and specifies how much @cgrp can
714 	 * burst temporarily. The specific control mechanism and thus the
715 	 * interpretation of @period_us and burstiness is up to the BPF
716 	 * scheduler.
717 	 */
718 	void (*cgroup_set_bandwidth)(struct cgroup *cgrp,
719 				     u64 period_us, u64 quota_us, u64 burst_us);
720 
721 	/**
722 	 * @cgroup_set_idle: A cgroup's idle state is being changed
723 	 * @cgrp: cgroup whose idle state is being updated
724 	 * @idle: whether the cgroup is entering or exiting idle state
725 	 *
726 	 * Update @cgrp's idle state to @idle. This callback is invoked when
727 	 * a cgroup transitions between idle and non-idle states, allowing the
728 	 * BPF scheduler to adjust its behavior accordingly.
729 	 */
730 	void (*cgroup_set_idle)(struct cgroup *cgrp, bool idle);
731 
732 #endif	/* CONFIG_EXT_GROUP_SCHED */
733 
734 	/**
735 	 * @sub_attach: Attach a sub-scheduler
736 	 * @args: argument container, see the struct definition
737 	 *
738 	 * Return 0 to accept the sub-scheduler. -errno to reject.
739 	 */
740 	s32 (*sub_attach)(struct scx_sub_attach_args *args);
741 
742 	/**
743 	 * @sub_detach: Detach a sub-scheduler
744 	 * @args: argument container, see the struct definition
745 	 */
746 	void (*sub_detach)(struct scx_sub_detach_args *args);
747 
748 	/*
749 	 * All online ops must come before ops.cpu_online().
750 	 */
751 
752 	/**
753 	 * @cpu_online: A CPU became online
754 	 * @cpu: CPU which just came up
755 	 *
756 	 * @cpu just came online. @cpu will not call ops.enqueue() or
757 	 * ops.dispatch(), nor run tasks associated with other CPUs beforehand.
758 	 */
759 	void (*cpu_online)(s32 cpu);
760 
761 	/**
762 	 * @cpu_offline: A CPU is going offline
763 	 * @cpu: CPU which is going offline
764 	 *
765 	 * @cpu is going offline. @cpu will not call ops.enqueue() or
766 	 * ops.dispatch(), nor run tasks associated with other CPUs afterwards.
767 	 */
768 	void (*cpu_offline)(s32 cpu);
769 
770 	/*
771 	 * All CPU hotplug ops must come before ops.init().
772 	 */
773 
774 	/**
775 	 * @init: Initialize the BPF scheduler
776 	 */
777 	s32 (*init)(void);
778 
779 	/**
780 	 * @exit: Clean up after the BPF scheduler
781 	 * @info: Exit info
782 	 *
783 	 * ops.exit() is also called on ops.init() failure, which is a bit
784 	 * unusual. This is to allow rich reporting through @info on how
785 	 * ops.init() failed.
786 	 */
787 	void (*exit)(struct scx_exit_info *info);
788 
789 	/*
790 	 * Data fields must comes after all ops fields.
791 	 */
792 
793 	/**
794 	 * @dispatch_max_batch: Max nr of tasks that dispatch() can dispatch
795 	 */
796 	u32 dispatch_max_batch;
797 
798 	/**
799 	 * @flags: %SCX_OPS_* flags
800 	 */
801 	u64 flags;
802 
803 	/**
804 	 * @timeout_ms: The maximum amount of time, in milliseconds, that a
805 	 * runnable task should be able to wait before being scheduled. The
806 	 * maximum timeout may not exceed the default timeout of 30 seconds.
807 	 *
808 	 * Defaults to the maximum allowed timeout value of 30 seconds.
809 	 */
810 	u32 timeout_ms;
811 
812 	/**
813 	 * @exit_dump_len: scx_exit_info.dump buffer length. If 0, the default
814 	 * value of 32768 is used.
815 	 */
816 	u32 exit_dump_len;
817 
818 	/**
819 	 * @hotplug_seq: A sequence number that may be set by the scheduler to
820 	 * detect when a hotplug event has occurred during the loading process.
821 	 * If 0, no detection occurs. Otherwise, the scheduler will fail to
822 	 * load if the sequence number does not match @scx_hotplug_seq on the
823 	 * enable path.
824 	 */
825 	u64 hotplug_seq;
826 
827 	/**
828 	 * @cgroup_id: When >1, attach the scheduler as a sub-scheduler on the
829 	 * specified cgroup.
830 	 */
831 	u64 sub_cgroup_id;
832 
833 	/**
834 	 * @name: BPF scheduler's name
835 	 *
836 	 * Must be a non-zero valid BPF object name including only isalnum(),
837 	 * '_' and '.' chars. Shows up in kernel.sched_ext_ops sysctl while the
838 	 * BPF scheduler is enabled.
839 	 */
840 	char name[SCX_OPS_NAME_LEN];
841 
842 	/* internal use only, must be NULL */
843 	void __rcu *priv;
844 };
845 
846 enum scx_opi {
847 	SCX_OPI_BEGIN			= 0,
848 	SCX_OPI_NORMAL_BEGIN		= 0,
849 	SCX_OPI_NORMAL_END		= SCX_OP_IDX(cpu_online),
850 	SCX_OPI_CPU_HOTPLUG_BEGIN	= SCX_OP_IDX(cpu_online),
851 	SCX_OPI_CPU_HOTPLUG_END		= SCX_OP_IDX(init),
852 	SCX_OPI_END			= SCX_OP_IDX(init),
853 };
854 
855 /*
856  * Collection of event counters. Event types are placed in descending order.
857  */
858 struct scx_event_stats {
859 	/*
860 	 * If ops.select_cpu() returns a CPU which can't be used by the task,
861 	 * the core scheduler code silently picks a fallback CPU.
862 	 */
863 	s64		SCX_EV_SELECT_CPU_FALLBACK;
864 
865 	/*
866 	 * When dispatching to a local DSQ, the CPU may have gone offline in
867 	 * the meantime. In this case, the task is bounced to the global DSQ.
868 	 */
869 	s64		SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE;
870 
871 	/*
872 	 * If SCX_OPS_ENQ_LAST is not set, the number of times that a task
873 	 * continued to run because there were no other tasks on the CPU.
874 	 */
875 	s64		SCX_EV_DISPATCH_KEEP_LAST;
876 
877 	/*
878 	 * If SCX_OPS_ENQ_EXITING is not set, the number of times that a task
879 	 * is dispatched to a local DSQ when exiting.
880 	 */
881 	s64		SCX_EV_ENQ_SKIP_EXITING;
882 
883 	/*
884 	 * If SCX_OPS_ENQ_MIGRATION_DISABLED is not set, the number of times a
885 	 * migration disabled task skips ops.enqueue() and is dispatched to its
886 	 * local DSQ.
887 	 */
888 	s64		SCX_EV_ENQ_SKIP_MIGRATION_DISABLED;
889 
890 	/*
891 	 * Total number of times a task's time slice was refilled with the
892 	 * default value (SCX_SLICE_DFL).
893 	 */
894 	s64		SCX_EV_REFILL_SLICE_DFL;
895 
896 	/*
897 	 * The total duration of bypass modes in nanoseconds.
898 	 */
899 	s64		SCX_EV_BYPASS_DURATION;
900 
901 	/*
902 	 * The number of tasks dispatched in the bypassing mode.
903 	 */
904 	s64		SCX_EV_BYPASS_DISPATCH;
905 
906 	/*
907 	 * The number of times the bypassing mode has been activated.
908 	 */
909 	s64		SCX_EV_BYPASS_ACTIVATE;
910 
911 	/*
912 	 * The number of times the scheduler attempted to insert a task that it
913 	 * doesn't own into a DSQ. Such attempts are ignored.
914 	 *
915 	 * As BPF schedulers are allowed to ignore dequeues, it's difficult to
916 	 * tell whether such an attempt is from a scheduler malfunction or an
917 	 * ignored dequeue around sub-sched enabling. If this count keeps going
918 	 * up regardless of sub-sched enabling, it likely indicates a bug in the
919 	 * scheduler.
920 	 */
921 	s64		SCX_EV_INSERT_NOT_OWNED;
922 
923 	/*
924 	 * The number of times tasks from bypassing descendants are scheduled
925 	 * from sub_bypass_dsq's.
926 	 */
927 	s64		SCX_EV_SUB_BYPASS_DISPATCH;
928 };
929 
930 struct scx_sched;
931 
932 enum scx_sched_pcpu_flags {
933 	SCX_SCHED_PCPU_BYPASSING	= 1LLU << 0,
934 };
935 
936 /* dispatch buf */
937 struct scx_dsp_buf_ent {
938 	struct task_struct	*task;
939 	unsigned long		qseq;
940 	u64			dsq_id;
941 	u64			enq_flags;
942 };
943 
944 struct scx_dsp_ctx {
945 	struct rq		*rq;
946 	u32			cursor;
947 	u32			nr_tasks;
948 	struct scx_dsp_buf_ent	buf[];
949 };
950 
951 struct scx_deferred_reenq_local {
952 	struct list_head	node;
953 	u64			flags;
954 };
955 
956 struct scx_sched_pcpu {
957 	struct scx_sched	*sch;
958 	u64			flags;	/* protected by rq lock */
959 
960 	/*
961 	 * The event counters are in a per-CPU variable to minimize the
962 	 * accounting overhead. A system-wide view on the event counter is
963 	 * constructed when requested by scx_bpf_events().
964 	 */
965 	struct scx_event_stats	event_stats;
966 
967 	struct scx_deferred_reenq_local deferred_reenq_local;
968 	struct scx_dispatch_q	bypass_dsq;
969 #ifdef CONFIG_EXT_SUB_SCHED
970 	u32			bypass_host_seq;
971 #endif
972 
973 	/* must be the last entry - contains flex array */
974 	struct scx_dsp_ctx	dsp_ctx;
975 };
976 
977 struct scx_sched_pnode {
978 	struct scx_dispatch_q	global_dsq;
979 };
980 
981 struct scx_sched {
982 	struct sched_ext_ops	ops;
983 	DECLARE_BITMAP(has_op, SCX_OPI_END);
984 
985 	/*
986 	 * Dispatch queues.
987 	 *
988 	 * The global DSQ (%SCX_DSQ_GLOBAL) is split per-node for scalability.
989 	 * This is to avoid live-locking in bypass mode where all tasks are
990 	 * dispatched to %SCX_DSQ_GLOBAL and all CPUs consume from it. If
991 	 * per-node split isn't sufficient, it can be further split.
992 	 */
993 	struct rhashtable	dsq_hash;
994 	struct scx_sched_pnode	**pnode;
995 	struct scx_sched_pcpu __percpu *pcpu;
996 
997 	u64			slice_dfl;
998 	u64			bypass_timestamp;
999 	s32			bypass_depth;
1000 
1001 	/* bypass dispatch path enable state, see bypass_dsp_enabled() */
1002 	unsigned long		bypass_dsp_claim;
1003 	atomic_t		bypass_dsp_enable_depth;
1004 
1005 	bool			aborting;
1006 	u32			dsp_max_batch;
1007 	s32			level;
1008 
1009 	/*
1010 	 * Updates to the following warned bitfields can race causing RMW issues
1011 	 * but it doesn't really matter.
1012 	 */
1013 	bool			warned_zero_slice:1;
1014 	bool			warned_deprecated_rq:1;
1015 	bool			warned_unassoc_progs:1;
1016 
1017 	struct list_head	all;
1018 
1019 #ifdef CONFIG_EXT_SUB_SCHED
1020 	struct rhash_head	hash_node;
1021 
1022 	struct list_head	children;
1023 	struct list_head	sibling;
1024 	struct cgroup		*cgrp;
1025 	char			*cgrp_path;
1026 	struct kset		*sub_kset;
1027 
1028 	bool			sub_attached;
1029 #endif	/* CONFIG_EXT_SUB_SCHED */
1030 
1031 	/*
1032 	 * The maximum amount of time in jiffies that a task may be runnable
1033 	 * without being scheduled on a CPU. If this timeout is exceeded, it
1034 	 * will trigger scx_error().
1035 	 */
1036 	unsigned long		watchdog_timeout;
1037 
1038 	atomic_t		exit_kind;
1039 	struct scx_exit_info	*exit_info;
1040 
1041 	struct kobject		kobj;
1042 
1043 	struct kthread_worker	*helper;
1044 	struct irq_work		error_irq_work;
1045 	struct kthread_work	disable_work;
1046 	struct timer_list	bypass_lb_timer;
1047 	struct rcu_work		rcu_work;
1048 
1049 	/* all ancestors including self */
1050 	struct scx_sched	*ancestors[];
1051 };
1052 
1053 enum scx_wake_flags {
1054 	/* expose select WF_* flags as enums */
1055 	SCX_WAKE_FORK		= WF_FORK,
1056 	SCX_WAKE_TTWU		= WF_TTWU,
1057 	SCX_WAKE_SYNC		= WF_SYNC,
1058 };
1059 
1060 enum scx_enq_flags {
1061 	/* expose select ENQUEUE_* flags as enums */
1062 	SCX_ENQ_WAKEUP		= ENQUEUE_WAKEUP,
1063 	SCX_ENQ_HEAD		= ENQUEUE_HEAD,
1064 	SCX_ENQ_CPU_SELECTED	= ENQUEUE_RQ_SELECTED,
1065 
1066 	/* high 32bits are SCX specific */
1067 
1068 	/*
1069 	 * Set the following to trigger preemption when calling
1070 	 * scx_bpf_dsq_insert() with a local dsq as the target. The slice of the
1071 	 * current task is cleared to zero and the CPU is kicked into the
1072 	 * scheduling path. Implies %SCX_ENQ_HEAD.
1073 	 */
1074 	SCX_ENQ_PREEMPT		= 1LLU << 32,
1075 
1076 	/*
1077 	 * The task being enqueued was previously enqueued on a DSQ, but was
1078 	 * removed and is being re-enqueued. See SCX_TASK_REENQ_* flags to find
1079 	 * out why a given task is being reenqueued.
1080 	 */
1081 	SCX_ENQ_REENQ		= 1LLU << 40,
1082 
1083 	/*
1084 	 * The task being enqueued is the only task available for the cpu. By
1085 	 * default, ext core keeps executing such tasks but when
1086 	 * %SCX_OPS_ENQ_LAST is specified, they're ops.enqueue()'d with the
1087 	 * %SCX_ENQ_LAST flag set.
1088 	 *
1089 	 * The BPF scheduler is responsible for triggering a follow-up
1090 	 * scheduling event. Otherwise, Execution may stall.
1091 	 */
1092 	SCX_ENQ_LAST		= 1LLU << 41,
1093 
1094 	/* high 8 bits are internal */
1095 	__SCX_ENQ_INTERNAL_MASK	= 0xffLLU << 56,
1096 
1097 	SCX_ENQ_CLEAR_OPSS	= 1LLU << 56,
1098 	SCX_ENQ_DSQ_PRIQ	= 1LLU << 57,
1099 	SCX_ENQ_NESTED		= 1LLU << 58,
1100 };
1101 
1102 enum scx_deq_flags {
1103 	/* expose select DEQUEUE_* flags as enums */
1104 	SCX_DEQ_SLEEP		= DEQUEUE_SLEEP,
1105 
1106 	/* high 32bits are SCX specific */
1107 
1108 	/*
1109 	 * The generic core-sched layer decided to execute the task even though
1110 	 * it hasn't been dispatched yet. Dequeue from the BPF side.
1111 	 */
1112 	SCX_DEQ_CORE_SCHED_EXEC	= 1LLU << 32,
1113 
1114 	/*
1115 	 * The task is being dequeued due to a property change (e.g.,
1116 	 * sched_setaffinity(), sched_setscheduler(), set_user_nice(),
1117 	 * etc.).
1118 	 */
1119 	SCX_DEQ_SCHED_CHANGE	= 1LLU << 33,
1120 };
1121 
1122 enum scx_reenq_flags {
1123 	/* low 16bits determine which tasks should be reenqueued */
1124 	SCX_REENQ_ANY		= 1LLU << 0,	/* all tasks */
1125 
1126 	__SCX_REENQ_FILTER_MASK	= 0xffffLLU,
1127 
1128 	__SCX_REENQ_USER_MASK	= SCX_REENQ_ANY,
1129 };
1130 
1131 enum scx_pick_idle_cpu_flags {
1132 	SCX_PICK_IDLE_CORE	= 1LLU << 0,	/* pick a CPU whose SMT siblings are also idle */
1133 	SCX_PICK_IDLE_IN_NODE	= 1LLU << 1,	/* pick a CPU in the same target NUMA node */
1134 };
1135 
1136 enum scx_kick_flags {
1137 	/*
1138 	 * Kick the target CPU if idle. Guarantees that the target CPU goes
1139 	 * through at least one full scheduling cycle before going idle. If the
1140 	 * target CPU can be determined to be currently not idle and going to go
1141 	 * through a scheduling cycle before going idle, noop.
1142 	 */
1143 	SCX_KICK_IDLE		= 1LLU << 0,
1144 
1145 	/*
1146 	 * Preempt the current task and execute the dispatch path. If the
1147 	 * current task of the target CPU is an SCX task, its ->scx.slice is
1148 	 * cleared to zero before the scheduling path is invoked so that the
1149 	 * task expires and the dispatch path is invoked.
1150 	 */
1151 	SCX_KICK_PREEMPT	= 1LLU << 1,
1152 
1153 	/*
1154 	 * The scx_bpf_kick_cpu() call will return after the current SCX task of
1155 	 * the target CPU switches out. This can be used to implement e.g. core
1156 	 * scheduling. This has no effect if the current task on the target CPU
1157 	 * is not on SCX.
1158 	 */
1159 	SCX_KICK_WAIT		= 1LLU << 2,
1160 };
1161 
1162 enum scx_tg_flags {
1163 	SCX_TG_ONLINE		= 1U << 0,
1164 	SCX_TG_INITED		= 1U << 1,
1165 };
1166 
1167 enum scx_enable_state {
1168 	SCX_ENABLING,
1169 	SCX_ENABLED,
1170 	SCX_DISABLING,
1171 	SCX_DISABLED,
1172 };
1173 
1174 static const char *scx_enable_state_str[] = {
1175 	[SCX_ENABLING]		= "enabling",
1176 	[SCX_ENABLED]		= "enabled",
1177 	[SCX_DISABLING]		= "disabling",
1178 	[SCX_DISABLED]		= "disabled",
1179 };
1180 
1181 /*
1182  * Task Ownership State Machine (sched_ext_entity->ops_state)
1183  *
1184  * The sched_ext core uses this state machine to track task ownership
1185  * between the SCX core and the BPF scheduler. This allows the BPF
1186  * scheduler to dispatch tasks without strict ordering requirements, while
1187  * the SCX core safely rejects invalid dispatches.
1188  *
1189  * State Transitions
1190  *
1191  *       .------------> NONE (owned by SCX core)
1192  *       |               |           ^
1193  *       |       enqueue |           | direct dispatch
1194  *       |               v           |
1195  *       |           QUEUEING -------'
1196  *       |               |
1197  *       |       enqueue |
1198  *       |     completes |
1199  *       |               v
1200  *       |            QUEUED (owned by BPF scheduler)
1201  *       |               |
1202  *       |      dispatch |
1203  *       |               |
1204  *       |               v
1205  *       |          DISPATCHING
1206  *       |               |
1207  *       |      dispatch |
1208  *       |     completes |
1209  *       `---------------'
1210  *
1211  * State Descriptions
1212  *
1213  * - %SCX_OPSS_NONE:
1214  *     Task is owned by the SCX core. It's either on a run queue, running,
1215  *     or being manipulated by the core scheduler. The BPF scheduler has no
1216  *     claim on this task.
1217  *
1218  * - %SCX_OPSS_QUEUEING:
1219  *     Transitional state while transferring a task from the SCX core to
1220  *     the BPF scheduler. The task's rq lock is held during this state.
1221  *     Since QUEUEING is both entered and exited under the rq lock, dequeue
1222  *     can never observe this state (it would be a BUG). When finishing a
1223  *     dispatch, if the task is still in %SCX_OPSS_QUEUEING the completion
1224  *     path busy-waits for it to leave this state (via wait_ops_state())
1225  *     before retrying.
1226  *
1227  * - %SCX_OPSS_QUEUED:
1228  *     Task is owned by the BPF scheduler. It's on a DSQ (dispatch queue)
1229  *     and the BPF scheduler is responsible for dispatching it. A QSEQ
1230  *     (queue sequence number) is embedded in this state to detect
1231  *     dispatch/dequeue races: if a task is dequeued and re-enqueued, the
1232  *     QSEQ changes and any in-flight dispatch operations targeting the old
1233  *     QSEQ are safely ignored.
1234  *
1235  * - %SCX_OPSS_DISPATCHING:
1236  *     Transitional state while transferring a task from the BPF scheduler
1237  *     back to the SCX core. This state indicates the BPF scheduler has
1238  *     selected the task for execution. When dequeue needs to take the task
1239  *     off a DSQ and it is still in %SCX_OPSS_DISPATCHING, the dequeue path
1240  *     busy-waits for it to leave this state (via wait_ops_state()) before
1241  *     proceeding. Exits to %SCX_OPSS_NONE when dispatch completes.
1242  *
1243  * Memory Ordering
1244  *
1245  * Transitions out of %SCX_OPSS_QUEUEING and %SCX_OPSS_DISPATCHING into
1246  * %SCX_OPSS_NONE or %SCX_OPSS_QUEUED must use atomic_long_set_release()
1247  * and waiters must use atomic_long_read_acquire(). This ensures proper
1248  * synchronization between concurrent operations.
1249  *
1250  * Cross-CPU Task Migration
1251  *
1252  * When moving a task in the %SCX_OPSS_DISPATCHING state, we can't simply
1253  * grab the target CPU's rq lock because a concurrent dequeue might be
1254  * waiting on %SCX_OPSS_DISPATCHING while holding the source rq lock
1255  * (deadlock).
1256  *
1257  * The sched_ext core uses a "lock dancing" protocol coordinated by
1258  * p->scx.holding_cpu. When moving a task to a different rq:
1259  *
1260  *   1. Verify task can be moved (CPU affinity, migration_disabled, etc.)
1261  *   2. Set p->scx.holding_cpu to the current CPU
1262  *   3. Set task state to %SCX_OPSS_NONE; dequeue waits while DISPATCHING
1263  *      is set, so clearing DISPATCHING first prevents the circular wait
1264  *      (safe to lock the rq we need)
1265  *   4. Unlock the current CPU's rq
1266  *   5. Lock src_rq (where the task currently lives)
1267  *   6. Verify p->scx.holding_cpu == current CPU, if not, dequeue won the
1268  *      race (dequeue clears holding_cpu to -1 when it takes the task), in
1269  *      this case migration is aborted
1270  *   7. If src_rq == dst_rq: clear holding_cpu and enqueue directly
1271  *      into dst_rq's local DSQ (no lock swap needed)
1272  *   8. Otherwise: call move_remote_task_to_local_dsq(), which releases
1273  *      src_rq, locks dst_rq, and performs the deactivate/activate
1274  *      migration cycle (dst_rq is held on return)
1275  *   9. Unlock dst_rq and re-lock the current CPU's rq to restore
1276  *      the lock state expected by the caller
1277  *
1278  * If any verification fails, abort the migration.
1279  *
1280  * This state tracking allows the BPF scheduler to try to dispatch any task
1281  * at any time regardless of its state. The SCX core can safely
1282  * reject/ignore invalid dispatches, simplifying the BPF scheduler
1283  * implementation.
1284  */
1285 enum scx_ops_state {
1286 	SCX_OPSS_NONE,		/* owned by the SCX core */
1287 	SCX_OPSS_QUEUEING,	/* in transit to the BPF scheduler */
1288 	SCX_OPSS_QUEUED,	/* owned by the BPF scheduler */
1289 	SCX_OPSS_DISPATCHING,	/* in transit back to the SCX core */
1290 
1291 	/*
1292 	 * QSEQ brands each QUEUED instance so that, when dispatch races
1293 	 * dequeue/requeue, the dispatcher can tell whether it still has a claim
1294 	 * on the task being dispatched.
1295 	 *
1296 	 * As some 32bit archs can't do 64bit store_release/load_acquire,
1297 	 * p->scx.ops_state is atomic_long_t which leaves 30 bits for QSEQ on
1298 	 * 32bit machines. The dispatch race window QSEQ protects is very narrow
1299 	 * and runs with IRQ disabled. 30 bits should be sufficient.
1300 	 */
1301 	SCX_OPSS_QSEQ_SHIFT	= 2,
1302 };
1303 
1304 /* Use macros to ensure that the type is unsigned long for the masks */
1305 #define SCX_OPSS_STATE_MASK	((1LU << SCX_OPSS_QSEQ_SHIFT) - 1)
1306 #define SCX_OPSS_QSEQ_MASK	(~SCX_OPSS_STATE_MASK)
1307 
1308 extern struct scx_sched __rcu *scx_root;
1309 DECLARE_PER_CPU(struct rq *, scx_locked_rq_state);
1310 
1311 /*
1312  * Return the rq currently locked from an scx callback, or NULL if no rq is
1313  * locked.
1314  */
1315 static inline struct rq *scx_locked_rq(void)
1316 {
1317 	return __this_cpu_read(scx_locked_rq_state);
1318 }
1319 
1320 static inline bool scx_kf_allowed_if_unlocked(void)
1321 {
1322 	return !current->scx.kf_mask;
1323 }
1324 
1325 static inline bool scx_bypassing(struct scx_sched *sch, s32 cpu)
1326 {
1327 	return unlikely(per_cpu_ptr(sch->pcpu, cpu)->flags &
1328 			SCX_SCHED_PCPU_BYPASSING);
1329 }
1330 
1331 #ifdef CONFIG_EXT_SUB_SCHED
1332 /**
1333  * scx_task_sched - Find scx_sched scheduling a task
1334  * @p: task of interest
1335  *
1336  * Return @p's scheduler instance. Must be called with @p's pi_lock or rq lock
1337  * held.
1338  */
1339 static inline struct scx_sched *scx_task_sched(const struct task_struct *p)
1340 {
1341 	return rcu_dereference_protected(p->scx.sched,
1342 					 lockdep_is_held(&p->pi_lock) ||
1343 					 lockdep_is_held(__rq_lockp(task_rq(p))));
1344 }
1345 
1346 /**
1347  * scx_task_sched_rcu - Find scx_sched scheduling a task
1348  * @p: task of interest
1349  *
1350  * Return @p's scheduler instance. The returned scx_sched is RCU protected.
1351  */
1352 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p)
1353 {
1354 	return rcu_dereference_all(p->scx.sched);
1355 }
1356 
1357 /**
1358  * scx_task_on_sched - Is a task on the specified sched?
1359  * @sch: sched to test against
1360  * @p: task of interest
1361  *
1362  * Returns %true if @p is on @sch, %false otherwise.
1363  */
1364 static inline bool scx_task_on_sched(struct scx_sched *sch,
1365 				     const struct task_struct *p)
1366 {
1367 	return rcu_access_pointer(p->scx.sched) == sch;
1368 }
1369 
1370 /**
1371  * scx_prog_sched - Find scx_sched associated with a BPF prog
1372  * @aux: aux passed in from BPF to a kfunc
1373  *
1374  * To be called from kfuncs. Return the scheduler instance associated with the
1375  * BPF program given the implicit kfunc argument aux. The returned scx_sched is
1376  * RCU protected.
1377  */
1378 static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux)
1379 {
1380 	struct sched_ext_ops *ops;
1381 	struct scx_sched *root;
1382 
1383 	ops = bpf_prog_get_assoc_struct_ops(aux);
1384 	if (likely(ops))
1385 		return rcu_dereference_all(ops->priv);
1386 
1387 	root = rcu_dereference_all(scx_root);
1388 	if (root) {
1389 		/*
1390 		 * COMPAT-v6.19: Schedulers built before sub-sched support was
1391 		 * introduced may have unassociated non-struct_ops programs.
1392 		 */
1393 		if (!root->ops.sub_attach)
1394 			return root;
1395 
1396 		if (!root->warned_unassoc_progs) {
1397 			printk_deferred(KERN_WARNING "sched_ext: Unassociated program %s (id %d)\n",
1398 					aux->name, aux->id);
1399 			root->warned_unassoc_progs = true;
1400 		}
1401 	}
1402 
1403 	return NULL;
1404 }
1405 #else	/* CONFIG_EXT_SUB_SCHED */
1406 static inline struct scx_sched *scx_task_sched(const struct task_struct *p)
1407 {
1408 	return rcu_dereference_protected(scx_root,
1409 					 lockdep_is_held(&p->pi_lock) ||
1410 					 lockdep_is_held(__rq_lockp(task_rq(p))));
1411 }
1412 
1413 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p)
1414 {
1415 	return rcu_dereference_all(scx_root);
1416 }
1417 
1418 static inline bool scx_task_on_sched(struct scx_sched *sch,
1419 				     const struct task_struct *p)
1420 {
1421 	return true;
1422 }
1423 
1424 static struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux)
1425 {
1426 	return rcu_dereference_all(scx_root);
1427 }
1428 #endif	/* CONFIG_EXT_SUB_SCHED */
1429