xref: /linux/kernel/sched/ext_internal.h (revision c90af06c80a33a28f0bdba3ba136439afad4dd38)
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 	/*
184 	 * CPU cgroup support flags
185 	 */
186 	SCX_OPS_HAS_CGROUP_WEIGHT	= 1LLU << 16,	/* DEPRECATED, will be removed on 6.18 */
187 
188 	SCX_OPS_ALL_FLAGS		= SCX_OPS_KEEP_BUILTIN_IDLE |
189 					  SCX_OPS_ENQ_LAST |
190 					  SCX_OPS_ENQ_EXITING |
191 					  SCX_OPS_ENQ_MIGRATION_DISABLED |
192 					  SCX_OPS_ALLOW_QUEUED_WAKEUP |
193 					  SCX_OPS_SWITCH_PARTIAL |
194 					  SCX_OPS_BUILTIN_IDLE_PER_NODE |
195 					  SCX_OPS_HAS_CGROUP_WEIGHT,
196 
197 	/* high 8 bits are internal, don't include in SCX_OPS_ALL_FLAGS */
198 	__SCX_OPS_INTERNAL_MASK		= 0xffLLU << 56,
199 
200 	SCX_OPS_HAS_CPU_PREEMPT		= 1LLU << 56,
201 };
202 
203 /* argument container for ops.init_task() */
204 struct scx_init_task_args {
205 	/*
206 	 * Set if ops.init_task() is being invoked on the fork path, as opposed
207 	 * to the scheduler transition path.
208 	 */
209 	bool			fork;
210 #ifdef CONFIG_EXT_GROUP_SCHED
211 	/* the cgroup the task is joining */
212 	struct cgroup		*cgroup;
213 #endif
214 };
215 
216 /* argument container for ops.exit_task() */
217 struct scx_exit_task_args {
218 	/* Whether the task exited before running on sched_ext. */
219 	bool cancelled;
220 };
221 
222 /* argument container for ops.cgroup_init() */
223 struct scx_cgroup_init_args {
224 	/* the weight of the cgroup [1..10000] */
225 	u32			weight;
226 
227 	/* bandwidth control parameters from cpu.max and cpu.max.burst */
228 	u64			bw_period_us;
229 	u64			bw_quota_us;
230 	u64			bw_burst_us;
231 };
232 
233 enum scx_cpu_preempt_reason {
234 	/* next task is being scheduled by &sched_class_rt */
235 	SCX_CPU_PREEMPT_RT,
236 	/* next task is being scheduled by &sched_class_dl */
237 	SCX_CPU_PREEMPT_DL,
238 	/* next task is being scheduled by &sched_class_stop */
239 	SCX_CPU_PREEMPT_STOP,
240 	/* unknown reason for SCX being preempted */
241 	SCX_CPU_PREEMPT_UNKNOWN,
242 };
243 
244 /*
245  * Argument container for ops.cpu_acquire(). Currently empty, but may be
246  * expanded in the future.
247  */
248 struct scx_cpu_acquire_args {};
249 
250 /* argument container for ops.cpu_release() */
251 struct scx_cpu_release_args {
252 	/* the reason the CPU was preempted */
253 	enum scx_cpu_preempt_reason reason;
254 
255 	/* the task that's going to be scheduled on the CPU */
256 	struct task_struct	*task;
257 };
258 
259 /* informational context provided to dump operations */
260 struct scx_dump_ctx {
261 	enum scx_exit_kind	kind;
262 	s64			exit_code;
263 	const char		*reason;
264 	u64			at_ns;
265 	u64			at_jiffies;
266 };
267 
268 /* argument container for ops.sub_attach() */
269 struct scx_sub_attach_args {
270 	struct sched_ext_ops	*ops;
271 	char			*cgroup_path;
272 };
273 
274 /* argument container for ops.sub_detach() */
275 struct scx_sub_detach_args {
276 	struct sched_ext_ops	*ops;
277 	char			*cgroup_path;
278 };
279 
280 /**
281  * struct sched_ext_ops - Operation table for BPF scheduler implementation
282  *
283  * A BPF scheduler can implement an arbitrary scheduling policy by
284  * implementing and loading operations in this table. Note that a userland
285  * scheduling policy can also be implemented using the BPF scheduler
286  * as a shim layer.
287  */
288 struct sched_ext_ops {
289 	/**
290 	 * @select_cpu: Pick the target CPU for a task which is being woken up
291 	 * @p: task being woken up
292 	 * @prev_cpu: the cpu @p was on before sleeping
293 	 * @wake_flags: SCX_WAKE_*
294 	 *
295 	 * Decision made here isn't final. @p may be moved to any CPU while it
296 	 * is getting dispatched for execution later. However, as @p is not on
297 	 * the rq at this point, getting the eventual execution CPU right here
298 	 * saves a small bit of overhead down the line.
299 	 *
300 	 * If an idle CPU is returned, the CPU is kicked and will try to
301 	 * dispatch. While an explicit custom mechanism can be added,
302 	 * select_cpu() serves as the default way to wake up idle CPUs.
303 	 *
304 	 * @p may be inserted into a DSQ directly by calling
305 	 * scx_bpf_dsq_insert(). If so, the ops.enqueue() will be skipped.
306 	 * Directly inserting into %SCX_DSQ_LOCAL will put @p in the local DSQ
307 	 * of the CPU returned by this operation.
308 	 *
309 	 * Note that select_cpu() is never called for tasks that can only run
310 	 * on a single CPU or tasks with migration disabled, as they don't have
311 	 * the option to select a different CPU. See select_task_rq() for
312 	 * details.
313 	 */
314 	s32 (*select_cpu)(struct task_struct *p, s32 prev_cpu, u64 wake_flags);
315 
316 	/**
317 	 * @enqueue: Enqueue a task on the BPF scheduler
318 	 * @p: task being enqueued
319 	 * @enq_flags: %SCX_ENQ_*
320 	 *
321 	 * @p is ready to run. Insert directly into a DSQ by calling
322 	 * scx_bpf_dsq_insert() or enqueue on the BPF scheduler. If not directly
323 	 * inserted, the bpf scheduler owns @p and if it fails to dispatch @p,
324 	 * the task will stall.
325 	 *
326 	 * If @p was inserted into a DSQ from ops.select_cpu(), this callback is
327 	 * skipped.
328 	 */
329 	void (*enqueue)(struct task_struct *p, u64 enq_flags);
330 
331 	/**
332 	 * @dequeue: Remove a task from the BPF scheduler
333 	 * @p: task being dequeued
334 	 * @deq_flags: %SCX_DEQ_*
335 	 *
336 	 * Remove @p from the BPF scheduler. This is usually called to isolate
337 	 * the task while updating its scheduling properties (e.g. priority).
338 	 *
339 	 * The ext core keeps track of whether the BPF side owns a given task or
340 	 * not and can gracefully ignore spurious dispatches from BPF side,
341 	 * which makes it safe to not implement this method. However, depending
342 	 * on the scheduling logic, this can lead to confusing behaviors - e.g.
343 	 * scheduling position not being updated across a priority change.
344 	 */
345 	void (*dequeue)(struct task_struct *p, u64 deq_flags);
346 
347 	/**
348 	 * @dispatch: Dispatch tasks from the BPF scheduler and/or user DSQs
349 	 * @cpu: CPU to dispatch tasks for
350 	 * @prev: previous task being switched out
351 	 *
352 	 * Called when a CPU's local dsq is empty. The operation should dispatch
353 	 * one or more tasks from the BPF scheduler into the DSQs using
354 	 * scx_bpf_dsq_insert() and/or move from user DSQs into the local DSQ
355 	 * using scx_bpf_dsq_move_to_local().
356 	 *
357 	 * The maximum number of times scx_bpf_dsq_insert() can be called
358 	 * without an intervening scx_bpf_dsq_move_to_local() is specified by
359 	 * ops.dispatch_max_batch. See the comments on top of the two functions
360 	 * for more details.
361 	 *
362 	 * When not %NULL, @prev is an SCX task with its slice depleted. If
363 	 * @prev is still runnable as indicated by set %SCX_TASK_QUEUED in
364 	 * @prev->scx.flags, it is not enqueued yet and will be enqueued after
365 	 * ops.dispatch() returns. To keep executing @prev, return without
366 	 * dispatching or moving any tasks. Also see %SCX_OPS_ENQ_LAST.
367 	 */
368 	void (*dispatch)(s32 cpu, struct task_struct *prev);
369 
370 	/**
371 	 * @tick: Periodic tick
372 	 * @p: task running currently
373 	 *
374 	 * This operation is called every 1/HZ seconds on CPUs which are
375 	 * executing an SCX task. Setting @p->scx.slice to 0 will trigger an
376 	 * immediate dispatch cycle on the CPU.
377 	 */
378 	void (*tick)(struct task_struct *p);
379 
380 	/**
381 	 * @runnable: A task is becoming runnable on its associated CPU
382 	 * @p: task becoming runnable
383 	 * @enq_flags: %SCX_ENQ_*
384 	 *
385 	 * This and the following three functions can be used to track a task's
386 	 * execution state transitions. A task becomes ->runnable() on a CPU,
387 	 * and then goes through one or more ->running() and ->stopping() pairs
388 	 * as it runs on the CPU, and eventually becomes ->quiescent() when it's
389 	 * done running on the CPU.
390 	 *
391 	 * @p is becoming runnable on the CPU because it's
392 	 *
393 	 * - waking up (%SCX_ENQ_WAKEUP)
394 	 * - being moved from another CPU
395 	 * - being restored after temporarily taken off the queue for an
396 	 *   attribute change.
397 	 *
398 	 * This and ->enqueue() are related but not coupled. This operation
399 	 * notifies @p's state transition and may not be followed by ->enqueue()
400 	 * e.g. when @p is being dispatched to a remote CPU, or when @p is
401 	 * being enqueued on a CPU experiencing a hotplug event. Likewise, a
402 	 * task may be ->enqueue()'d without being preceded by this operation
403 	 * e.g. after exhausting its slice.
404 	 */
405 	void (*runnable)(struct task_struct *p, u64 enq_flags);
406 
407 	/**
408 	 * @running: A task is starting to run on its associated CPU
409 	 * @p: task starting to run
410 	 *
411 	 * Note that this callback may be called from a CPU other than the
412 	 * one the task is going to run on. This can happen when a task
413 	 * property is changed (i.e., affinity), since scx_next_task_scx(),
414 	 * which triggers this callback, may run on a CPU different from
415 	 * the task's assigned CPU.
416 	 *
417 	 * Therefore, always use scx_bpf_task_cpu(@p) to determine the
418 	 * target CPU the task is going to use.
419 	 *
420 	 * See ->runnable() for explanation on the task state notifiers.
421 	 */
422 	void (*running)(struct task_struct *p);
423 
424 	/**
425 	 * @stopping: A task is stopping execution
426 	 * @p: task stopping to run
427 	 * @runnable: is task @p still runnable?
428 	 *
429 	 * Note that this callback may be called from a CPU other than the
430 	 * one the task was running on. This can happen when a task
431 	 * property is changed (i.e., affinity), since dequeue_task_scx(),
432 	 * which triggers this callback, may run on a CPU different from
433 	 * the task's assigned CPU.
434 	 *
435 	 * Therefore, always use scx_bpf_task_cpu(@p) to retrieve the CPU
436 	 * the task was running on.
437 	 *
438 	 * See ->runnable() for explanation on the task state notifiers. If
439 	 * !@runnable, ->quiescent() will be invoked after this operation
440 	 * returns.
441 	 */
442 	void (*stopping)(struct task_struct *p, bool runnable);
443 
444 	/**
445 	 * @quiescent: A task is becoming not runnable on its associated CPU
446 	 * @p: task becoming not runnable
447 	 * @deq_flags: %SCX_DEQ_*
448 	 *
449 	 * See ->runnable() for explanation on the task state notifiers.
450 	 *
451 	 * @p is becoming quiescent on the CPU because it's
452 	 *
453 	 * - sleeping (%SCX_DEQ_SLEEP)
454 	 * - being moved to another CPU
455 	 * - being temporarily taken off the queue for an attribute change
456 	 *   (%SCX_DEQ_SAVE)
457 	 *
458 	 * This and ->dequeue() are related but not coupled. This operation
459 	 * notifies @p's state transition and may not be preceded by ->dequeue()
460 	 * e.g. when @p is being dispatched to a remote CPU.
461 	 */
462 	void (*quiescent)(struct task_struct *p, u64 deq_flags);
463 
464 	/**
465 	 * @yield: Yield CPU
466 	 * @from: yielding task
467 	 * @to: optional yield target task
468 	 *
469 	 * If @to is NULL, @from is yielding the CPU to other runnable tasks.
470 	 * The BPF scheduler should ensure that other available tasks are
471 	 * dispatched before the yielding task. Return value is ignored in this
472 	 * case.
473 	 *
474 	 * If @to is not-NULL, @from wants to yield the CPU to @to. If the bpf
475 	 * scheduler can implement the request, return %true; otherwise, %false.
476 	 */
477 	bool (*yield)(struct task_struct *from, struct task_struct *to);
478 
479 	/**
480 	 * @core_sched_before: Task ordering for core-sched
481 	 * @a: task A
482 	 * @b: task B
483 	 *
484 	 * Used by core-sched to determine the ordering between two tasks. See
485 	 * Documentation/admin-guide/hw-vuln/core-scheduling.rst for details on
486 	 * core-sched.
487 	 *
488 	 * Both @a and @b are runnable and may or may not currently be queued on
489 	 * the BPF scheduler. Should return %true if @a should run before @b.
490 	 * %false if there's no required ordering or @b should run before @a.
491 	 *
492 	 * If not specified, the default is ordering them according to when they
493 	 * became runnable.
494 	 */
495 	bool (*core_sched_before)(struct task_struct *a, struct task_struct *b);
496 
497 	/**
498 	 * @set_weight: Set task weight
499 	 * @p: task to set weight for
500 	 * @weight: new weight [1..10000]
501 	 *
502 	 * Update @p's weight to @weight.
503 	 */
504 	void (*set_weight)(struct task_struct *p, u32 weight);
505 
506 	/**
507 	 * @set_cpumask: Set CPU affinity
508 	 * @p: task to set CPU affinity for
509 	 * @cpumask: cpumask of cpus that @p can run on
510 	 *
511 	 * Update @p's CPU affinity to @cpumask.
512 	 */
513 	void (*set_cpumask)(struct task_struct *p,
514 			    const struct cpumask *cpumask);
515 
516 	/**
517 	 * @update_idle: Update the idle state of a CPU
518 	 * @cpu: CPU to update the idle state for
519 	 * @idle: whether entering or exiting the idle state
520 	 *
521 	 * This operation is called when @rq's CPU goes or leaves the idle
522 	 * state. By default, implementing this operation disables the built-in
523 	 * idle CPU tracking and the following helpers become unavailable:
524 	 *
525 	 * - scx_bpf_select_cpu_dfl()
526 	 * - scx_bpf_select_cpu_and()
527 	 * - scx_bpf_test_and_clear_cpu_idle()
528 	 * - scx_bpf_pick_idle_cpu()
529 	 *
530 	 * The user also must implement ops.select_cpu() as the default
531 	 * implementation relies on scx_bpf_select_cpu_dfl().
532 	 *
533 	 * Specify the %SCX_OPS_KEEP_BUILTIN_IDLE flag to keep the built-in idle
534 	 * tracking.
535 	 */
536 	void (*update_idle)(s32 cpu, bool idle);
537 
538 	/**
539 	 * @cpu_acquire: A CPU is becoming available to the BPF scheduler
540 	 * @cpu: The CPU being acquired by the BPF scheduler.
541 	 * @args: Acquire arguments, see the struct definition.
542 	 *
543 	 * A CPU that was previously released from the BPF scheduler is now once
544 	 * again under its control.
545 	 */
546 	void (*cpu_acquire)(s32 cpu, struct scx_cpu_acquire_args *args);
547 
548 	/**
549 	 * @cpu_release: A CPU is taken away from the BPF scheduler
550 	 * @cpu: The CPU being released by the BPF scheduler.
551 	 * @args: Release arguments, see the struct definition.
552 	 *
553 	 * The specified CPU is no longer under the control of the BPF
554 	 * scheduler. This could be because it was preempted by a higher
555 	 * priority sched_class, though there may be other reasons as well. The
556 	 * caller should consult @args->reason to determine the cause.
557 	 */
558 	void (*cpu_release)(s32 cpu, struct scx_cpu_release_args *args);
559 
560 	/**
561 	 * @init_task: Initialize a task to run in a BPF scheduler
562 	 * @p: task to initialize for BPF scheduling
563 	 * @args: init arguments, see the struct definition
564 	 *
565 	 * Either we're loading a BPF scheduler or a new task is being forked.
566 	 * Initialize @p for BPF scheduling. This operation may block and can
567 	 * be used for allocations, and is called exactly once for a task.
568 	 *
569 	 * Return 0 for success, -errno for failure. An error return while
570 	 * loading will abort loading of the BPF scheduler. During a fork, it
571 	 * will abort that specific fork.
572 	 */
573 	s32 (*init_task)(struct task_struct *p, struct scx_init_task_args *args);
574 
575 	/**
576 	 * @exit_task: Exit a previously-running task from the system
577 	 * @p: task to exit
578 	 * @args: exit arguments, see the struct definition
579 	 *
580 	 * @p is exiting or the BPF scheduler is being unloaded. Perform any
581 	 * necessary cleanup for @p.
582 	 */
583 	void (*exit_task)(struct task_struct *p, struct scx_exit_task_args *args);
584 
585 	/**
586 	 * @enable: Enable BPF scheduling for a task
587 	 * @p: task to enable BPF scheduling for
588 	 *
589 	 * Enable @p for BPF scheduling. enable() is called on @p any time it
590 	 * enters SCX, and is always paired with a matching disable().
591 	 */
592 	void (*enable)(struct task_struct *p);
593 
594 	/**
595 	 * @disable: Disable BPF scheduling for a task
596 	 * @p: task to disable BPF scheduling for
597 	 *
598 	 * @p is exiting, leaving SCX or the BPF scheduler is being unloaded.
599 	 * Disable BPF scheduling for @p. A disable() call is always matched
600 	 * with a prior enable() call.
601 	 */
602 	void (*disable)(struct task_struct *p);
603 
604 	/**
605 	 * @dump: Dump BPF scheduler state on error
606 	 * @ctx: debug dump context
607 	 *
608 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump.
609 	 */
610 	void (*dump)(struct scx_dump_ctx *ctx);
611 
612 	/**
613 	 * @dump_cpu: Dump BPF scheduler state for a CPU on error
614 	 * @ctx: debug dump context
615 	 * @cpu: CPU to generate debug dump for
616 	 * @idle: @cpu is currently idle without any runnable tasks
617 	 *
618 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
619 	 * @cpu. If @idle is %true and this operation doesn't produce any
620 	 * output, @cpu is skipped for dump.
621 	 */
622 	void (*dump_cpu)(struct scx_dump_ctx *ctx, s32 cpu, bool idle);
623 
624 	/**
625 	 * @dump_task: Dump BPF scheduler state for a runnable task on error
626 	 * @ctx: debug dump context
627 	 * @p: runnable task to generate debug dump for
628 	 *
629 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
630 	 * @p.
631 	 */
632 	void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p);
633 
634 #ifdef CONFIG_EXT_GROUP_SCHED
635 	/**
636 	 * @cgroup_init: Initialize a cgroup
637 	 * @cgrp: cgroup being initialized
638 	 * @args: init arguments, see the struct definition
639 	 *
640 	 * Either the BPF scheduler is being loaded or @cgrp created, initialize
641 	 * @cgrp for sched_ext. This operation may block.
642 	 *
643 	 * Return 0 for success, -errno for failure. An error return while
644 	 * loading will abort loading of the BPF scheduler. During cgroup
645 	 * creation, it will abort the specific cgroup creation.
646 	 */
647 	s32 (*cgroup_init)(struct cgroup *cgrp,
648 			   struct scx_cgroup_init_args *args);
649 
650 	/**
651 	 * @cgroup_exit: Exit a cgroup
652 	 * @cgrp: cgroup being exited
653 	 *
654 	 * Either the BPF scheduler is being unloaded or @cgrp destroyed, exit
655 	 * @cgrp for sched_ext. This operation my block.
656 	 */
657 	void (*cgroup_exit)(struct cgroup *cgrp);
658 
659 	/**
660 	 * @cgroup_prep_move: Prepare a task to be moved to a different cgroup
661 	 * @p: task being moved
662 	 * @from: cgroup @p is being moved from
663 	 * @to: cgroup @p is being moved to
664 	 *
665 	 * Prepare @p for move from cgroup @from to @to. This operation may
666 	 * block and can be used for allocations.
667 	 *
668 	 * Return 0 for success, -errno for failure. An error return aborts the
669 	 * migration.
670 	 */
671 	s32 (*cgroup_prep_move)(struct task_struct *p,
672 				struct cgroup *from, struct cgroup *to);
673 
674 	/**
675 	 * @cgroup_move: Commit cgroup move
676 	 * @p: task being moved
677 	 * @from: cgroup @p is being moved from
678 	 * @to: cgroup @p is being moved to
679 	 *
680 	 * Commit the move. @p is dequeued during this operation.
681 	 */
682 	void (*cgroup_move)(struct task_struct *p,
683 			    struct cgroup *from, struct cgroup *to);
684 
685 	/**
686 	 * @cgroup_cancel_move: Cancel cgroup move
687 	 * @p: task whose cgroup move is being canceled
688 	 * @from: cgroup @p was being moved from
689 	 * @to: cgroup @p was being moved to
690 	 *
691 	 * @p was cgroup_prep_move()'d but failed before reaching cgroup_move().
692 	 * Undo the preparation.
693 	 */
694 	void (*cgroup_cancel_move)(struct task_struct *p,
695 				   struct cgroup *from, struct cgroup *to);
696 
697 	/**
698 	 * @cgroup_set_weight: A cgroup's weight is being changed
699 	 * @cgrp: cgroup whose weight is being updated
700 	 * @weight: new weight [1..10000]
701 	 *
702 	 * Update @cgrp's weight to @weight.
703 	 */
704 	void (*cgroup_set_weight)(struct cgroup *cgrp, u32 weight);
705 
706 	/**
707 	 * @cgroup_set_bandwidth: A cgroup's bandwidth is being changed
708 	 * @cgrp: cgroup whose bandwidth is being updated
709 	 * @period_us: bandwidth control period
710 	 * @quota_us: bandwidth control quota
711 	 * @burst_us: bandwidth control burst
712 	 *
713 	 * Update @cgrp's bandwidth control parameters. This is from the cpu.max
714 	 * cgroup interface.
715 	 *
716 	 * @quota_us / @period_us determines the CPU bandwidth @cgrp is entitled
717 	 * to. For example, if @period_us is 1_000_000 and @quota_us is
718 	 * 2_500_000. @cgrp is entitled to 2.5 CPUs. @burst_us can be
719 	 * interpreted in the same fashion and specifies how much @cgrp can
720 	 * burst temporarily. The specific control mechanism and thus the
721 	 * interpretation of @period_us and burstiness is up to the BPF
722 	 * scheduler.
723 	 */
724 	void (*cgroup_set_bandwidth)(struct cgroup *cgrp,
725 				     u64 period_us, u64 quota_us, u64 burst_us);
726 
727 	/**
728 	 * @cgroup_set_idle: A cgroup's idle state is being changed
729 	 * @cgrp: cgroup whose idle state is being updated
730 	 * @idle: whether the cgroup is entering or exiting idle state
731 	 *
732 	 * Update @cgrp's idle state to @idle. This callback is invoked when
733 	 * a cgroup transitions between idle and non-idle states, allowing the
734 	 * BPF scheduler to adjust its behavior accordingly.
735 	 */
736 	void (*cgroup_set_idle)(struct cgroup *cgrp, bool idle);
737 
738 #endif	/* CONFIG_EXT_GROUP_SCHED */
739 
740 	/**
741 	 * @sub_attach: Attach a sub-scheduler
742 	 * @args: argument container, see the struct definition
743 	 *
744 	 * Return 0 to accept the sub-scheduler. -errno to reject.
745 	 */
746 	s32 (*sub_attach)(struct scx_sub_attach_args *args);
747 
748 	/**
749 	 * @sub_detach: Detach a sub-scheduler
750 	 * @args: argument container, see the struct definition
751 	 */
752 	void (*sub_detach)(struct scx_sub_detach_args *args);
753 
754 	/*
755 	 * All online ops must come before ops.cpu_online().
756 	 */
757 
758 	/**
759 	 * @cpu_online: A CPU became online
760 	 * @cpu: CPU which just came up
761 	 *
762 	 * @cpu just came online. @cpu will not call ops.enqueue() or
763 	 * ops.dispatch(), nor run tasks associated with other CPUs beforehand.
764 	 */
765 	void (*cpu_online)(s32 cpu);
766 
767 	/**
768 	 * @cpu_offline: A CPU is going offline
769 	 * @cpu: CPU which is going offline
770 	 *
771 	 * @cpu is going offline. @cpu will not call ops.enqueue() or
772 	 * ops.dispatch(), nor run tasks associated with other CPUs afterwards.
773 	 */
774 	void (*cpu_offline)(s32 cpu);
775 
776 	/*
777 	 * All CPU hotplug ops must come before ops.init().
778 	 */
779 
780 	/**
781 	 * @init: Initialize the BPF scheduler
782 	 */
783 	s32 (*init)(void);
784 
785 	/**
786 	 * @exit: Clean up after the BPF scheduler
787 	 * @info: Exit info
788 	 *
789 	 * ops.exit() is also called on ops.init() failure, which is a bit
790 	 * unusual. This is to allow rich reporting through @info on how
791 	 * ops.init() failed.
792 	 */
793 	void (*exit)(struct scx_exit_info *info);
794 
795 	/*
796 	 * Data fields must comes after all ops fields.
797 	 */
798 
799 	/**
800 	 * @dispatch_max_batch: Max nr of tasks that dispatch() can dispatch
801 	 */
802 	u32 dispatch_max_batch;
803 
804 	/**
805 	 * @flags: %SCX_OPS_* flags
806 	 */
807 	u64 flags;
808 
809 	/**
810 	 * @timeout_ms: The maximum amount of time, in milliseconds, that a
811 	 * runnable task should be able to wait before being scheduled. The
812 	 * maximum timeout may not exceed the default timeout of 30 seconds.
813 	 *
814 	 * Defaults to the maximum allowed timeout value of 30 seconds.
815 	 */
816 	u32 timeout_ms;
817 
818 	/**
819 	 * @exit_dump_len: scx_exit_info.dump buffer length. If 0, the default
820 	 * value of 32768 is used.
821 	 */
822 	u32 exit_dump_len;
823 
824 	/**
825 	 * @hotplug_seq: A sequence number that may be set by the scheduler to
826 	 * detect when a hotplug event has occurred during the loading process.
827 	 * If 0, no detection occurs. Otherwise, the scheduler will fail to
828 	 * load if the sequence number does not match @scx_hotplug_seq on the
829 	 * enable path.
830 	 */
831 	u64 hotplug_seq;
832 
833 	/**
834 	 * @cgroup_id: When >1, attach the scheduler as a sub-scheduler on the
835 	 * specified cgroup.
836 	 */
837 	u64 sub_cgroup_id;
838 
839 	/**
840 	 * @name: BPF scheduler's name
841 	 *
842 	 * Must be a non-zero valid BPF object name including only isalnum(),
843 	 * '_' and '.' chars. Shows up in kernel.sched_ext_ops sysctl while the
844 	 * BPF scheduler is enabled.
845 	 */
846 	char name[SCX_OPS_NAME_LEN];
847 
848 	/* internal use only, must be NULL */
849 	void __rcu *priv;
850 };
851 
852 enum scx_opi {
853 	SCX_OPI_BEGIN			= 0,
854 	SCX_OPI_NORMAL_BEGIN		= 0,
855 	SCX_OPI_NORMAL_END		= SCX_OP_IDX(cpu_online),
856 	SCX_OPI_CPU_HOTPLUG_BEGIN	= SCX_OP_IDX(cpu_online),
857 	SCX_OPI_CPU_HOTPLUG_END		= SCX_OP_IDX(init),
858 	SCX_OPI_END			= SCX_OP_IDX(init),
859 };
860 
861 /*
862  * Collection of event counters. Event types are placed in descending order.
863  */
864 struct scx_event_stats {
865 	/*
866 	 * If ops.select_cpu() returns a CPU which can't be used by the task,
867 	 * the core scheduler code silently picks a fallback CPU.
868 	 */
869 	s64		SCX_EV_SELECT_CPU_FALLBACK;
870 
871 	/*
872 	 * When dispatching to a local DSQ, the CPU may have gone offline in
873 	 * the meantime. In this case, the task is bounced to the global DSQ.
874 	 */
875 	s64		SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE;
876 
877 	/*
878 	 * If SCX_OPS_ENQ_LAST is not set, the number of times that a task
879 	 * continued to run because there were no other tasks on the CPU.
880 	 */
881 	s64		SCX_EV_DISPATCH_KEEP_LAST;
882 
883 	/*
884 	 * If SCX_OPS_ENQ_EXITING is not set, the number of times that a task
885 	 * is dispatched to a local DSQ when exiting.
886 	 */
887 	s64		SCX_EV_ENQ_SKIP_EXITING;
888 
889 	/*
890 	 * If SCX_OPS_ENQ_MIGRATION_DISABLED is not set, the number of times a
891 	 * migration disabled task skips ops.enqueue() and is dispatched to its
892 	 * local DSQ.
893 	 */
894 	s64		SCX_EV_ENQ_SKIP_MIGRATION_DISABLED;
895 
896 	/*
897 	 * Total number of times a task's time slice was refilled with the
898 	 * default value (SCX_SLICE_DFL).
899 	 */
900 	s64		SCX_EV_REFILL_SLICE_DFL;
901 
902 	/*
903 	 * The total duration of bypass modes in nanoseconds.
904 	 */
905 	s64		SCX_EV_BYPASS_DURATION;
906 
907 	/*
908 	 * The number of tasks dispatched in the bypassing mode.
909 	 */
910 	s64		SCX_EV_BYPASS_DISPATCH;
911 
912 	/*
913 	 * The number of times the bypassing mode has been activated.
914 	 */
915 	s64		SCX_EV_BYPASS_ACTIVATE;
916 
917 	/*
918 	 * The number of times the scheduler attempted to insert a task that it
919 	 * doesn't own into a DSQ. Such attempts are ignored.
920 	 *
921 	 * As BPF schedulers are allowed to ignore dequeues, it's difficult to
922 	 * tell whether such an attempt is from a scheduler malfunction or an
923 	 * ignored dequeue around sub-sched enabling. If this count keeps going
924 	 * up regardless of sub-sched enabling, it likely indicates a bug in the
925 	 * scheduler.
926 	 */
927 	s64		SCX_EV_INSERT_NOT_OWNED;
928 
929 	/*
930 	 * The number of times tasks from bypassing descendants are scheduled
931 	 * from sub_bypass_dsq's.
932 	 */
933 	s64		SCX_EV_SUB_BYPASS_DISPATCH;
934 };
935 
936 struct scx_sched;
937 
938 enum scx_sched_pcpu_flags {
939 	SCX_SCHED_PCPU_BYPASSING	= 1LLU << 0,
940 };
941 
942 /* dispatch buf */
943 struct scx_dsp_buf_ent {
944 	struct task_struct	*task;
945 	unsigned long		qseq;
946 	u64			dsq_id;
947 	u64			enq_flags;
948 };
949 
950 struct scx_dsp_ctx {
951 	struct rq		*rq;
952 	u32			cursor;
953 	u32			nr_tasks;
954 	struct scx_dsp_buf_ent	buf[];
955 };
956 
957 struct scx_deferred_reenq_local {
958 	struct list_head	node;
959 	u64			flags;
960 };
961 
962 struct scx_sched_pcpu {
963 	struct scx_sched	*sch;
964 	u64			flags;	/* protected by rq lock */
965 
966 	/*
967 	 * The event counters are in a per-CPU variable to minimize the
968 	 * accounting overhead. A system-wide view on the event counter is
969 	 * constructed when requested by scx_bpf_events().
970 	 */
971 	struct scx_event_stats	event_stats;
972 
973 	struct scx_deferred_reenq_local deferred_reenq_local;
974 	struct scx_dispatch_q	bypass_dsq;
975 #ifdef CONFIG_EXT_SUB_SCHED
976 	u32			bypass_host_seq;
977 #endif
978 
979 	/* must be the last entry - contains flex array */
980 	struct scx_dsp_ctx	dsp_ctx;
981 };
982 
983 struct scx_sched_pnode {
984 	struct scx_dispatch_q	global_dsq;
985 };
986 
987 struct scx_sched {
988 	struct sched_ext_ops	ops;
989 	DECLARE_BITMAP(has_op, SCX_OPI_END);
990 
991 	/*
992 	 * Dispatch queues.
993 	 *
994 	 * The global DSQ (%SCX_DSQ_GLOBAL) is split per-node for scalability.
995 	 * This is to avoid live-locking in bypass mode where all tasks are
996 	 * dispatched to %SCX_DSQ_GLOBAL and all CPUs consume from it. If
997 	 * per-node split isn't sufficient, it can be further split.
998 	 */
999 	struct rhashtable	dsq_hash;
1000 	struct scx_sched_pnode	**pnode;
1001 	struct scx_sched_pcpu __percpu *pcpu;
1002 
1003 	u64			slice_dfl;
1004 	u64			bypass_timestamp;
1005 	s32			bypass_depth;
1006 
1007 	/* bypass dispatch path enable state, see bypass_dsp_enabled() */
1008 	unsigned long		bypass_dsp_claim;
1009 	atomic_t		bypass_dsp_enable_depth;
1010 
1011 	bool			aborting;
1012 	u32			dsp_max_batch;
1013 	s32			level;
1014 
1015 	/*
1016 	 * Updates to the following warned bitfields can race causing RMW issues
1017 	 * but it doesn't really matter.
1018 	 */
1019 	bool			warned_zero_slice:1;
1020 	bool			warned_deprecated_rq:1;
1021 	bool			warned_unassoc_progs:1;
1022 
1023 	struct list_head	all;
1024 
1025 #ifdef CONFIG_EXT_SUB_SCHED
1026 	struct rhash_head	hash_node;
1027 
1028 	struct list_head	children;
1029 	struct list_head	sibling;
1030 	struct cgroup		*cgrp;
1031 	char			*cgrp_path;
1032 	struct kset		*sub_kset;
1033 
1034 	bool			sub_attached;
1035 #endif	/* CONFIG_EXT_SUB_SCHED */
1036 
1037 	/*
1038 	 * The maximum amount of time in jiffies that a task may be runnable
1039 	 * without being scheduled on a CPU. If this timeout is exceeded, it
1040 	 * will trigger scx_error().
1041 	 */
1042 	unsigned long		watchdog_timeout;
1043 
1044 	atomic_t		exit_kind;
1045 	struct scx_exit_info	*exit_info;
1046 
1047 	struct kobject		kobj;
1048 
1049 	struct kthread_worker	*helper;
1050 	struct irq_work		error_irq_work;
1051 	struct kthread_work	disable_work;
1052 	struct timer_list	bypass_lb_timer;
1053 	struct rcu_work		rcu_work;
1054 
1055 	/* all ancestors including self */
1056 	struct scx_sched	*ancestors[];
1057 };
1058 
1059 enum scx_wake_flags {
1060 	/* expose select WF_* flags as enums */
1061 	SCX_WAKE_FORK		= WF_FORK,
1062 	SCX_WAKE_TTWU		= WF_TTWU,
1063 	SCX_WAKE_SYNC		= WF_SYNC,
1064 };
1065 
1066 enum scx_enq_flags {
1067 	/* expose select ENQUEUE_* flags as enums */
1068 	SCX_ENQ_WAKEUP		= ENQUEUE_WAKEUP,
1069 	SCX_ENQ_HEAD		= ENQUEUE_HEAD,
1070 	SCX_ENQ_CPU_SELECTED	= ENQUEUE_RQ_SELECTED,
1071 
1072 	/* high 32bits are SCX specific */
1073 
1074 	/*
1075 	 * Set the following to trigger preemption when calling
1076 	 * scx_bpf_dsq_insert() with a local dsq as the target. The slice of the
1077 	 * current task is cleared to zero and the CPU is kicked into the
1078 	 * scheduling path. Implies %SCX_ENQ_HEAD.
1079 	 */
1080 	SCX_ENQ_PREEMPT		= 1LLU << 32,
1081 
1082 	/*
1083 	 * The task being enqueued was previously enqueued on a DSQ, but was
1084 	 * removed and is being re-enqueued. See SCX_TASK_REENQ_* flags to find
1085 	 * out why a given task is being reenqueued.
1086 	 */
1087 	SCX_ENQ_REENQ		= 1LLU << 40,
1088 
1089 	/*
1090 	 * The task being enqueued is the only task available for the cpu. By
1091 	 * default, ext core keeps executing such tasks but when
1092 	 * %SCX_OPS_ENQ_LAST is specified, they're ops.enqueue()'d with the
1093 	 * %SCX_ENQ_LAST flag set.
1094 	 *
1095 	 * The BPF scheduler is responsible for triggering a follow-up
1096 	 * scheduling event. Otherwise, Execution may stall.
1097 	 */
1098 	SCX_ENQ_LAST		= 1LLU << 41,
1099 
1100 	/* high 8 bits are internal */
1101 	__SCX_ENQ_INTERNAL_MASK	= 0xffLLU << 56,
1102 
1103 	SCX_ENQ_CLEAR_OPSS	= 1LLU << 56,
1104 	SCX_ENQ_DSQ_PRIQ	= 1LLU << 57,
1105 	SCX_ENQ_NESTED		= 1LLU << 58,
1106 };
1107 
1108 enum scx_deq_flags {
1109 	/* expose select DEQUEUE_* flags as enums */
1110 	SCX_DEQ_SLEEP		= DEQUEUE_SLEEP,
1111 
1112 	/* high 32bits are SCX specific */
1113 
1114 	/*
1115 	 * The generic core-sched layer decided to execute the task even though
1116 	 * it hasn't been dispatched yet. Dequeue from the BPF side.
1117 	 */
1118 	SCX_DEQ_CORE_SCHED_EXEC	= 1LLU << 32,
1119 
1120 	/*
1121 	 * The task is being dequeued due to a property change (e.g.,
1122 	 * sched_setaffinity(), sched_setscheduler(), set_user_nice(),
1123 	 * etc.).
1124 	 */
1125 	SCX_DEQ_SCHED_CHANGE	= 1LLU << 33,
1126 };
1127 
1128 enum scx_reenq_flags {
1129 	/* low 16bits determine which tasks should be reenqueued */
1130 	SCX_REENQ_ANY		= 1LLU << 0,	/* all tasks */
1131 
1132 	__SCX_REENQ_FILTER_MASK	= 0xffffLLU,
1133 
1134 	__SCX_REENQ_USER_MASK	= SCX_REENQ_ANY,
1135 };
1136 
1137 enum scx_pick_idle_cpu_flags {
1138 	SCX_PICK_IDLE_CORE	= 1LLU << 0,	/* pick a CPU whose SMT siblings are also idle */
1139 	SCX_PICK_IDLE_IN_NODE	= 1LLU << 1,	/* pick a CPU in the same target NUMA node */
1140 };
1141 
1142 enum scx_kick_flags {
1143 	/*
1144 	 * Kick the target CPU if idle. Guarantees that the target CPU goes
1145 	 * through at least one full scheduling cycle before going idle. If the
1146 	 * target CPU can be determined to be currently not idle and going to go
1147 	 * through a scheduling cycle before going idle, noop.
1148 	 */
1149 	SCX_KICK_IDLE		= 1LLU << 0,
1150 
1151 	/*
1152 	 * Preempt the current task and execute the dispatch path. If the
1153 	 * current task of the target CPU is an SCX task, its ->scx.slice is
1154 	 * cleared to zero before the scheduling path is invoked so that the
1155 	 * task expires and the dispatch path is invoked.
1156 	 */
1157 	SCX_KICK_PREEMPT	= 1LLU << 1,
1158 
1159 	/*
1160 	 * The scx_bpf_kick_cpu() call will return after the current SCX task of
1161 	 * the target CPU switches out. This can be used to implement e.g. core
1162 	 * scheduling. This has no effect if the current task on the target CPU
1163 	 * is not on SCX.
1164 	 */
1165 	SCX_KICK_WAIT		= 1LLU << 2,
1166 };
1167 
1168 enum scx_tg_flags {
1169 	SCX_TG_ONLINE		= 1U << 0,
1170 	SCX_TG_INITED		= 1U << 1,
1171 };
1172 
1173 enum scx_enable_state {
1174 	SCX_ENABLING,
1175 	SCX_ENABLED,
1176 	SCX_DISABLING,
1177 	SCX_DISABLED,
1178 };
1179 
1180 static const char *scx_enable_state_str[] = {
1181 	[SCX_ENABLING]		= "enabling",
1182 	[SCX_ENABLED]		= "enabled",
1183 	[SCX_DISABLING]		= "disabling",
1184 	[SCX_DISABLED]		= "disabled",
1185 };
1186 
1187 /*
1188  * Task Ownership State Machine (sched_ext_entity->ops_state)
1189  *
1190  * The sched_ext core uses this state machine to track task ownership
1191  * between the SCX core and the BPF scheduler. This allows the BPF
1192  * scheduler to dispatch tasks without strict ordering requirements, while
1193  * the SCX core safely rejects invalid dispatches.
1194  *
1195  * State Transitions
1196  *
1197  *       .------------> NONE (owned by SCX core)
1198  *       |               |           ^
1199  *       |       enqueue |           | direct dispatch
1200  *       |               v           |
1201  *       |           QUEUEING -------'
1202  *       |               |
1203  *       |       enqueue |
1204  *       |     completes |
1205  *       |               v
1206  *       |            QUEUED (owned by BPF scheduler)
1207  *       |               |
1208  *       |      dispatch |
1209  *       |               |
1210  *       |               v
1211  *       |          DISPATCHING
1212  *       |               |
1213  *       |      dispatch |
1214  *       |     completes |
1215  *       `---------------'
1216  *
1217  * State Descriptions
1218  *
1219  * - %SCX_OPSS_NONE:
1220  *     Task is owned by the SCX core. It's either on a run queue, running,
1221  *     or being manipulated by the core scheduler. The BPF scheduler has no
1222  *     claim on this task.
1223  *
1224  * - %SCX_OPSS_QUEUEING:
1225  *     Transitional state while transferring a task from the SCX core to
1226  *     the BPF scheduler. The task's rq lock is held during this state.
1227  *     Since QUEUEING is both entered and exited under the rq lock, dequeue
1228  *     can never observe this state (it would be a BUG). When finishing a
1229  *     dispatch, if the task is still in %SCX_OPSS_QUEUEING the completion
1230  *     path busy-waits for it to leave this state (via wait_ops_state())
1231  *     before retrying.
1232  *
1233  * - %SCX_OPSS_QUEUED:
1234  *     Task is owned by the BPF scheduler. It's on a DSQ (dispatch queue)
1235  *     and the BPF scheduler is responsible for dispatching it. A QSEQ
1236  *     (queue sequence number) is embedded in this state to detect
1237  *     dispatch/dequeue races: if a task is dequeued and re-enqueued, the
1238  *     QSEQ changes and any in-flight dispatch operations targeting the old
1239  *     QSEQ are safely ignored.
1240  *
1241  * - %SCX_OPSS_DISPATCHING:
1242  *     Transitional state while transferring a task from the BPF scheduler
1243  *     back to the SCX core. This state indicates the BPF scheduler has
1244  *     selected the task for execution. When dequeue needs to take the task
1245  *     off a DSQ and it is still in %SCX_OPSS_DISPATCHING, the dequeue path
1246  *     busy-waits for it to leave this state (via wait_ops_state()) before
1247  *     proceeding. Exits to %SCX_OPSS_NONE when dispatch completes.
1248  *
1249  * Memory Ordering
1250  *
1251  * Transitions out of %SCX_OPSS_QUEUEING and %SCX_OPSS_DISPATCHING into
1252  * %SCX_OPSS_NONE or %SCX_OPSS_QUEUED must use atomic_long_set_release()
1253  * and waiters must use atomic_long_read_acquire(). This ensures proper
1254  * synchronization between concurrent operations.
1255  *
1256  * Cross-CPU Task Migration
1257  *
1258  * When moving a task in the %SCX_OPSS_DISPATCHING state, we can't simply
1259  * grab the target CPU's rq lock because a concurrent dequeue might be
1260  * waiting on %SCX_OPSS_DISPATCHING while holding the source rq lock
1261  * (deadlock).
1262  *
1263  * The sched_ext core uses a "lock dancing" protocol coordinated by
1264  * p->scx.holding_cpu. When moving a task to a different rq:
1265  *
1266  *   1. Verify task can be moved (CPU affinity, migration_disabled, etc.)
1267  *   2. Set p->scx.holding_cpu to the current CPU
1268  *   3. Set task state to %SCX_OPSS_NONE; dequeue waits while DISPATCHING
1269  *      is set, so clearing DISPATCHING first prevents the circular wait
1270  *      (safe to lock the rq we need)
1271  *   4. Unlock the current CPU's rq
1272  *   5. Lock src_rq (where the task currently lives)
1273  *   6. Verify p->scx.holding_cpu == current CPU, if not, dequeue won the
1274  *      race (dequeue clears holding_cpu to -1 when it takes the task), in
1275  *      this case migration is aborted
1276  *   7. If src_rq == dst_rq: clear holding_cpu and enqueue directly
1277  *      into dst_rq's local DSQ (no lock swap needed)
1278  *   8. Otherwise: call move_remote_task_to_local_dsq(), which releases
1279  *      src_rq, locks dst_rq, and performs the deactivate/activate
1280  *      migration cycle (dst_rq is held on return)
1281  *   9. Unlock dst_rq and re-lock the current CPU's rq to restore
1282  *      the lock state expected by the caller
1283  *
1284  * If any verification fails, abort the migration.
1285  *
1286  * This state tracking allows the BPF scheduler to try to dispatch any task
1287  * at any time regardless of its state. The SCX core can safely
1288  * reject/ignore invalid dispatches, simplifying the BPF scheduler
1289  * implementation.
1290  */
1291 enum scx_ops_state {
1292 	SCX_OPSS_NONE,		/* owned by the SCX core */
1293 	SCX_OPSS_QUEUEING,	/* in transit to the BPF scheduler */
1294 	SCX_OPSS_QUEUED,	/* owned by the BPF scheduler */
1295 	SCX_OPSS_DISPATCHING,	/* in transit back to the SCX core */
1296 
1297 	/*
1298 	 * QSEQ brands each QUEUED instance so that, when dispatch races
1299 	 * dequeue/requeue, the dispatcher can tell whether it still has a claim
1300 	 * on the task being dispatched.
1301 	 *
1302 	 * As some 32bit archs can't do 64bit store_release/load_acquire,
1303 	 * p->scx.ops_state is atomic_long_t which leaves 30 bits for QSEQ on
1304 	 * 32bit machines. The dispatch race window QSEQ protects is very narrow
1305 	 * and runs with IRQ disabled. 30 bits should be sufficient.
1306 	 */
1307 	SCX_OPSS_QSEQ_SHIFT	= 2,
1308 };
1309 
1310 /* Use macros to ensure that the type is unsigned long for the masks */
1311 #define SCX_OPSS_STATE_MASK	((1LU << SCX_OPSS_QSEQ_SHIFT) - 1)
1312 #define SCX_OPSS_QSEQ_MASK	(~SCX_OPSS_STATE_MASK)
1313 
1314 extern struct scx_sched __rcu *scx_root;
1315 DECLARE_PER_CPU(struct rq *, scx_locked_rq_state);
1316 
1317 /*
1318  * Return the rq currently locked from an scx callback, or NULL if no rq is
1319  * locked.
1320  */
1321 static inline struct rq *scx_locked_rq(void)
1322 {
1323 	return __this_cpu_read(scx_locked_rq_state);
1324 }
1325 
1326 static inline bool scx_kf_allowed_if_unlocked(void)
1327 {
1328 	return !current->scx.kf_mask;
1329 }
1330 
1331 static inline bool scx_bypassing(struct scx_sched *sch, s32 cpu)
1332 {
1333 	return unlikely(per_cpu_ptr(sch->pcpu, cpu)->flags &
1334 			SCX_SCHED_PCPU_BYPASSING);
1335 }
1336 
1337 #ifdef CONFIG_EXT_SUB_SCHED
1338 /**
1339  * scx_task_sched - Find scx_sched scheduling a task
1340  * @p: task of interest
1341  *
1342  * Return @p's scheduler instance. Must be called with @p's pi_lock or rq lock
1343  * held.
1344  */
1345 static inline struct scx_sched *scx_task_sched(const struct task_struct *p)
1346 {
1347 	return rcu_dereference_protected(p->scx.sched,
1348 					 lockdep_is_held(&p->pi_lock) ||
1349 					 lockdep_is_held(__rq_lockp(task_rq(p))));
1350 }
1351 
1352 /**
1353  * scx_task_sched_rcu - Find scx_sched scheduling a task
1354  * @p: task of interest
1355  *
1356  * Return @p's scheduler instance. The returned scx_sched is RCU protected.
1357  */
1358 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p)
1359 {
1360 	return rcu_dereference_all(p->scx.sched);
1361 }
1362 
1363 /**
1364  * scx_task_on_sched - Is a task on the specified sched?
1365  * @sch: sched to test against
1366  * @p: task of interest
1367  *
1368  * Returns %true if @p is on @sch, %false otherwise.
1369  */
1370 static inline bool scx_task_on_sched(struct scx_sched *sch,
1371 				     const struct task_struct *p)
1372 {
1373 	return rcu_access_pointer(p->scx.sched) == sch;
1374 }
1375 
1376 /**
1377  * scx_prog_sched - Find scx_sched associated with a BPF prog
1378  * @aux: aux passed in from BPF to a kfunc
1379  *
1380  * To be called from kfuncs. Return the scheduler instance associated with the
1381  * BPF program given the implicit kfunc argument aux. The returned scx_sched is
1382  * RCU protected.
1383  */
1384 static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux)
1385 {
1386 	struct sched_ext_ops *ops;
1387 	struct scx_sched *root;
1388 
1389 	ops = bpf_prog_get_assoc_struct_ops(aux);
1390 	if (likely(ops))
1391 		return rcu_dereference_all(ops->priv);
1392 
1393 	root = rcu_dereference_all(scx_root);
1394 	if (root) {
1395 		/*
1396 		 * COMPAT-v6.19: Schedulers built before sub-sched support was
1397 		 * introduced may have unassociated non-struct_ops programs.
1398 		 */
1399 		if (!root->ops.sub_attach)
1400 			return root;
1401 
1402 		if (!root->warned_unassoc_progs) {
1403 			printk_deferred(KERN_WARNING "sched_ext: Unassociated program %s (id %d)\n",
1404 					aux->name, aux->id);
1405 			root->warned_unassoc_progs = true;
1406 		}
1407 	}
1408 
1409 	return NULL;
1410 }
1411 #else	/* CONFIG_EXT_SUB_SCHED */
1412 static inline struct scx_sched *scx_task_sched(const struct task_struct *p)
1413 {
1414 	return rcu_dereference_protected(scx_root,
1415 					 lockdep_is_held(&p->pi_lock) ||
1416 					 lockdep_is_held(__rq_lockp(task_rq(p))));
1417 }
1418 
1419 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p)
1420 {
1421 	return rcu_dereference_all(scx_root);
1422 }
1423 
1424 static inline bool scx_task_on_sched(struct scx_sched *sch,
1425 				     const struct task_struct *p)
1426 {
1427 	return true;
1428 }
1429 
1430 static struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux)
1431 {
1432 	return rcu_dereference_all(scx_root);
1433 }
1434 #endif	/* CONFIG_EXT_SUB_SCHED */
1435