xref: /linux/kernel/sched/ext.c (revision ddceadce63d9cb752c2472e220ded05cabaf7971)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * BPF extensible scheduler class: Documentation/scheduler/sched-ext.rst
4  *
5  * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
6  * Copyright (c) 2022 Tejun Heo <tj@kernel.org>
7  * Copyright (c) 2022 David Vernet <dvernet@meta.com>
8  */
9 #include <linux/btf_ids.h>
10 #include "ext_idle.h"
11 
12 #define SCX_OP_IDX(op)		(offsetof(struct sched_ext_ops, op) / sizeof(void (*)(void)))
13 
14 enum scx_consts {
15 	SCX_DSP_DFL_MAX_BATCH		= 32,
16 	SCX_DSP_MAX_LOOPS		= 32,
17 	SCX_WATCHDOG_MAX_TIMEOUT	= 30 * HZ,
18 
19 	SCX_EXIT_BT_LEN			= 64,
20 	SCX_EXIT_MSG_LEN		= 1024,
21 	SCX_EXIT_DUMP_DFL_LEN		= 32768,
22 
23 	SCX_CPUPERF_ONE			= SCHED_CAPACITY_SCALE,
24 
25 	/*
26 	 * Iterating all tasks may take a while. Periodically drop
27 	 * scx_tasks_lock to avoid causing e.g. CSD and RCU stalls.
28 	 */
29 	SCX_TASK_ITER_BATCH		= 32,
30 };
31 
32 enum scx_exit_kind {
33 	SCX_EXIT_NONE,
34 	SCX_EXIT_DONE,
35 
36 	SCX_EXIT_UNREG = 64,	/* user-space initiated unregistration */
37 	SCX_EXIT_UNREG_BPF,	/* BPF-initiated unregistration */
38 	SCX_EXIT_UNREG_KERN,	/* kernel-initiated unregistration */
39 	SCX_EXIT_SYSRQ,		/* requested by 'S' sysrq */
40 
41 	SCX_EXIT_ERROR = 1024,	/* runtime error, error msg contains details */
42 	SCX_EXIT_ERROR_BPF,	/* ERROR but triggered through scx_bpf_error() */
43 	SCX_EXIT_ERROR_STALL,	/* watchdog detected stalled runnable tasks */
44 };
45 
46 /*
47  * An exit code can be specified when exiting with scx_bpf_exit() or scx_exit(),
48  * corresponding to exit_kind UNREG_BPF and UNREG_KERN respectively. The codes
49  * are 64bit of the format:
50  *
51  *   Bits: [63  ..  48 47   ..  32 31 .. 0]
52  *         [ SYS ACT ] [ SYS RSN ] [ USR  ]
53  *
54  *   SYS ACT: System-defined exit actions
55  *   SYS RSN: System-defined exit reasons
56  *   USR    : User-defined exit codes and reasons
57  *
58  * Using the above, users may communicate intention and context by ORing system
59  * actions and/or system reasons with a user-defined exit code.
60  */
61 enum scx_exit_code {
62 	/* Reasons */
63 	SCX_ECODE_RSN_HOTPLUG	= 1LLU << 32,
64 
65 	/* Actions */
66 	SCX_ECODE_ACT_RESTART	= 1LLU << 48,
67 };
68 
69 /*
70  * scx_exit_info is passed to ops.exit() to describe why the BPF scheduler is
71  * being disabled.
72  */
73 struct scx_exit_info {
74 	/* %SCX_EXIT_* - broad category of the exit reason */
75 	enum scx_exit_kind	kind;
76 
77 	/* exit code if gracefully exiting */
78 	s64			exit_code;
79 
80 	/* textual representation of the above */
81 	const char		*reason;
82 
83 	/* backtrace if exiting due to an error */
84 	unsigned long		*bt;
85 	u32			bt_len;
86 
87 	/* informational message */
88 	char			*msg;
89 
90 	/* debug dump */
91 	char			*dump;
92 };
93 
94 /* sched_ext_ops.flags */
95 enum scx_ops_flags {
96 	/*
97 	 * Keep built-in idle tracking even if ops.update_idle() is implemented.
98 	 */
99 	SCX_OPS_KEEP_BUILTIN_IDLE	= 1LLU << 0,
100 
101 	/*
102 	 * By default, if there are no other task to run on the CPU, ext core
103 	 * keeps running the current task even after its slice expires. If this
104 	 * flag is specified, such tasks are passed to ops.enqueue() with
105 	 * %SCX_ENQ_LAST. See the comment above %SCX_ENQ_LAST for more info.
106 	 */
107 	SCX_OPS_ENQ_LAST		= 1LLU << 1,
108 
109 	/*
110 	 * An exiting task may schedule after PF_EXITING is set. In such cases,
111 	 * bpf_task_from_pid() may not be able to find the task and if the BPF
112 	 * scheduler depends on pid lookup for dispatching, the task will be
113 	 * lost leading to various issues including RCU grace period stalls.
114 	 *
115 	 * To mask this problem, by default, unhashed tasks are automatically
116 	 * dispatched to the local DSQ on enqueue. If the BPF scheduler doesn't
117 	 * depend on pid lookups and wants to handle these tasks directly, the
118 	 * following flag can be used.
119 	 */
120 	SCX_OPS_ENQ_EXITING		= 1LLU << 2,
121 
122 	/*
123 	 * If set, only tasks with policy set to SCHED_EXT are attached to
124 	 * sched_ext. If clear, SCHED_NORMAL tasks are also included.
125 	 */
126 	SCX_OPS_SWITCH_PARTIAL		= 1LLU << 3,
127 
128 	/*
129 	 * A migration disabled task can only execute on its current CPU. By
130 	 * default, such tasks are automatically put on the CPU's local DSQ with
131 	 * the default slice on enqueue. If this ops flag is set, they also go
132 	 * through ops.enqueue().
133 	 *
134 	 * A migration disabled task never invokes ops.select_cpu() as it can
135 	 * only select the current CPU. Also, p->cpus_ptr will only contain its
136 	 * current CPU while p->nr_cpus_allowed keeps tracking p->user_cpus_ptr
137 	 * and thus may disagree with cpumask_weight(p->cpus_ptr).
138 	 */
139 	SCX_OPS_ENQ_MIGRATION_DISABLED	= 1LLU << 4,
140 
141 	/*
142 	 * Queued wakeup (ttwu_queue) is a wakeup optimization that invokes
143 	 * ops.enqueue() on the ops.select_cpu() selected or the wakee's
144 	 * previous CPU via IPI (inter-processor interrupt) to reduce cacheline
145 	 * transfers. When this optimization is enabled, ops.select_cpu() is
146 	 * skipped in some cases (when racing against the wakee switching out).
147 	 * As the BPF scheduler may depend on ops.select_cpu() being invoked
148 	 * during wakeups, queued wakeup is disabled by default.
149 	 *
150 	 * If this ops flag is set, queued wakeup optimization is enabled and
151 	 * the BPF scheduler must be able to handle ops.enqueue() invoked on the
152 	 * wakee's CPU without preceding ops.select_cpu() even for tasks which
153 	 * may be executed on multiple CPUs.
154 	 */
155 	SCX_OPS_ALLOW_QUEUED_WAKEUP	= 1LLU << 5,
156 
157 	/*
158 	 * If set, enable per-node idle cpumasks. If clear, use a single global
159 	 * flat idle cpumask.
160 	 */
161 	SCX_OPS_BUILTIN_IDLE_PER_NODE	= 1LLU << 6,
162 
163 	/*
164 	 * CPU cgroup support flags
165 	 */
166 	SCX_OPS_HAS_CGROUP_WEIGHT	= 1LLU << 16,	/* DEPRECATED, will be removed on 6.18 */
167 
168 	SCX_OPS_ALL_FLAGS		= SCX_OPS_KEEP_BUILTIN_IDLE |
169 					  SCX_OPS_ENQ_LAST |
170 					  SCX_OPS_ENQ_EXITING |
171 					  SCX_OPS_ENQ_MIGRATION_DISABLED |
172 					  SCX_OPS_ALLOW_QUEUED_WAKEUP |
173 					  SCX_OPS_SWITCH_PARTIAL |
174 					  SCX_OPS_BUILTIN_IDLE_PER_NODE |
175 					  SCX_OPS_HAS_CGROUP_WEIGHT,
176 
177 	/* high 8 bits are internal, don't include in SCX_OPS_ALL_FLAGS */
178 	__SCX_OPS_INTERNAL_MASK		= 0xffLLU << 56,
179 
180 	SCX_OPS_HAS_CPU_PREEMPT		= 1LLU << 56,
181 };
182 
183 /* argument container for ops.init_task() */
184 struct scx_init_task_args {
185 	/*
186 	 * Set if ops.init_task() is being invoked on the fork path, as opposed
187 	 * to the scheduler transition path.
188 	 */
189 	bool			fork;
190 #ifdef CONFIG_EXT_GROUP_SCHED
191 	/* the cgroup the task is joining */
192 	struct cgroup		*cgroup;
193 #endif
194 };
195 
196 /* argument container for ops.exit_task() */
197 struct scx_exit_task_args {
198 	/* Whether the task exited before running on sched_ext. */
199 	bool cancelled;
200 };
201 
202 /* argument container for ops->cgroup_init() */
203 struct scx_cgroup_init_args {
204 	/* the weight of the cgroup [1..10000] */
205 	u32			weight;
206 
207 	/* bandwidth control parameters from cpu.max and cpu.max.burst */
208 	u64			bw_period_us;
209 	u64			bw_quota_us;
210 	u64			bw_burst_us;
211 };
212 
213 enum scx_cpu_preempt_reason {
214 	/* next task is being scheduled by &sched_class_rt */
215 	SCX_CPU_PREEMPT_RT,
216 	/* next task is being scheduled by &sched_class_dl */
217 	SCX_CPU_PREEMPT_DL,
218 	/* next task is being scheduled by &sched_class_stop */
219 	SCX_CPU_PREEMPT_STOP,
220 	/* unknown reason for SCX being preempted */
221 	SCX_CPU_PREEMPT_UNKNOWN,
222 };
223 
224 /*
225  * Argument container for ops->cpu_acquire(). Currently empty, but may be
226  * expanded in the future.
227  */
228 struct scx_cpu_acquire_args {};
229 
230 /* argument container for ops->cpu_release() */
231 struct scx_cpu_release_args {
232 	/* the reason the CPU was preempted */
233 	enum scx_cpu_preempt_reason reason;
234 
235 	/* the task that's going to be scheduled on the CPU */
236 	struct task_struct	*task;
237 };
238 
239 /*
240  * Informational context provided to dump operations.
241  */
242 struct scx_dump_ctx {
243 	enum scx_exit_kind	kind;
244 	s64			exit_code;
245 	const char		*reason;
246 	u64			at_ns;
247 	u64			at_jiffies;
248 };
249 
250 /**
251  * struct sched_ext_ops - Operation table for BPF scheduler implementation
252  *
253  * A BPF scheduler can implement an arbitrary scheduling policy by
254  * implementing and loading operations in this table. Note that a userland
255  * scheduling policy can also be implemented using the BPF scheduler
256  * as a shim layer.
257  */
258 struct sched_ext_ops {
259 	/**
260 	 * @select_cpu: Pick the target CPU for a task which is being woken up
261 	 * @p: task being woken up
262 	 * @prev_cpu: the cpu @p was on before sleeping
263 	 * @wake_flags: SCX_WAKE_*
264 	 *
265 	 * Decision made here isn't final. @p may be moved to any CPU while it
266 	 * is getting dispatched for execution later. However, as @p is not on
267 	 * the rq at this point, getting the eventual execution CPU right here
268 	 * saves a small bit of overhead down the line.
269 	 *
270 	 * If an idle CPU is returned, the CPU is kicked and will try to
271 	 * dispatch. While an explicit custom mechanism can be added,
272 	 * select_cpu() serves as the default way to wake up idle CPUs.
273 	 *
274 	 * @p may be inserted into a DSQ directly by calling
275 	 * scx_bpf_dsq_insert(). If so, the ops.enqueue() will be skipped.
276 	 * Directly inserting into %SCX_DSQ_LOCAL will put @p in the local DSQ
277 	 * of the CPU returned by this operation.
278 	 *
279 	 * Note that select_cpu() is never called for tasks that can only run
280 	 * on a single CPU or tasks with migration disabled, as they don't have
281 	 * the option to select a different CPU. See select_task_rq() for
282 	 * details.
283 	 */
284 	s32 (*select_cpu)(struct task_struct *p, s32 prev_cpu, u64 wake_flags);
285 
286 	/**
287 	 * @enqueue: Enqueue a task on the BPF scheduler
288 	 * @p: task being enqueued
289 	 * @enq_flags: %SCX_ENQ_*
290 	 *
291 	 * @p is ready to run. Insert directly into a DSQ by calling
292 	 * scx_bpf_dsq_insert() or enqueue on the BPF scheduler. If not directly
293 	 * inserted, the bpf scheduler owns @p and if it fails to dispatch @p,
294 	 * the task will stall.
295 	 *
296 	 * If @p was inserted into a DSQ from ops.select_cpu(), this callback is
297 	 * skipped.
298 	 */
299 	void (*enqueue)(struct task_struct *p, u64 enq_flags);
300 
301 	/**
302 	 * @dequeue: Remove a task from the BPF scheduler
303 	 * @p: task being dequeued
304 	 * @deq_flags: %SCX_DEQ_*
305 	 *
306 	 * Remove @p from the BPF scheduler. This is usually called to isolate
307 	 * the task while updating its scheduling properties (e.g. priority).
308 	 *
309 	 * The ext core keeps track of whether the BPF side owns a given task or
310 	 * not and can gracefully ignore spurious dispatches from BPF side,
311 	 * which makes it safe to not implement this method. However, depending
312 	 * on the scheduling logic, this can lead to confusing behaviors - e.g.
313 	 * scheduling position not being updated across a priority change.
314 	 */
315 	void (*dequeue)(struct task_struct *p, u64 deq_flags);
316 
317 	/**
318 	 * @dispatch: Dispatch tasks from the BPF scheduler and/or user DSQs
319 	 * @cpu: CPU to dispatch tasks for
320 	 * @prev: previous task being switched out
321 	 *
322 	 * Called when a CPU's local dsq is empty. The operation should dispatch
323 	 * one or more tasks from the BPF scheduler into the DSQs using
324 	 * scx_bpf_dsq_insert() and/or move from user DSQs into the local DSQ
325 	 * using scx_bpf_dsq_move_to_local().
326 	 *
327 	 * The maximum number of times scx_bpf_dsq_insert() can be called
328 	 * without an intervening scx_bpf_dsq_move_to_local() is specified by
329 	 * ops.dispatch_max_batch. See the comments on top of the two functions
330 	 * for more details.
331 	 *
332 	 * When not %NULL, @prev is an SCX task with its slice depleted. If
333 	 * @prev is still runnable as indicated by set %SCX_TASK_QUEUED in
334 	 * @prev->scx.flags, it is not enqueued yet and will be enqueued after
335 	 * ops.dispatch() returns. To keep executing @prev, return without
336 	 * dispatching or moving any tasks. Also see %SCX_OPS_ENQ_LAST.
337 	 */
338 	void (*dispatch)(s32 cpu, struct task_struct *prev);
339 
340 	/**
341 	 * @tick: Periodic tick
342 	 * @p: task running currently
343 	 *
344 	 * This operation is called every 1/HZ seconds on CPUs which are
345 	 * executing an SCX task. Setting @p->scx.slice to 0 will trigger an
346 	 * immediate dispatch cycle on the CPU.
347 	 */
348 	void (*tick)(struct task_struct *p);
349 
350 	/**
351 	 * @runnable: A task is becoming runnable on its associated CPU
352 	 * @p: task becoming runnable
353 	 * @enq_flags: %SCX_ENQ_*
354 	 *
355 	 * This and the following three functions can be used to track a task's
356 	 * execution state transitions. A task becomes ->runnable() on a CPU,
357 	 * and then goes through one or more ->running() and ->stopping() pairs
358 	 * as it runs on the CPU, and eventually becomes ->quiescent() when it's
359 	 * done running on the CPU.
360 	 *
361 	 * @p is becoming runnable on the CPU because it's
362 	 *
363 	 * - waking up (%SCX_ENQ_WAKEUP)
364 	 * - being moved from another CPU
365 	 * - being restored after temporarily taken off the queue for an
366 	 *   attribute change.
367 	 *
368 	 * This and ->enqueue() are related but not coupled. This operation
369 	 * notifies @p's state transition and may not be followed by ->enqueue()
370 	 * e.g. when @p is being dispatched to a remote CPU, or when @p is
371 	 * being enqueued on a CPU experiencing a hotplug event. Likewise, a
372 	 * task may be ->enqueue()'d without being preceded by this operation
373 	 * e.g. after exhausting its slice.
374 	 */
375 	void (*runnable)(struct task_struct *p, u64 enq_flags);
376 
377 	/**
378 	 * @running: A task is starting to run on its associated CPU
379 	 * @p: task starting to run
380 	 *
381 	 * Note that this callback may be called from a CPU other than the
382 	 * one the task is going to run on. This can happen when a task
383 	 * property is changed (i.e., affinity), since scx_next_task_scx(),
384 	 * which triggers this callback, may run on a CPU different from
385 	 * the task's assigned CPU.
386 	 *
387 	 * Therefore, always use scx_bpf_task_cpu(@p) to determine the
388 	 * target CPU the task is going to use.
389 	 *
390 	 * See ->runnable() for explanation on the task state notifiers.
391 	 */
392 	void (*running)(struct task_struct *p);
393 
394 	/**
395 	 * @stopping: A task is stopping execution
396 	 * @p: task stopping to run
397 	 * @runnable: is task @p still runnable?
398 	 *
399 	 * Note that this callback may be called from a CPU other than the
400 	 * one the task was running on. This can happen when a task
401 	 * property is changed (i.e., affinity), since dequeue_task_scx(),
402 	 * which triggers this callback, may run on a CPU different from
403 	 * the task's assigned CPU.
404 	 *
405 	 * Therefore, always use scx_bpf_task_cpu(@p) to retrieve the CPU
406 	 * the task was running on.
407 	 *
408 	 * See ->runnable() for explanation on the task state notifiers. If
409 	 * !@runnable, ->quiescent() will be invoked after this operation
410 	 * returns.
411 	 */
412 	void (*stopping)(struct task_struct *p, bool runnable);
413 
414 	/**
415 	 * @quiescent: A task is becoming not runnable on its associated CPU
416 	 * @p: task becoming not runnable
417 	 * @deq_flags: %SCX_DEQ_*
418 	 *
419 	 * See ->runnable() for explanation on the task state notifiers.
420 	 *
421 	 * @p is becoming quiescent on the CPU because it's
422 	 *
423 	 * - sleeping (%SCX_DEQ_SLEEP)
424 	 * - being moved to another CPU
425 	 * - being temporarily taken off the queue for an attribute change
426 	 *   (%SCX_DEQ_SAVE)
427 	 *
428 	 * This and ->dequeue() are related but not coupled. This operation
429 	 * notifies @p's state transition and may not be preceded by ->dequeue()
430 	 * e.g. when @p is being dispatched to a remote CPU.
431 	 */
432 	void (*quiescent)(struct task_struct *p, u64 deq_flags);
433 
434 	/**
435 	 * @yield: Yield CPU
436 	 * @from: yielding task
437 	 * @to: optional yield target task
438 	 *
439 	 * If @to is NULL, @from is yielding the CPU to other runnable tasks.
440 	 * The BPF scheduler should ensure that other available tasks are
441 	 * dispatched before the yielding task. Return value is ignored in this
442 	 * case.
443 	 *
444 	 * If @to is not-NULL, @from wants to yield the CPU to @to. If the bpf
445 	 * scheduler can implement the request, return %true; otherwise, %false.
446 	 */
447 	bool (*yield)(struct task_struct *from, struct task_struct *to);
448 
449 	/**
450 	 * @core_sched_before: Task ordering for core-sched
451 	 * @a: task A
452 	 * @b: task B
453 	 *
454 	 * Used by core-sched to determine the ordering between two tasks. See
455 	 * Documentation/admin-guide/hw-vuln/core-scheduling.rst for details on
456 	 * core-sched.
457 	 *
458 	 * Both @a and @b are runnable and may or may not currently be queued on
459 	 * the BPF scheduler. Should return %true if @a should run before @b.
460 	 * %false if there's no required ordering or @b should run before @a.
461 	 *
462 	 * If not specified, the default is ordering them according to when they
463 	 * became runnable.
464 	 */
465 	bool (*core_sched_before)(struct task_struct *a, struct task_struct *b);
466 
467 	/**
468 	 * @set_weight: Set task weight
469 	 * @p: task to set weight for
470 	 * @weight: new weight [1..10000]
471 	 *
472 	 * Update @p's weight to @weight.
473 	 */
474 	void (*set_weight)(struct task_struct *p, u32 weight);
475 
476 	/**
477 	 * @set_cpumask: Set CPU affinity
478 	 * @p: task to set CPU affinity for
479 	 * @cpumask: cpumask of cpus that @p can run on
480 	 *
481 	 * Update @p's CPU affinity to @cpumask.
482 	 */
483 	void (*set_cpumask)(struct task_struct *p,
484 			    const struct cpumask *cpumask);
485 
486 	/**
487 	 * @update_idle: Update the idle state of a CPU
488 	 * @cpu: CPU to update the idle state for
489 	 * @idle: whether entering or exiting the idle state
490 	 *
491 	 * This operation is called when @rq's CPU goes or leaves the idle
492 	 * state. By default, implementing this operation disables the built-in
493 	 * idle CPU tracking and the following helpers become unavailable:
494 	 *
495 	 * - scx_bpf_select_cpu_dfl()
496 	 * - scx_bpf_select_cpu_and()
497 	 * - scx_bpf_test_and_clear_cpu_idle()
498 	 * - scx_bpf_pick_idle_cpu()
499 	 *
500 	 * The user also must implement ops.select_cpu() as the default
501 	 * implementation relies on scx_bpf_select_cpu_dfl().
502 	 *
503 	 * Specify the %SCX_OPS_KEEP_BUILTIN_IDLE flag to keep the built-in idle
504 	 * tracking.
505 	 */
506 	void (*update_idle)(s32 cpu, bool idle);
507 
508 	/**
509 	 * @cpu_acquire: A CPU is becoming available to the BPF scheduler
510 	 * @cpu: The CPU being acquired by the BPF scheduler.
511 	 * @args: Acquire arguments, see the struct definition.
512 	 *
513 	 * A CPU that was previously released from the BPF scheduler is now once
514 	 * again under its control.
515 	 */
516 	void (*cpu_acquire)(s32 cpu, struct scx_cpu_acquire_args *args);
517 
518 	/**
519 	 * @cpu_release: A CPU is taken away from the BPF scheduler
520 	 * @cpu: The CPU being released by the BPF scheduler.
521 	 * @args: Release arguments, see the struct definition.
522 	 *
523 	 * The specified CPU is no longer under the control of the BPF
524 	 * scheduler. This could be because it was preempted by a higher
525 	 * priority sched_class, though there may be other reasons as well. The
526 	 * caller should consult @args->reason to determine the cause.
527 	 */
528 	void (*cpu_release)(s32 cpu, struct scx_cpu_release_args *args);
529 
530 	/**
531 	 * @init_task: Initialize a task to run in a BPF scheduler
532 	 * @p: task to initialize for BPF scheduling
533 	 * @args: init arguments, see the struct definition
534 	 *
535 	 * Either we're loading a BPF scheduler or a new task is being forked.
536 	 * Initialize @p for BPF scheduling. This operation may block and can
537 	 * be used for allocations, and is called exactly once for a task.
538 	 *
539 	 * Return 0 for success, -errno for failure. An error return while
540 	 * loading will abort loading of the BPF scheduler. During a fork, it
541 	 * will abort that specific fork.
542 	 */
543 	s32 (*init_task)(struct task_struct *p, struct scx_init_task_args *args);
544 
545 	/**
546 	 * @exit_task: Exit a previously-running task from the system
547 	 * @p: task to exit
548 	 * @args: exit arguments, see the struct definition
549 	 *
550 	 * @p is exiting or the BPF scheduler is being unloaded. Perform any
551 	 * necessary cleanup for @p.
552 	 */
553 	void (*exit_task)(struct task_struct *p, struct scx_exit_task_args *args);
554 
555 	/**
556 	 * @enable: Enable BPF scheduling for a task
557 	 * @p: task to enable BPF scheduling for
558 	 *
559 	 * Enable @p for BPF scheduling. enable() is called on @p any time it
560 	 * enters SCX, and is always paired with a matching disable().
561 	 */
562 	void (*enable)(struct task_struct *p);
563 
564 	/**
565 	 * @disable: Disable BPF scheduling for a task
566 	 * @p: task to disable BPF scheduling for
567 	 *
568 	 * @p is exiting, leaving SCX or the BPF scheduler is being unloaded.
569 	 * Disable BPF scheduling for @p. A disable() call is always matched
570 	 * with a prior enable() call.
571 	 */
572 	void (*disable)(struct task_struct *p);
573 
574 	/**
575 	 * @dump: Dump BPF scheduler state on error
576 	 * @ctx: debug dump context
577 	 *
578 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump.
579 	 */
580 	void (*dump)(struct scx_dump_ctx *ctx);
581 
582 	/**
583 	 * @dump_cpu: Dump BPF scheduler state for a CPU on error
584 	 * @ctx: debug dump context
585 	 * @cpu: CPU to generate debug dump for
586 	 * @idle: @cpu is currently idle without any runnable tasks
587 	 *
588 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
589 	 * @cpu. If @idle is %true and this operation doesn't produce any
590 	 * output, @cpu is skipped for dump.
591 	 */
592 	void (*dump_cpu)(struct scx_dump_ctx *ctx, s32 cpu, bool idle);
593 
594 	/**
595 	 * @dump_task: Dump BPF scheduler state for a runnable task on error
596 	 * @ctx: debug dump context
597 	 * @p: runnable task to generate debug dump for
598 	 *
599 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
600 	 * @p.
601 	 */
602 	void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p);
603 
604 #ifdef CONFIG_EXT_GROUP_SCHED
605 	/**
606 	 * @cgroup_init: Initialize a cgroup
607 	 * @cgrp: cgroup being initialized
608 	 * @args: init arguments, see the struct definition
609 	 *
610 	 * Either the BPF scheduler is being loaded or @cgrp created, initialize
611 	 * @cgrp for sched_ext. This operation may block.
612 	 *
613 	 * Return 0 for success, -errno for failure. An error return while
614 	 * loading will abort loading of the BPF scheduler. During cgroup
615 	 * creation, it will abort the specific cgroup creation.
616 	 */
617 	s32 (*cgroup_init)(struct cgroup *cgrp,
618 			   struct scx_cgroup_init_args *args);
619 
620 	/**
621 	 * @cgroup_exit: Exit a cgroup
622 	 * @cgrp: cgroup being exited
623 	 *
624 	 * Either the BPF scheduler is being unloaded or @cgrp destroyed, exit
625 	 * @cgrp for sched_ext. This operation my block.
626 	 */
627 	void (*cgroup_exit)(struct cgroup *cgrp);
628 
629 	/**
630 	 * @cgroup_prep_move: Prepare a task to be moved to a different cgroup
631 	 * @p: task being moved
632 	 * @from: cgroup @p is being moved from
633 	 * @to: cgroup @p is being moved to
634 	 *
635 	 * Prepare @p for move from cgroup @from to @to. This operation may
636 	 * block and can be used for allocations.
637 	 *
638 	 * Return 0 for success, -errno for failure. An error return aborts the
639 	 * migration.
640 	 */
641 	s32 (*cgroup_prep_move)(struct task_struct *p,
642 				struct cgroup *from, struct cgroup *to);
643 
644 	/**
645 	 * @cgroup_move: Commit cgroup move
646 	 * @p: task being moved
647 	 * @from: cgroup @p is being moved from
648 	 * @to: cgroup @p is being moved to
649 	 *
650 	 * Commit the move. @p is dequeued during this operation.
651 	 */
652 	void (*cgroup_move)(struct task_struct *p,
653 			    struct cgroup *from, struct cgroup *to);
654 
655 	/**
656 	 * @cgroup_cancel_move: Cancel cgroup move
657 	 * @p: task whose cgroup move is being canceled
658 	 * @from: cgroup @p was being moved from
659 	 * @to: cgroup @p was being moved to
660 	 *
661 	 * @p was cgroup_prep_move()'d but failed before reaching cgroup_move().
662 	 * Undo the preparation.
663 	 */
664 	void (*cgroup_cancel_move)(struct task_struct *p,
665 				   struct cgroup *from, struct cgroup *to);
666 
667 	/**
668 	 * @cgroup_set_weight: A cgroup's weight is being changed
669 	 * @cgrp: cgroup whose weight is being updated
670 	 * @weight: new weight [1..10000]
671 	 *
672 	 * Update @cgrp's weight to @weight.
673 	 */
674 	void (*cgroup_set_weight)(struct cgroup *cgrp, u32 weight);
675 
676 	/**
677 	 * @cgroup_set_bandwidth: A cgroup's bandwidth is being changed
678 	 * @cgrp: cgroup whose bandwidth is being updated
679 	 * @period_us: bandwidth control period
680 	 * @quota_us: bandwidth control quota
681 	 * @burst_us: bandwidth control burst
682 	 *
683 	 * Update @cgrp's bandwidth control parameters. This is from the cpu.max
684 	 * cgroup interface.
685 	 *
686 	 * @quota_us / @period_us determines the CPU bandwidth @cgrp is entitled
687 	 * to. For example, if @period_us is 1_000_000 and @quota_us is
688 	 * 2_500_000. @cgrp is entitled to 2.5 CPUs. @burst_us can be
689 	 * interpreted in the same fashion and specifies how much @cgrp can
690 	 * burst temporarily. The specific control mechanism and thus the
691 	 * interpretation of @period_us and burstiness is upto to the BPF
692 	 * scheduler.
693 	 */
694 	void (*cgroup_set_bandwidth)(struct cgroup *cgrp,
695 				     u64 period_us, u64 quota_us, u64 burst_us);
696 
697 #endif	/* CONFIG_EXT_GROUP_SCHED */
698 
699 	/*
700 	 * All online ops must come before ops.cpu_online().
701 	 */
702 
703 	/**
704 	 * @cpu_online: A CPU became online
705 	 * @cpu: CPU which just came up
706 	 *
707 	 * @cpu just came online. @cpu will not call ops.enqueue() or
708 	 * ops.dispatch(), nor run tasks associated with other CPUs beforehand.
709 	 */
710 	void (*cpu_online)(s32 cpu);
711 
712 	/**
713 	 * @cpu_offline: A CPU is going offline
714 	 * @cpu: CPU which is going offline
715 	 *
716 	 * @cpu is going offline. @cpu will not call ops.enqueue() or
717 	 * ops.dispatch(), nor run tasks associated with other CPUs afterwards.
718 	 */
719 	void (*cpu_offline)(s32 cpu);
720 
721 	/*
722 	 * All CPU hotplug ops must come before ops.init().
723 	 */
724 
725 	/**
726 	 * @init: Initialize the BPF scheduler
727 	 */
728 	s32 (*init)(void);
729 
730 	/**
731 	 * @exit: Clean up after the BPF scheduler
732 	 * @info: Exit info
733 	 *
734 	 * ops.exit() is also called on ops.init() failure, which is a bit
735 	 * unusual. This is to allow rich reporting through @info on how
736 	 * ops.init() failed.
737 	 */
738 	void (*exit)(struct scx_exit_info *info);
739 
740 	/**
741 	 * @dispatch_max_batch: Max nr of tasks that dispatch() can dispatch
742 	 */
743 	u32 dispatch_max_batch;
744 
745 	/**
746 	 * @flags: %SCX_OPS_* flags
747 	 */
748 	u64 flags;
749 
750 	/**
751 	 * @timeout_ms: The maximum amount of time, in milliseconds, that a
752 	 * runnable task should be able to wait before being scheduled. The
753 	 * maximum timeout may not exceed the default timeout of 30 seconds.
754 	 *
755 	 * Defaults to the maximum allowed timeout value of 30 seconds.
756 	 */
757 	u32 timeout_ms;
758 
759 	/**
760 	 * @exit_dump_len: scx_exit_info.dump buffer length. If 0, the default
761 	 * value of 32768 is used.
762 	 */
763 	u32 exit_dump_len;
764 
765 	/**
766 	 * @hotplug_seq: A sequence number that may be set by the scheduler to
767 	 * detect when a hotplug event has occurred during the loading process.
768 	 * If 0, no detection occurs. Otherwise, the scheduler will fail to
769 	 * load if the sequence number does not match @scx_hotplug_seq on the
770 	 * enable path.
771 	 */
772 	u64 hotplug_seq;
773 
774 	/**
775 	 * @name: BPF scheduler's name
776 	 *
777 	 * Must be a non-zero valid BPF object name including only isalnum(),
778 	 * '_' and '.' chars. Shows up in kernel.sched_ext_ops sysctl while the
779 	 * BPF scheduler is enabled.
780 	 */
781 	char name[SCX_OPS_NAME_LEN];
782 
783 	/* internal use only, must be NULL */
784 	void *priv;
785 };
786 
787 enum scx_opi {
788 	SCX_OPI_BEGIN			= 0,
789 	SCX_OPI_NORMAL_BEGIN		= 0,
790 	SCX_OPI_NORMAL_END		= SCX_OP_IDX(cpu_online),
791 	SCX_OPI_CPU_HOTPLUG_BEGIN	= SCX_OP_IDX(cpu_online),
792 	SCX_OPI_CPU_HOTPLUG_END		= SCX_OP_IDX(init),
793 	SCX_OPI_END			= SCX_OP_IDX(init),
794 };
795 
796 /*
797  * Collection of event counters. Event types are placed in descending order.
798  */
799 struct scx_event_stats {
800 	/*
801 	 * If ops.select_cpu() returns a CPU which can't be used by the task,
802 	 * the core scheduler code silently picks a fallback CPU.
803 	 */
804 	s64		SCX_EV_SELECT_CPU_FALLBACK;
805 
806 	/*
807 	 * When dispatching to a local DSQ, the CPU may have gone offline in
808 	 * the meantime. In this case, the task is bounced to the global DSQ.
809 	 */
810 	s64		SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE;
811 
812 	/*
813 	 * If SCX_OPS_ENQ_LAST is not set, the number of times that a task
814 	 * continued to run because there were no other tasks on the CPU.
815 	 */
816 	s64		SCX_EV_DISPATCH_KEEP_LAST;
817 
818 	/*
819 	 * If SCX_OPS_ENQ_EXITING is not set, the number of times that a task
820 	 * is dispatched to a local DSQ when exiting.
821 	 */
822 	s64		SCX_EV_ENQ_SKIP_EXITING;
823 
824 	/*
825 	 * If SCX_OPS_ENQ_MIGRATION_DISABLED is not set, the number of times a
826 	 * migration disabled task skips ops.enqueue() and is dispatched to its
827 	 * local DSQ.
828 	 */
829 	s64		SCX_EV_ENQ_SKIP_MIGRATION_DISABLED;
830 
831 	/*
832 	 * Total number of times a task's time slice was refilled with the
833 	 * default value (SCX_SLICE_DFL).
834 	 */
835 	s64		SCX_EV_REFILL_SLICE_DFL;
836 
837 	/*
838 	 * The total duration of bypass modes in nanoseconds.
839 	 */
840 	s64		SCX_EV_BYPASS_DURATION;
841 
842 	/*
843 	 * The number of tasks dispatched in the bypassing mode.
844 	 */
845 	s64		SCX_EV_BYPASS_DISPATCH;
846 
847 	/*
848 	 * The number of times the bypassing mode has been activated.
849 	 */
850 	s64		SCX_EV_BYPASS_ACTIVATE;
851 };
852 
853 struct scx_sched {
854 	struct sched_ext_ops	ops;
855 	DECLARE_BITMAP(has_op, SCX_OPI_END);
856 
857 	/*
858 	 * Dispatch queues.
859 	 *
860 	 * The global DSQ (%SCX_DSQ_GLOBAL) is split per-node for scalability.
861 	 * This is to avoid live-locking in bypass mode where all tasks are
862 	 * dispatched to %SCX_DSQ_GLOBAL and all CPUs consume from it. If
863 	 * per-node split isn't sufficient, it can be further split.
864 	 */
865 	struct rhashtable	dsq_hash;
866 	struct scx_dispatch_q	**global_dsqs;
867 
868 	/*
869 	 * The event counters are in a per-CPU variable to minimize the
870 	 * accounting overhead. A system-wide view on the event counter is
871 	 * constructed when requested by scx_bpf_events().
872 	 */
873 	struct scx_event_stats __percpu *event_stats_cpu;
874 
875 	bool			warned_zero_slice;
876 
877 	atomic_t		exit_kind;
878 	struct scx_exit_info	*exit_info;
879 
880 	struct kobject		kobj;
881 
882 	struct kthread_worker	*helper;
883 	struct irq_work		error_irq_work;
884 	struct kthread_work	disable_work;
885 	struct rcu_work		rcu_work;
886 };
887 
888 enum scx_wake_flags {
889 	/* expose select WF_* flags as enums */
890 	SCX_WAKE_FORK		= WF_FORK,
891 	SCX_WAKE_TTWU		= WF_TTWU,
892 	SCX_WAKE_SYNC		= WF_SYNC,
893 };
894 
895 enum scx_enq_flags {
896 	/* expose select ENQUEUE_* flags as enums */
897 	SCX_ENQ_WAKEUP		= ENQUEUE_WAKEUP,
898 	SCX_ENQ_HEAD		= ENQUEUE_HEAD,
899 	SCX_ENQ_CPU_SELECTED	= ENQUEUE_RQ_SELECTED,
900 
901 	/* high 32bits are SCX specific */
902 
903 	/*
904 	 * Set the following to trigger preemption when calling
905 	 * scx_bpf_dsq_insert() with a local dsq as the target. The slice of the
906 	 * current task is cleared to zero and the CPU is kicked into the
907 	 * scheduling path. Implies %SCX_ENQ_HEAD.
908 	 */
909 	SCX_ENQ_PREEMPT		= 1LLU << 32,
910 
911 	/*
912 	 * The task being enqueued was previously enqueued on the current CPU's
913 	 * %SCX_DSQ_LOCAL, but was removed from it in a call to the
914 	 * bpf_scx_reenqueue_local() kfunc. If bpf_scx_reenqueue_local() was
915 	 * invoked in a ->cpu_release() callback, and the task is again
916 	 * dispatched back to %SCX_LOCAL_DSQ by this current ->enqueue(), the
917 	 * task will not be scheduled on the CPU until at least the next invocation
918 	 * of the ->cpu_acquire() callback.
919 	 */
920 	SCX_ENQ_REENQ		= 1LLU << 40,
921 
922 	/*
923 	 * The task being enqueued is the only task available for the cpu. By
924 	 * default, ext core keeps executing such tasks but when
925 	 * %SCX_OPS_ENQ_LAST is specified, they're ops.enqueue()'d with the
926 	 * %SCX_ENQ_LAST flag set.
927 	 *
928 	 * The BPF scheduler is responsible for triggering a follow-up
929 	 * scheduling event. Otherwise, Execution may stall.
930 	 */
931 	SCX_ENQ_LAST		= 1LLU << 41,
932 
933 	/* high 8 bits are internal */
934 	__SCX_ENQ_INTERNAL_MASK	= 0xffLLU << 56,
935 
936 	SCX_ENQ_CLEAR_OPSS	= 1LLU << 56,
937 	SCX_ENQ_DSQ_PRIQ	= 1LLU << 57,
938 };
939 
940 enum scx_deq_flags {
941 	/* expose select DEQUEUE_* flags as enums */
942 	SCX_DEQ_SLEEP		= DEQUEUE_SLEEP,
943 
944 	/* high 32bits are SCX specific */
945 
946 	/*
947 	 * The generic core-sched layer decided to execute the task even though
948 	 * it hasn't been dispatched yet. Dequeue from the BPF side.
949 	 */
950 	SCX_DEQ_CORE_SCHED_EXEC	= 1LLU << 32,
951 };
952 
953 enum scx_pick_idle_cpu_flags {
954 	SCX_PICK_IDLE_CORE	= 1LLU << 0,	/* pick a CPU whose SMT siblings are also idle */
955 	SCX_PICK_IDLE_IN_NODE	= 1LLU << 1,	/* pick a CPU in the same target NUMA node */
956 };
957 
958 enum scx_kick_flags {
959 	/*
960 	 * Kick the target CPU if idle. Guarantees that the target CPU goes
961 	 * through at least one full scheduling cycle before going idle. If the
962 	 * target CPU can be determined to be currently not idle and going to go
963 	 * through a scheduling cycle before going idle, noop.
964 	 */
965 	SCX_KICK_IDLE		= 1LLU << 0,
966 
967 	/*
968 	 * Preempt the current task and execute the dispatch path. If the
969 	 * current task of the target CPU is an SCX task, its ->scx.slice is
970 	 * cleared to zero before the scheduling path is invoked so that the
971 	 * task expires and the dispatch path is invoked.
972 	 */
973 	SCX_KICK_PREEMPT	= 1LLU << 1,
974 
975 	/*
976 	 * Wait for the CPU to be rescheduled. The scx_bpf_kick_cpu() call will
977 	 * return after the target CPU finishes picking the next task.
978 	 */
979 	SCX_KICK_WAIT		= 1LLU << 2,
980 };
981 
982 enum scx_tg_flags {
983 	SCX_TG_ONLINE		= 1U << 0,
984 	SCX_TG_INITED		= 1U << 1,
985 };
986 
987 enum scx_enable_state {
988 	SCX_ENABLING,
989 	SCX_ENABLED,
990 	SCX_DISABLING,
991 	SCX_DISABLED,
992 };
993 
994 static const char *scx_enable_state_str[] = {
995 	[SCX_ENABLING]		= "enabling",
996 	[SCX_ENABLED]		= "enabled",
997 	[SCX_DISABLING]		= "disabling",
998 	[SCX_DISABLED]		= "disabled",
999 };
1000 
1001 /*
1002  * sched_ext_entity->ops_state
1003  *
1004  * Used to track the task ownership between the SCX core and the BPF scheduler.
1005  * State transitions look as follows:
1006  *
1007  * NONE -> QUEUEING -> QUEUED -> DISPATCHING
1008  *   ^              |                 |
1009  *   |              v                 v
1010  *   \-------------------------------/
1011  *
1012  * QUEUEING and DISPATCHING states can be waited upon. See wait_ops_state() call
1013  * sites for explanations on the conditions being waited upon and why they are
1014  * safe. Transitions out of them into NONE or QUEUED must store_release and the
1015  * waiters should load_acquire.
1016  *
1017  * Tracking scx_ops_state enables sched_ext core to reliably determine whether
1018  * any given task can be dispatched by the BPF scheduler at all times and thus
1019  * relaxes the requirements on the BPF scheduler. This allows the BPF scheduler
1020  * to try to dispatch any task anytime regardless of its state as the SCX core
1021  * can safely reject invalid dispatches.
1022  */
1023 enum scx_ops_state {
1024 	SCX_OPSS_NONE,		/* owned by the SCX core */
1025 	SCX_OPSS_QUEUEING,	/* in transit to the BPF scheduler */
1026 	SCX_OPSS_QUEUED,	/* owned by the BPF scheduler */
1027 	SCX_OPSS_DISPATCHING,	/* in transit back to the SCX core */
1028 
1029 	/*
1030 	 * QSEQ brands each QUEUED instance so that, when dispatch races
1031 	 * dequeue/requeue, the dispatcher can tell whether it still has a claim
1032 	 * on the task being dispatched.
1033 	 *
1034 	 * As some 32bit archs can't do 64bit store_release/load_acquire,
1035 	 * p->scx.ops_state is atomic_long_t which leaves 30 bits for QSEQ on
1036 	 * 32bit machines. The dispatch race window QSEQ protects is very narrow
1037 	 * and runs with IRQ disabled. 30 bits should be sufficient.
1038 	 */
1039 	SCX_OPSS_QSEQ_SHIFT	= 2,
1040 };
1041 
1042 /* Use macros to ensure that the type is unsigned long for the masks */
1043 #define SCX_OPSS_STATE_MASK	((1LU << SCX_OPSS_QSEQ_SHIFT) - 1)
1044 #define SCX_OPSS_QSEQ_MASK	(~SCX_OPSS_STATE_MASK)
1045 
1046 /*
1047  * NOTE: sched_ext is in the process of growing multiple scheduler support and
1048  * scx_root usage is in a transitional state. Naked dereferences are safe if the
1049  * caller is one of the tasks attached to SCX and explicit RCU dereference is
1050  * necessary otherwise. Naked scx_root dereferences trigger sparse warnings but
1051  * are used as temporary markers to indicate that the dereferences need to be
1052  * updated to point to the associated scheduler instances rather than scx_root.
1053  */
1054 static struct scx_sched __rcu *scx_root;
1055 
1056 /*
1057  * During exit, a task may schedule after losing its PIDs. When disabling the
1058  * BPF scheduler, we need to be able to iterate tasks in every state to
1059  * guarantee system safety. Maintain a dedicated task list which contains every
1060  * task between its fork and eventual free.
1061  */
1062 static DEFINE_SPINLOCK(scx_tasks_lock);
1063 static LIST_HEAD(scx_tasks);
1064 
1065 /* ops enable/disable */
1066 static DEFINE_MUTEX(scx_enable_mutex);
1067 DEFINE_STATIC_KEY_FALSE(__scx_enabled);
1068 DEFINE_STATIC_PERCPU_RWSEM(scx_fork_rwsem);
1069 static atomic_t scx_enable_state_var = ATOMIC_INIT(SCX_DISABLED);
1070 static unsigned long scx_in_softlockup;
1071 static atomic_t scx_breather_depth = ATOMIC_INIT(0);
1072 static int scx_bypass_depth;
1073 static bool scx_init_task_enabled;
1074 static bool scx_switching_all;
1075 DEFINE_STATIC_KEY_FALSE(__scx_switched_all);
1076 
1077 static atomic_long_t scx_nr_rejected = ATOMIC_LONG_INIT(0);
1078 static atomic_long_t scx_hotplug_seq = ATOMIC_LONG_INIT(0);
1079 
1080 /*
1081  * A monotically increasing sequence number that is incremented every time a
1082  * scheduler is enabled. This can be used by to check if any custom sched_ext
1083  * scheduler has ever been used in the system.
1084  */
1085 static atomic_long_t scx_enable_seq = ATOMIC_LONG_INIT(0);
1086 
1087 /*
1088  * The maximum amount of time in jiffies that a task may be runnable without
1089  * being scheduled on a CPU. If this timeout is exceeded, it will trigger
1090  * scx_error().
1091  */
1092 static unsigned long scx_watchdog_timeout;
1093 
1094 /*
1095  * The last time the delayed work was run. This delayed work relies on
1096  * ksoftirqd being able to run to service timer interrupts, so it's possible
1097  * that this work itself could get wedged. To account for this, we check that
1098  * it's not stalled in the timer tick, and trigger an error if it is.
1099  */
1100 static unsigned long scx_watchdog_timestamp = INITIAL_JIFFIES;
1101 
1102 static struct delayed_work scx_watchdog_work;
1103 
1104 /* for %SCX_KICK_WAIT */
1105 static unsigned long __percpu *scx_kick_cpus_pnt_seqs;
1106 
1107 /*
1108  * Direct dispatch marker.
1109  *
1110  * Non-NULL values are used for direct dispatch from enqueue path. A valid
1111  * pointer points to the task currently being enqueued. An ERR_PTR value is used
1112  * to indicate that direct dispatch has already happened.
1113  */
1114 static DEFINE_PER_CPU(struct task_struct *, direct_dispatch_task);
1115 
1116 static const struct rhashtable_params dsq_hash_params = {
1117 	.key_len		= sizeof_field(struct scx_dispatch_q, id),
1118 	.key_offset		= offsetof(struct scx_dispatch_q, id),
1119 	.head_offset		= offsetof(struct scx_dispatch_q, hash_node),
1120 };
1121 
1122 static LLIST_HEAD(dsqs_to_free);
1123 
1124 /* dispatch buf */
1125 struct scx_dsp_buf_ent {
1126 	struct task_struct	*task;
1127 	unsigned long		qseq;
1128 	u64			dsq_id;
1129 	u64			enq_flags;
1130 };
1131 
1132 static u32 scx_dsp_max_batch;
1133 
1134 struct scx_dsp_ctx {
1135 	struct rq		*rq;
1136 	u32			cursor;
1137 	u32			nr_tasks;
1138 	struct scx_dsp_buf_ent	buf[];
1139 };
1140 
1141 static struct scx_dsp_ctx __percpu *scx_dsp_ctx;
1142 
1143 /* string formatting from BPF */
1144 struct scx_bstr_buf {
1145 	u64			data[MAX_BPRINTF_VARARGS];
1146 	char			line[SCX_EXIT_MSG_LEN];
1147 };
1148 
1149 static DEFINE_RAW_SPINLOCK(scx_exit_bstr_buf_lock);
1150 static struct scx_bstr_buf scx_exit_bstr_buf;
1151 
1152 /* ops debug dump */
1153 struct scx_dump_data {
1154 	s32			cpu;
1155 	bool			first;
1156 	s32			cursor;
1157 	struct seq_buf		*s;
1158 	const char		*prefix;
1159 	struct scx_bstr_buf	buf;
1160 };
1161 
1162 static struct scx_dump_data scx_dump_data = {
1163 	.cpu			= -1,
1164 };
1165 
1166 /* /sys/kernel/sched_ext interface */
1167 static struct kset *scx_kset;
1168 
1169 #define CREATE_TRACE_POINTS
1170 #include <trace/events/sched_ext.h>
1171 
1172 static void process_ddsp_deferred_locals(struct rq *rq);
1173 static void scx_bpf_kick_cpu(s32 cpu, u64 flags);
1174 static void scx_vexit(struct scx_sched *sch, enum scx_exit_kind kind,
1175 		      s64 exit_code, const char *fmt, va_list args);
1176 
1177 static __printf(4, 5) void scx_exit(struct scx_sched *sch,
1178 				    enum scx_exit_kind kind, s64 exit_code,
1179 				    const char *fmt, ...)
1180 {
1181 	va_list args;
1182 
1183 	va_start(args, fmt);
1184 	scx_vexit(sch, kind, exit_code, fmt, args);
1185 	va_end(args);
1186 }
1187 
1188 static __printf(3, 4) void scx_kf_exit(enum scx_exit_kind kind, s64 exit_code,
1189 				       const char *fmt, ...)
1190 {
1191 	struct scx_sched *sch;
1192 	va_list args;
1193 
1194 	rcu_read_lock();
1195 	sch = rcu_dereference(scx_root);
1196 	if (sch) {
1197 		va_start(args, fmt);
1198 		scx_vexit(sch, kind, exit_code, fmt, args);
1199 		va_end(args);
1200 	}
1201 	rcu_read_unlock();
1202 }
1203 
1204 #define scx_error(sch, fmt, args...)	scx_exit((sch), SCX_EXIT_ERROR, 0, fmt, ##args)
1205 #define scx_kf_error(fmt, args...)	scx_kf_exit(SCX_EXIT_ERROR, 0, fmt, ##args)
1206 
1207 #define SCX_HAS_OP(sch, op)	test_bit(SCX_OP_IDX(op), (sch)->has_op)
1208 
1209 static long jiffies_delta_msecs(unsigned long at, unsigned long now)
1210 {
1211 	if (time_after(at, now))
1212 		return jiffies_to_msecs(at - now);
1213 	else
1214 		return -(long)jiffies_to_msecs(now - at);
1215 }
1216 
1217 /* if the highest set bit is N, return a mask with bits [N+1, 31] set */
1218 static u32 higher_bits(u32 flags)
1219 {
1220 	return ~((1 << fls(flags)) - 1);
1221 }
1222 
1223 /* return the mask with only the highest bit set */
1224 static u32 highest_bit(u32 flags)
1225 {
1226 	int bit = fls(flags);
1227 	return ((u64)1 << bit) >> 1;
1228 }
1229 
1230 static bool u32_before(u32 a, u32 b)
1231 {
1232 	return (s32)(a - b) < 0;
1233 }
1234 
1235 static struct scx_dispatch_q *find_global_dsq(struct task_struct *p)
1236 {
1237 	struct scx_sched *sch = scx_root;
1238 
1239 	return sch->global_dsqs[cpu_to_node(task_cpu(p))];
1240 }
1241 
1242 static struct scx_dispatch_q *find_user_dsq(struct scx_sched *sch, u64 dsq_id)
1243 {
1244 	return rhashtable_lookup_fast(&sch->dsq_hash, &dsq_id, dsq_hash_params);
1245 }
1246 
1247 /*
1248  * scx_kf_mask enforcement. Some kfuncs can only be called from specific SCX
1249  * ops. When invoking SCX ops, SCX_CALL_OP[_RET]() should be used to indicate
1250  * the allowed kfuncs and those kfuncs should use scx_kf_allowed() to check
1251  * whether it's running from an allowed context.
1252  *
1253  * @mask is constant, always inline to cull the mask calculations.
1254  */
1255 static __always_inline void scx_kf_allow(u32 mask)
1256 {
1257 	/* nesting is allowed only in increasing scx_kf_mask order */
1258 	WARN_ONCE((mask | higher_bits(mask)) & current->scx.kf_mask,
1259 		  "invalid nesting current->scx.kf_mask=0x%x mask=0x%x\n",
1260 		  current->scx.kf_mask, mask);
1261 	current->scx.kf_mask |= mask;
1262 	barrier();
1263 }
1264 
1265 static void scx_kf_disallow(u32 mask)
1266 {
1267 	barrier();
1268 	current->scx.kf_mask &= ~mask;
1269 }
1270 
1271 /*
1272  * Track the rq currently locked.
1273  *
1274  * This allows kfuncs to safely operate on rq from any scx ops callback,
1275  * knowing which rq is already locked.
1276  */
1277 DEFINE_PER_CPU(struct rq *, scx_locked_rq_state);
1278 
1279 static inline void update_locked_rq(struct rq *rq)
1280 {
1281 	/*
1282 	 * Check whether @rq is actually locked. This can help expose bugs
1283 	 * or incorrect assumptions about the context in which a kfunc or
1284 	 * callback is executed.
1285 	 */
1286 	if (rq)
1287 		lockdep_assert_rq_held(rq);
1288 	__this_cpu_write(scx_locked_rq_state, rq);
1289 }
1290 
1291 #define SCX_CALL_OP(sch, mask, op, rq, args...)					\
1292 do {										\
1293 	update_locked_rq(rq);							\
1294 	if (mask) {								\
1295 		scx_kf_allow(mask);						\
1296 		(sch)->ops.op(args);						\
1297 		scx_kf_disallow(mask);						\
1298 	} else {								\
1299 		(sch)->ops.op(args);						\
1300 	}									\
1301 	update_locked_rq(NULL);							\
1302 } while (0)
1303 
1304 #define SCX_CALL_OP_RET(sch, mask, op, rq, args...)				\
1305 ({										\
1306 	__typeof__((sch)->ops.op(args)) __ret;					\
1307 										\
1308 	update_locked_rq(rq);							\
1309 	if (mask) {								\
1310 		scx_kf_allow(mask);						\
1311 		__ret = (sch)->ops.op(args);					\
1312 		scx_kf_disallow(mask);						\
1313 	} else {								\
1314 		__ret = (sch)->ops.op(args);					\
1315 	}									\
1316 	update_locked_rq(NULL);							\
1317 	__ret;									\
1318 })
1319 
1320 /*
1321  * Some kfuncs are allowed only on the tasks that are subjects of the
1322  * in-progress scx_ops operation for, e.g., locking guarantees. To enforce such
1323  * restrictions, the following SCX_CALL_OP_*() variants should be used when
1324  * invoking scx_ops operations that take task arguments. These can only be used
1325  * for non-nesting operations due to the way the tasks are tracked.
1326  *
1327  * kfuncs which can only operate on such tasks can in turn use
1328  * scx_kf_allowed_on_arg_tasks() to test whether the invocation is allowed on
1329  * the specific task.
1330  */
1331 #define SCX_CALL_OP_TASK(sch, mask, op, rq, task, args...)			\
1332 do {										\
1333 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
1334 	current->scx.kf_tasks[0] = task;					\
1335 	SCX_CALL_OP((sch), mask, op, rq, task, ##args);				\
1336 	current->scx.kf_tasks[0] = NULL;					\
1337 } while (0)
1338 
1339 #define SCX_CALL_OP_TASK_RET(sch, mask, op, rq, task, args...)			\
1340 ({										\
1341 	__typeof__((sch)->ops.op(task, ##args)) __ret;				\
1342 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
1343 	current->scx.kf_tasks[0] = task;					\
1344 	__ret = SCX_CALL_OP_RET((sch), mask, op, rq, task, ##args);		\
1345 	current->scx.kf_tasks[0] = NULL;					\
1346 	__ret;									\
1347 })
1348 
1349 #define SCX_CALL_OP_2TASKS_RET(sch, mask, op, rq, task0, task1, args...)	\
1350 ({										\
1351 	__typeof__((sch)->ops.op(task0, task1, ##args)) __ret;			\
1352 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
1353 	current->scx.kf_tasks[0] = task0;					\
1354 	current->scx.kf_tasks[1] = task1;					\
1355 	__ret = SCX_CALL_OP_RET((sch), mask, op, rq, task0, task1, ##args);	\
1356 	current->scx.kf_tasks[0] = NULL;					\
1357 	current->scx.kf_tasks[1] = NULL;					\
1358 	__ret;									\
1359 })
1360 
1361 /* @mask is constant, always inline to cull unnecessary branches */
1362 static __always_inline bool scx_kf_allowed(u32 mask)
1363 {
1364 	if (unlikely(!(current->scx.kf_mask & mask))) {
1365 		scx_kf_error("kfunc with mask 0x%x called from an operation only allowing 0x%x",
1366 			     mask, current->scx.kf_mask);
1367 		return false;
1368 	}
1369 
1370 	/*
1371 	 * Enforce nesting boundaries. e.g. A kfunc which can be called from
1372 	 * DISPATCH must not be called if we're running DEQUEUE which is nested
1373 	 * inside ops.dispatch(). We don't need to check boundaries for any
1374 	 * blocking kfuncs as the verifier ensures they're only called from
1375 	 * sleepable progs.
1376 	 */
1377 	if (unlikely(highest_bit(mask) == SCX_KF_CPU_RELEASE &&
1378 		     (current->scx.kf_mask & higher_bits(SCX_KF_CPU_RELEASE)))) {
1379 		scx_kf_error("cpu_release kfunc called from a nested operation");
1380 		return false;
1381 	}
1382 
1383 	if (unlikely(highest_bit(mask) == SCX_KF_DISPATCH &&
1384 		     (current->scx.kf_mask & higher_bits(SCX_KF_DISPATCH)))) {
1385 		scx_kf_error("dispatch kfunc called from a nested operation");
1386 		return false;
1387 	}
1388 
1389 	return true;
1390 }
1391 
1392 /* see SCX_CALL_OP_TASK() */
1393 static __always_inline bool scx_kf_allowed_on_arg_tasks(u32 mask,
1394 							struct task_struct *p)
1395 {
1396 	if (!scx_kf_allowed(mask))
1397 		return false;
1398 
1399 	if (unlikely((p != current->scx.kf_tasks[0] &&
1400 		      p != current->scx.kf_tasks[1]))) {
1401 		scx_kf_error("called on a task not being operated on");
1402 		return false;
1403 	}
1404 
1405 	return true;
1406 }
1407 
1408 /**
1409  * nldsq_next_task - Iterate to the next task in a non-local DSQ
1410  * @dsq: user dsq being iterated
1411  * @cur: current position, %NULL to start iteration
1412  * @rev: walk backwards
1413  *
1414  * Returns %NULL when iteration is finished.
1415  */
1416 static struct task_struct *nldsq_next_task(struct scx_dispatch_q *dsq,
1417 					   struct task_struct *cur, bool rev)
1418 {
1419 	struct list_head *list_node;
1420 	struct scx_dsq_list_node *dsq_lnode;
1421 
1422 	lockdep_assert_held(&dsq->lock);
1423 
1424 	if (cur)
1425 		list_node = &cur->scx.dsq_list.node;
1426 	else
1427 		list_node = &dsq->list;
1428 
1429 	/* find the next task, need to skip BPF iteration cursors */
1430 	do {
1431 		if (rev)
1432 			list_node = list_node->prev;
1433 		else
1434 			list_node = list_node->next;
1435 
1436 		if (list_node == &dsq->list)
1437 			return NULL;
1438 
1439 		dsq_lnode = container_of(list_node, struct scx_dsq_list_node,
1440 					 node);
1441 	} while (dsq_lnode->flags & SCX_DSQ_LNODE_ITER_CURSOR);
1442 
1443 	return container_of(dsq_lnode, struct task_struct, scx.dsq_list);
1444 }
1445 
1446 #define nldsq_for_each_task(p, dsq)						\
1447 	for ((p) = nldsq_next_task((dsq), NULL, false); (p);			\
1448 	     (p) = nldsq_next_task((dsq), (p), false))
1449 
1450 
1451 /*
1452  * BPF DSQ iterator. Tasks in a non-local DSQ can be iterated in [reverse]
1453  * dispatch order. BPF-visible iterator is opaque and larger to allow future
1454  * changes without breaking backward compatibility. Can be used with
1455  * bpf_for_each(). See bpf_iter_scx_dsq_*().
1456  */
1457 enum scx_dsq_iter_flags {
1458 	/* iterate in the reverse dispatch order */
1459 	SCX_DSQ_ITER_REV		= 1U << 16,
1460 
1461 	__SCX_DSQ_ITER_HAS_SLICE	= 1U << 30,
1462 	__SCX_DSQ_ITER_HAS_VTIME	= 1U << 31,
1463 
1464 	__SCX_DSQ_ITER_USER_FLAGS	= SCX_DSQ_ITER_REV,
1465 	__SCX_DSQ_ITER_ALL_FLAGS	= __SCX_DSQ_ITER_USER_FLAGS |
1466 					  __SCX_DSQ_ITER_HAS_SLICE |
1467 					  __SCX_DSQ_ITER_HAS_VTIME,
1468 };
1469 
1470 struct bpf_iter_scx_dsq_kern {
1471 	struct scx_dsq_list_node	cursor;
1472 	struct scx_dispatch_q		*dsq;
1473 	u64				slice;
1474 	u64				vtime;
1475 } __attribute__((aligned(8)));
1476 
1477 struct bpf_iter_scx_dsq {
1478 	u64				__opaque[6];
1479 } __attribute__((aligned(8)));
1480 
1481 
1482 /*
1483  * SCX task iterator.
1484  */
1485 struct scx_task_iter {
1486 	struct sched_ext_entity		cursor;
1487 	struct task_struct		*locked;
1488 	struct rq			*rq;
1489 	struct rq_flags			rf;
1490 	u32				cnt;
1491 };
1492 
1493 /**
1494  * scx_task_iter_start - Lock scx_tasks_lock and start a task iteration
1495  * @iter: iterator to init
1496  *
1497  * Initialize @iter and return with scx_tasks_lock held. Once initialized, @iter
1498  * must eventually be stopped with scx_task_iter_stop().
1499  *
1500  * scx_tasks_lock and the rq lock may be released using scx_task_iter_unlock()
1501  * between this and the first next() call or between any two next() calls. If
1502  * the locks are released between two next() calls, the caller is responsible
1503  * for ensuring that the task being iterated remains accessible either through
1504  * RCU read lock or obtaining a reference count.
1505  *
1506  * All tasks which existed when the iteration started are guaranteed to be
1507  * visited as long as they still exist.
1508  */
1509 static void scx_task_iter_start(struct scx_task_iter *iter)
1510 {
1511 	BUILD_BUG_ON(__SCX_DSQ_ITER_ALL_FLAGS &
1512 		     ((1U << __SCX_DSQ_LNODE_PRIV_SHIFT) - 1));
1513 
1514 	spin_lock_irq(&scx_tasks_lock);
1515 
1516 	iter->cursor = (struct sched_ext_entity){ .flags = SCX_TASK_CURSOR };
1517 	list_add(&iter->cursor.tasks_node, &scx_tasks);
1518 	iter->locked = NULL;
1519 	iter->cnt = 0;
1520 }
1521 
1522 static void __scx_task_iter_rq_unlock(struct scx_task_iter *iter)
1523 {
1524 	if (iter->locked) {
1525 		task_rq_unlock(iter->rq, iter->locked, &iter->rf);
1526 		iter->locked = NULL;
1527 	}
1528 }
1529 
1530 /**
1531  * scx_task_iter_unlock - Unlock rq and scx_tasks_lock held by a task iterator
1532  * @iter: iterator to unlock
1533  *
1534  * If @iter is in the middle of a locked iteration, it may be locking the rq of
1535  * the task currently being visited in addition to scx_tasks_lock. Unlock both.
1536  * This function can be safely called anytime during an iteration.
1537  */
1538 static void scx_task_iter_unlock(struct scx_task_iter *iter)
1539 {
1540 	__scx_task_iter_rq_unlock(iter);
1541 	spin_unlock_irq(&scx_tasks_lock);
1542 }
1543 
1544 /**
1545  * scx_task_iter_relock - Lock scx_tasks_lock released by scx_task_iter_unlock()
1546  * @iter: iterator to re-lock
1547  *
1548  * Re-lock scx_tasks_lock unlocked by scx_task_iter_unlock(). Note that it
1549  * doesn't re-lock the rq lock. Must be called before other iterator operations.
1550  */
1551 static void scx_task_iter_relock(struct scx_task_iter *iter)
1552 {
1553 	spin_lock_irq(&scx_tasks_lock);
1554 }
1555 
1556 /**
1557  * scx_task_iter_stop - Stop a task iteration and unlock scx_tasks_lock
1558  * @iter: iterator to exit
1559  *
1560  * Exit a previously initialized @iter. Must be called with scx_tasks_lock held
1561  * which is released on return. If the iterator holds a task's rq lock, that rq
1562  * lock is also released. See scx_task_iter_start() for details.
1563  */
1564 static void scx_task_iter_stop(struct scx_task_iter *iter)
1565 {
1566 	list_del_init(&iter->cursor.tasks_node);
1567 	scx_task_iter_unlock(iter);
1568 }
1569 
1570 /**
1571  * scx_task_iter_next - Next task
1572  * @iter: iterator to walk
1573  *
1574  * Visit the next task. See scx_task_iter_start() for details. Locks are dropped
1575  * and re-acquired every %SCX_TASK_ITER_BATCH iterations to avoid causing stalls
1576  * by holding scx_tasks_lock for too long.
1577  */
1578 static struct task_struct *scx_task_iter_next(struct scx_task_iter *iter)
1579 {
1580 	struct list_head *cursor = &iter->cursor.tasks_node;
1581 	struct sched_ext_entity *pos;
1582 
1583 	if (!(++iter->cnt % SCX_TASK_ITER_BATCH)) {
1584 		scx_task_iter_unlock(iter);
1585 		cond_resched();
1586 		scx_task_iter_relock(iter);
1587 	}
1588 
1589 	list_for_each_entry(pos, cursor, tasks_node) {
1590 		if (&pos->tasks_node == &scx_tasks)
1591 			return NULL;
1592 		if (!(pos->flags & SCX_TASK_CURSOR)) {
1593 			list_move(cursor, &pos->tasks_node);
1594 			return container_of(pos, struct task_struct, scx);
1595 		}
1596 	}
1597 
1598 	/* can't happen, should always terminate at scx_tasks above */
1599 	BUG();
1600 }
1601 
1602 /**
1603  * scx_task_iter_next_locked - Next non-idle task with its rq locked
1604  * @iter: iterator to walk
1605  *
1606  * Visit the non-idle task with its rq lock held. Allows callers to specify
1607  * whether they would like to filter out dead tasks. See scx_task_iter_start()
1608  * for details.
1609  */
1610 static struct task_struct *scx_task_iter_next_locked(struct scx_task_iter *iter)
1611 {
1612 	struct task_struct *p;
1613 
1614 	__scx_task_iter_rq_unlock(iter);
1615 
1616 	while ((p = scx_task_iter_next(iter))) {
1617 		/*
1618 		 * scx_task_iter is used to prepare and move tasks into SCX
1619 		 * while loading the BPF scheduler and vice-versa while
1620 		 * unloading. The init_tasks ("swappers") should be excluded
1621 		 * from the iteration because:
1622 		 *
1623 		 * - It's unsafe to use __setschduler_prio() on an init_task to
1624 		 *   determine the sched_class to use as it won't preserve its
1625 		 *   idle_sched_class.
1626 		 *
1627 		 * - ops.init/exit_task() can easily be confused if called with
1628 		 *   init_tasks as they, e.g., share PID 0.
1629 		 *
1630 		 * As init_tasks are never scheduled through SCX, they can be
1631 		 * skipped safely. Note that is_idle_task() which tests %PF_IDLE
1632 		 * doesn't work here:
1633 		 *
1634 		 * - %PF_IDLE may not be set for an init_task whose CPU hasn't
1635 		 *   yet been onlined.
1636 		 *
1637 		 * - %PF_IDLE can be set on tasks that are not init_tasks. See
1638 		 *   play_idle_precise() used by CONFIG_IDLE_INJECT.
1639 		 *
1640 		 * Test for idle_sched_class as only init_tasks are on it.
1641 		 */
1642 		if (p->sched_class != &idle_sched_class)
1643 			break;
1644 	}
1645 	if (!p)
1646 		return NULL;
1647 
1648 	iter->rq = task_rq_lock(p, &iter->rf);
1649 	iter->locked = p;
1650 
1651 	return p;
1652 }
1653 
1654 /**
1655  * scx_add_event - Increase an event counter for 'name' by 'cnt'
1656  * @sch: scx_sched to account events for
1657  * @name: an event name defined in struct scx_event_stats
1658  * @cnt: the number of the event occured
1659  *
1660  * This can be used when preemption is not disabled.
1661  */
1662 #define scx_add_event(sch, name, cnt) do {					\
1663 	this_cpu_add((sch)->event_stats_cpu->name, (cnt));			\
1664 	trace_sched_ext_event(#name, (cnt));					\
1665 } while(0)
1666 
1667 /**
1668  * __scx_add_event - Increase an event counter for 'name' by 'cnt'
1669  * @sch: scx_sched to account events for
1670  * @name: an event name defined in struct scx_event_stats
1671  * @cnt: the number of the event occured
1672  *
1673  * This should be used only when preemption is disabled.
1674  */
1675 #define __scx_add_event(sch, name, cnt) do {					\
1676 	__this_cpu_add((sch)->event_stats_cpu->name, (cnt));			\
1677 	trace_sched_ext_event(#name, cnt);					\
1678 } while(0)
1679 
1680 /**
1681  * scx_agg_event - Aggregate an event counter 'kind' from 'src_e' to 'dst_e'
1682  * @dst_e: destination event stats
1683  * @src_e: source event stats
1684  * @kind: a kind of event to be aggregated
1685  */
1686 #define scx_agg_event(dst_e, src_e, kind) do {					\
1687 	(dst_e)->kind += READ_ONCE((src_e)->kind);				\
1688 } while(0)
1689 
1690 /**
1691  * scx_dump_event - Dump an event 'kind' in 'events' to 's'
1692  * @s: output seq_buf
1693  * @events: event stats
1694  * @kind: a kind of event to dump
1695  */
1696 #define scx_dump_event(s, events, kind) do {					\
1697 	dump_line(&(s), "%40s: %16lld", #kind, (events)->kind);			\
1698 } while (0)
1699 
1700 
1701 static void scx_read_events(struct scx_sched *sch,
1702 			    struct scx_event_stats *events);
1703 
1704 static enum scx_enable_state scx_enable_state(void)
1705 {
1706 	return atomic_read(&scx_enable_state_var);
1707 }
1708 
1709 static enum scx_enable_state scx_set_enable_state(enum scx_enable_state to)
1710 {
1711 	return atomic_xchg(&scx_enable_state_var, to);
1712 }
1713 
1714 static bool scx_tryset_enable_state(enum scx_enable_state to,
1715 				    enum scx_enable_state from)
1716 {
1717 	int from_v = from;
1718 
1719 	return atomic_try_cmpxchg(&scx_enable_state_var, &from_v, to);
1720 }
1721 
1722 /**
1723  * wait_ops_state - Busy-wait the specified ops state to end
1724  * @p: target task
1725  * @opss: state to wait the end of
1726  *
1727  * Busy-wait for @p to transition out of @opss. This can only be used when the
1728  * state part of @opss is %SCX_QUEUEING or %SCX_DISPATCHING. This function also
1729  * has load_acquire semantics to ensure that the caller can see the updates made
1730  * in the enqueueing and dispatching paths.
1731  */
1732 static void wait_ops_state(struct task_struct *p, unsigned long opss)
1733 {
1734 	do {
1735 		cpu_relax();
1736 	} while (atomic_long_read_acquire(&p->scx.ops_state) == opss);
1737 }
1738 
1739 static inline bool __cpu_valid(s32 cpu)
1740 {
1741 	return likely(cpu >= 0 && cpu < nr_cpu_ids && cpu_possible(cpu));
1742 }
1743 
1744 /**
1745  * ops_cpu_valid - Verify a cpu number, to be used on ops input args
1746  * @sch: scx_sched to abort on error
1747  * @cpu: cpu number which came from a BPF ops
1748  * @where: extra information reported on error
1749  *
1750  * @cpu is a cpu number which came from the BPF scheduler and can be any value.
1751  * Verify that it is in range and one of the possible cpus. If invalid, trigger
1752  * an ops error.
1753  */
1754 static bool ops_cpu_valid(struct scx_sched *sch, s32 cpu, const char *where)
1755 {
1756 	if (__cpu_valid(cpu)) {
1757 		return true;
1758 	} else {
1759 		scx_error(sch, "invalid CPU %d%s%s", cpu, where ? " " : "", where ?: "");
1760 		return false;
1761 	}
1762 }
1763 
1764 /**
1765  * kf_cpu_valid - Verify a CPU number, to be used on kfunc input args
1766  * @cpu: cpu number which came from a BPF ops
1767  * @where: extra information reported on error
1768  *
1769  * The same as ops_cpu_valid() but @sch is implicit.
1770  */
1771 static bool kf_cpu_valid(u32 cpu, const char *where)
1772 {
1773 	if (__cpu_valid(cpu)) {
1774 		return true;
1775 	} else {
1776 		scx_kf_error("invalid CPU %d%s%s", cpu, where ? " " : "", where ?: "");
1777 		return false;
1778 	}
1779 }
1780 
1781 /**
1782  * ops_sanitize_err - Sanitize a -errno value
1783  * @sch: scx_sched to error out on error
1784  * @ops_name: operation to blame on failure
1785  * @err: -errno value to sanitize
1786  *
1787  * Verify @err is a valid -errno. If not, trigger scx_error() and return
1788  * -%EPROTO. This is necessary because returning a rogue -errno up the chain can
1789  * cause misbehaviors. For an example, a large negative return from
1790  * ops.init_task() triggers an oops when passed up the call chain because the
1791  * value fails IS_ERR() test after being encoded with ERR_PTR() and then is
1792  * handled as a pointer.
1793  */
1794 static int ops_sanitize_err(struct scx_sched *sch, const char *ops_name, s32 err)
1795 {
1796 	if (err < 0 && err >= -MAX_ERRNO)
1797 		return err;
1798 
1799 	scx_error(sch, "ops.%s() returned an invalid errno %d", ops_name, err);
1800 	return -EPROTO;
1801 }
1802 
1803 static void run_deferred(struct rq *rq)
1804 {
1805 	process_ddsp_deferred_locals(rq);
1806 }
1807 
1808 static void deferred_bal_cb_workfn(struct rq *rq)
1809 {
1810 	run_deferred(rq);
1811 }
1812 
1813 static void deferred_irq_workfn(struct irq_work *irq_work)
1814 {
1815 	struct rq *rq = container_of(irq_work, struct rq, scx.deferred_irq_work);
1816 
1817 	raw_spin_rq_lock(rq);
1818 	run_deferred(rq);
1819 	raw_spin_rq_unlock(rq);
1820 }
1821 
1822 /**
1823  * schedule_deferred - Schedule execution of deferred actions on an rq
1824  * @rq: target rq
1825  *
1826  * Schedule execution of deferred actions on @rq. Must be called with @rq
1827  * locked. Deferred actions are executed with @rq locked but unpinned, and thus
1828  * can unlock @rq to e.g. migrate tasks to other rqs.
1829  */
1830 static void schedule_deferred(struct rq *rq)
1831 {
1832 	lockdep_assert_rq_held(rq);
1833 
1834 	/*
1835 	 * If in the middle of waking up a task, task_woken_scx() will be called
1836 	 * afterwards which will then run the deferred actions, no need to
1837 	 * schedule anything.
1838 	 */
1839 	if (rq->scx.flags & SCX_RQ_IN_WAKEUP)
1840 		return;
1841 
1842 	/*
1843 	 * If in balance, the balance callbacks will be called before rq lock is
1844 	 * released. Schedule one.
1845 	 */
1846 	if (rq->scx.flags & SCX_RQ_IN_BALANCE) {
1847 		queue_balance_callback(rq, &rq->scx.deferred_bal_cb,
1848 				       deferred_bal_cb_workfn);
1849 		return;
1850 	}
1851 
1852 	/*
1853 	 * No scheduler hooks available. Queue an irq work. They are executed on
1854 	 * IRQ re-enable which may take a bit longer than the scheduler hooks.
1855 	 * The above WAKEUP and BALANCE paths should cover most of the cases and
1856 	 * the time to IRQ re-enable shouldn't be long.
1857 	 */
1858 	irq_work_queue(&rq->scx.deferred_irq_work);
1859 }
1860 
1861 /**
1862  * touch_core_sched - Update timestamp used for core-sched task ordering
1863  * @rq: rq to read clock from, must be locked
1864  * @p: task to update the timestamp for
1865  *
1866  * Update @p->scx.core_sched_at timestamp. This is used by scx_prio_less() to
1867  * implement global or local-DSQ FIFO ordering for core-sched. Should be called
1868  * when a task becomes runnable and its turn on the CPU ends (e.g. slice
1869  * exhaustion).
1870  */
1871 static void touch_core_sched(struct rq *rq, struct task_struct *p)
1872 {
1873 	lockdep_assert_rq_held(rq);
1874 
1875 #ifdef CONFIG_SCHED_CORE
1876 	/*
1877 	 * It's okay to update the timestamp spuriously. Use
1878 	 * sched_core_disabled() which is cheaper than enabled().
1879 	 *
1880 	 * As this is used to determine ordering between tasks of sibling CPUs,
1881 	 * it may be better to use per-core dispatch sequence instead.
1882 	 */
1883 	if (!sched_core_disabled())
1884 		p->scx.core_sched_at = sched_clock_cpu(cpu_of(rq));
1885 #endif
1886 }
1887 
1888 /**
1889  * touch_core_sched_dispatch - Update core-sched timestamp on dispatch
1890  * @rq: rq to read clock from, must be locked
1891  * @p: task being dispatched
1892  *
1893  * If the BPF scheduler implements custom core-sched ordering via
1894  * ops.core_sched_before(), @p->scx.core_sched_at is used to implement FIFO
1895  * ordering within each local DSQ. This function is called from dispatch paths
1896  * and updates @p->scx.core_sched_at if custom core-sched ordering is in effect.
1897  */
1898 static void touch_core_sched_dispatch(struct rq *rq, struct task_struct *p)
1899 {
1900 	lockdep_assert_rq_held(rq);
1901 
1902 #ifdef CONFIG_SCHED_CORE
1903 	if (unlikely(SCX_HAS_OP(scx_root, core_sched_before)))
1904 		touch_core_sched(rq, p);
1905 #endif
1906 }
1907 
1908 static void update_curr_scx(struct rq *rq)
1909 {
1910 	struct task_struct *curr = rq->curr;
1911 	s64 delta_exec;
1912 
1913 	delta_exec = update_curr_common(rq);
1914 	if (unlikely(delta_exec <= 0))
1915 		return;
1916 
1917 	if (curr->scx.slice != SCX_SLICE_INF) {
1918 		curr->scx.slice -= min_t(u64, curr->scx.slice, delta_exec);
1919 		if (!curr->scx.slice)
1920 			touch_core_sched(rq, curr);
1921 	}
1922 }
1923 
1924 static bool scx_dsq_priq_less(struct rb_node *node_a,
1925 			      const struct rb_node *node_b)
1926 {
1927 	const struct task_struct *a =
1928 		container_of(node_a, struct task_struct, scx.dsq_priq);
1929 	const struct task_struct *b =
1930 		container_of(node_b, struct task_struct, scx.dsq_priq);
1931 
1932 	return time_before64(a->scx.dsq_vtime, b->scx.dsq_vtime);
1933 }
1934 
1935 static void dsq_mod_nr(struct scx_dispatch_q *dsq, s32 delta)
1936 {
1937 	/* scx_bpf_dsq_nr_queued() reads ->nr without locking, use WRITE_ONCE() */
1938 	WRITE_ONCE(dsq->nr, dsq->nr + delta);
1939 }
1940 
1941 static void refill_task_slice_dfl(struct task_struct *p)
1942 {
1943 	p->scx.slice = SCX_SLICE_DFL;
1944 	__scx_add_event(scx_root, SCX_EV_REFILL_SLICE_DFL, 1);
1945 }
1946 
1947 static void dispatch_enqueue(struct scx_sched *sch, struct scx_dispatch_q *dsq,
1948 			     struct task_struct *p, u64 enq_flags)
1949 {
1950 	bool is_local = dsq->id == SCX_DSQ_LOCAL;
1951 
1952 	WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node));
1953 	WARN_ON_ONCE((p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) ||
1954 		     !RB_EMPTY_NODE(&p->scx.dsq_priq));
1955 
1956 	if (!is_local) {
1957 		raw_spin_lock(&dsq->lock);
1958 		if (unlikely(dsq->id == SCX_DSQ_INVALID)) {
1959 			scx_error(sch, "attempting to dispatch to a destroyed dsq");
1960 			/* fall back to the global dsq */
1961 			raw_spin_unlock(&dsq->lock);
1962 			dsq = find_global_dsq(p);
1963 			raw_spin_lock(&dsq->lock);
1964 		}
1965 	}
1966 
1967 	if (unlikely((dsq->id & SCX_DSQ_FLAG_BUILTIN) &&
1968 		     (enq_flags & SCX_ENQ_DSQ_PRIQ))) {
1969 		/*
1970 		 * SCX_DSQ_LOCAL and SCX_DSQ_GLOBAL DSQs always consume from
1971 		 * their FIFO queues. To avoid confusion and accidentally
1972 		 * starving vtime-dispatched tasks by FIFO-dispatched tasks, we
1973 		 * disallow any internal DSQ from doing vtime ordering of
1974 		 * tasks.
1975 		 */
1976 		scx_error(sch, "cannot use vtime ordering for built-in DSQs");
1977 		enq_flags &= ~SCX_ENQ_DSQ_PRIQ;
1978 	}
1979 
1980 	if (enq_flags & SCX_ENQ_DSQ_PRIQ) {
1981 		struct rb_node *rbp;
1982 
1983 		/*
1984 		 * A PRIQ DSQ shouldn't be using FIFO enqueueing. As tasks are
1985 		 * linked to both the rbtree and list on PRIQs, this can only be
1986 		 * tested easily when adding the first task.
1987 		 */
1988 		if (unlikely(RB_EMPTY_ROOT(&dsq->priq) &&
1989 			     nldsq_next_task(dsq, NULL, false)))
1990 			scx_error(sch, "DSQ ID 0x%016llx already had FIFO-enqueued tasks",
1991 				  dsq->id);
1992 
1993 		p->scx.dsq_flags |= SCX_TASK_DSQ_ON_PRIQ;
1994 		rb_add(&p->scx.dsq_priq, &dsq->priq, scx_dsq_priq_less);
1995 
1996 		/*
1997 		 * Find the previous task and insert after it on the list so
1998 		 * that @dsq->list is vtime ordered.
1999 		 */
2000 		rbp = rb_prev(&p->scx.dsq_priq);
2001 		if (rbp) {
2002 			struct task_struct *prev =
2003 				container_of(rbp, struct task_struct,
2004 					     scx.dsq_priq);
2005 			list_add(&p->scx.dsq_list.node, &prev->scx.dsq_list.node);
2006 		} else {
2007 			list_add(&p->scx.dsq_list.node, &dsq->list);
2008 		}
2009 	} else {
2010 		/* a FIFO DSQ shouldn't be using PRIQ enqueuing */
2011 		if (unlikely(!RB_EMPTY_ROOT(&dsq->priq)))
2012 			scx_error(sch, "DSQ ID 0x%016llx already had PRIQ-enqueued tasks",
2013 				  dsq->id);
2014 
2015 		if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT))
2016 			list_add(&p->scx.dsq_list.node, &dsq->list);
2017 		else
2018 			list_add_tail(&p->scx.dsq_list.node, &dsq->list);
2019 	}
2020 
2021 	/* seq records the order tasks are queued, used by BPF DSQ iterator */
2022 	dsq->seq++;
2023 	p->scx.dsq_seq = dsq->seq;
2024 
2025 	dsq_mod_nr(dsq, 1);
2026 	p->scx.dsq = dsq;
2027 
2028 	/*
2029 	 * scx.ddsp_dsq_id and scx.ddsp_enq_flags are only relevant on the
2030 	 * direct dispatch path, but we clear them here because the direct
2031 	 * dispatch verdict may be overridden on the enqueue path during e.g.
2032 	 * bypass.
2033 	 */
2034 	p->scx.ddsp_dsq_id = SCX_DSQ_INVALID;
2035 	p->scx.ddsp_enq_flags = 0;
2036 
2037 	/*
2038 	 * We're transitioning out of QUEUEING or DISPATCHING. store_release to
2039 	 * match waiters' load_acquire.
2040 	 */
2041 	if (enq_flags & SCX_ENQ_CLEAR_OPSS)
2042 		atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
2043 
2044 	if (is_local) {
2045 		struct rq *rq = container_of(dsq, struct rq, scx.local_dsq);
2046 		bool preempt = false;
2047 
2048 		if ((enq_flags & SCX_ENQ_PREEMPT) && p != rq->curr &&
2049 		    rq->curr->sched_class == &ext_sched_class) {
2050 			rq->curr->scx.slice = 0;
2051 			preempt = true;
2052 		}
2053 
2054 		if (preempt || sched_class_above(&ext_sched_class,
2055 						 rq->curr->sched_class))
2056 			resched_curr(rq);
2057 	} else {
2058 		raw_spin_unlock(&dsq->lock);
2059 	}
2060 }
2061 
2062 static void task_unlink_from_dsq(struct task_struct *p,
2063 				 struct scx_dispatch_q *dsq)
2064 {
2065 	WARN_ON_ONCE(list_empty(&p->scx.dsq_list.node));
2066 
2067 	if (p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) {
2068 		rb_erase(&p->scx.dsq_priq, &dsq->priq);
2069 		RB_CLEAR_NODE(&p->scx.dsq_priq);
2070 		p->scx.dsq_flags &= ~SCX_TASK_DSQ_ON_PRIQ;
2071 	}
2072 
2073 	list_del_init(&p->scx.dsq_list.node);
2074 	dsq_mod_nr(dsq, -1);
2075 }
2076 
2077 static void dispatch_dequeue(struct rq *rq, struct task_struct *p)
2078 {
2079 	struct scx_dispatch_q *dsq = p->scx.dsq;
2080 	bool is_local = dsq == &rq->scx.local_dsq;
2081 
2082 	if (!dsq) {
2083 		/*
2084 		 * If !dsq && on-list, @p is on @rq's ddsp_deferred_locals.
2085 		 * Unlinking is all that's needed to cancel.
2086 		 */
2087 		if (unlikely(!list_empty(&p->scx.dsq_list.node)))
2088 			list_del_init(&p->scx.dsq_list.node);
2089 
2090 		/*
2091 		 * When dispatching directly from the BPF scheduler to a local
2092 		 * DSQ, the task isn't associated with any DSQ but
2093 		 * @p->scx.holding_cpu may be set under the protection of
2094 		 * %SCX_OPSS_DISPATCHING.
2095 		 */
2096 		if (p->scx.holding_cpu >= 0)
2097 			p->scx.holding_cpu = -1;
2098 
2099 		return;
2100 	}
2101 
2102 	if (!is_local)
2103 		raw_spin_lock(&dsq->lock);
2104 
2105 	/*
2106 	 * Now that we hold @dsq->lock, @p->holding_cpu and @p->scx.dsq_* can't
2107 	 * change underneath us.
2108 	*/
2109 	if (p->scx.holding_cpu < 0) {
2110 		/* @p must still be on @dsq, dequeue */
2111 		task_unlink_from_dsq(p, dsq);
2112 	} else {
2113 		/*
2114 		 * We're racing against dispatch_to_local_dsq() which already
2115 		 * removed @p from @dsq and set @p->scx.holding_cpu. Clear the
2116 		 * holding_cpu which tells dispatch_to_local_dsq() that it lost
2117 		 * the race.
2118 		 */
2119 		WARN_ON_ONCE(!list_empty(&p->scx.dsq_list.node));
2120 		p->scx.holding_cpu = -1;
2121 	}
2122 	p->scx.dsq = NULL;
2123 
2124 	if (!is_local)
2125 		raw_spin_unlock(&dsq->lock);
2126 }
2127 
2128 static struct scx_dispatch_q *find_dsq_for_dispatch(struct scx_sched *sch,
2129 						    struct rq *rq, u64 dsq_id,
2130 						    struct task_struct *p)
2131 {
2132 	struct scx_dispatch_q *dsq;
2133 
2134 	if (dsq_id == SCX_DSQ_LOCAL)
2135 		return &rq->scx.local_dsq;
2136 
2137 	if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
2138 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
2139 
2140 		if (!ops_cpu_valid(sch, cpu, "in SCX_DSQ_LOCAL_ON dispatch verdict"))
2141 			return find_global_dsq(p);
2142 
2143 		return &cpu_rq(cpu)->scx.local_dsq;
2144 	}
2145 
2146 	if (dsq_id == SCX_DSQ_GLOBAL)
2147 		dsq = find_global_dsq(p);
2148 	else
2149 		dsq = find_user_dsq(sch, dsq_id);
2150 
2151 	if (unlikely(!dsq)) {
2152 		scx_error(sch, "non-existent DSQ 0x%llx for %s[%d]",
2153 			  dsq_id, p->comm, p->pid);
2154 		return find_global_dsq(p);
2155 	}
2156 
2157 	return dsq;
2158 }
2159 
2160 static void mark_direct_dispatch(struct task_struct *ddsp_task,
2161 				 struct task_struct *p, u64 dsq_id,
2162 				 u64 enq_flags)
2163 {
2164 	/*
2165 	 * Mark that dispatch already happened from ops.select_cpu() or
2166 	 * ops.enqueue() by spoiling direct_dispatch_task with a non-NULL value
2167 	 * which can never match a valid task pointer.
2168 	 */
2169 	__this_cpu_write(direct_dispatch_task, ERR_PTR(-ESRCH));
2170 
2171 	/* @p must match the task on the enqueue path */
2172 	if (unlikely(p != ddsp_task)) {
2173 		if (IS_ERR(ddsp_task))
2174 			scx_kf_error("%s[%d] already direct-dispatched",
2175 				  p->comm, p->pid);
2176 		else
2177 			scx_kf_error("scheduling for %s[%d] but trying to direct-dispatch %s[%d]",
2178 				  ddsp_task->comm, ddsp_task->pid,
2179 				  p->comm, p->pid);
2180 		return;
2181 	}
2182 
2183 	WARN_ON_ONCE(p->scx.ddsp_dsq_id != SCX_DSQ_INVALID);
2184 	WARN_ON_ONCE(p->scx.ddsp_enq_flags);
2185 
2186 	p->scx.ddsp_dsq_id = dsq_id;
2187 	p->scx.ddsp_enq_flags = enq_flags;
2188 }
2189 
2190 static void direct_dispatch(struct scx_sched *sch, struct task_struct *p,
2191 			    u64 enq_flags)
2192 {
2193 	struct rq *rq = task_rq(p);
2194 	struct scx_dispatch_q *dsq =
2195 		find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, p);
2196 
2197 	touch_core_sched_dispatch(rq, p);
2198 
2199 	p->scx.ddsp_enq_flags |= enq_flags;
2200 
2201 	/*
2202 	 * We are in the enqueue path with @rq locked and pinned, and thus can't
2203 	 * double lock a remote rq and enqueue to its local DSQ. For
2204 	 * DSQ_LOCAL_ON verdicts targeting the local DSQ of a remote CPU, defer
2205 	 * the enqueue so that it's executed when @rq can be unlocked.
2206 	 */
2207 	if (dsq->id == SCX_DSQ_LOCAL && dsq != &rq->scx.local_dsq) {
2208 		unsigned long opss;
2209 
2210 		opss = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_STATE_MASK;
2211 
2212 		switch (opss & SCX_OPSS_STATE_MASK) {
2213 		case SCX_OPSS_NONE:
2214 			break;
2215 		case SCX_OPSS_QUEUEING:
2216 			/*
2217 			 * As @p was never passed to the BPF side, _release is
2218 			 * not strictly necessary. Still do it for consistency.
2219 			 */
2220 			atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
2221 			break;
2222 		default:
2223 			WARN_ONCE(true, "sched_ext: %s[%d] has invalid ops state 0x%lx in direct_dispatch()",
2224 				  p->comm, p->pid, opss);
2225 			atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
2226 			break;
2227 		}
2228 
2229 		WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node));
2230 		list_add_tail(&p->scx.dsq_list.node,
2231 			      &rq->scx.ddsp_deferred_locals);
2232 		schedule_deferred(rq);
2233 		return;
2234 	}
2235 
2236 	dispatch_enqueue(sch, dsq, p,
2237 			 p->scx.ddsp_enq_flags | SCX_ENQ_CLEAR_OPSS);
2238 }
2239 
2240 static bool scx_rq_online(struct rq *rq)
2241 {
2242 	/*
2243 	 * Test both cpu_active() and %SCX_RQ_ONLINE. %SCX_RQ_ONLINE indicates
2244 	 * the online state as seen from the BPF scheduler. cpu_active() test
2245 	 * guarantees that, if this function returns %true, %SCX_RQ_ONLINE will
2246 	 * stay set until the current scheduling operation is complete even if
2247 	 * we aren't locking @rq.
2248 	 */
2249 	return likely((rq->scx.flags & SCX_RQ_ONLINE) && cpu_active(cpu_of(rq)));
2250 }
2251 
2252 static void do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags,
2253 			    int sticky_cpu)
2254 {
2255 	struct scx_sched *sch = scx_root;
2256 	struct task_struct **ddsp_taskp;
2257 	unsigned long qseq;
2258 
2259 	WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_QUEUED));
2260 
2261 	/* rq migration */
2262 	if (sticky_cpu == cpu_of(rq))
2263 		goto local_norefill;
2264 
2265 	/*
2266 	 * If !scx_rq_online(), we already told the BPF scheduler that the CPU
2267 	 * is offline and are just running the hotplug path. Don't bother the
2268 	 * BPF scheduler.
2269 	 */
2270 	if (!scx_rq_online(rq))
2271 		goto local;
2272 
2273 	if (scx_rq_bypassing(rq)) {
2274 		__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
2275 		goto global;
2276 	}
2277 
2278 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
2279 		goto direct;
2280 
2281 	/* see %SCX_OPS_ENQ_EXITING */
2282 	if (!(sch->ops.flags & SCX_OPS_ENQ_EXITING) &&
2283 	    unlikely(p->flags & PF_EXITING)) {
2284 		__scx_add_event(sch, SCX_EV_ENQ_SKIP_EXITING, 1);
2285 		goto local;
2286 	}
2287 
2288 	/* see %SCX_OPS_ENQ_MIGRATION_DISABLED */
2289 	if (!(sch->ops.flags & SCX_OPS_ENQ_MIGRATION_DISABLED) &&
2290 	    is_migration_disabled(p)) {
2291 		__scx_add_event(sch, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED, 1);
2292 		goto local;
2293 	}
2294 
2295 	if (unlikely(!SCX_HAS_OP(sch, enqueue)))
2296 		goto global;
2297 
2298 	/* DSQ bypass didn't trigger, enqueue on the BPF scheduler */
2299 	qseq = rq->scx.ops_qseq++ << SCX_OPSS_QSEQ_SHIFT;
2300 
2301 	WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
2302 	atomic_long_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq);
2303 
2304 	ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
2305 	WARN_ON_ONCE(*ddsp_taskp);
2306 	*ddsp_taskp = p;
2307 
2308 	SCX_CALL_OP_TASK(sch, SCX_KF_ENQUEUE, enqueue, rq, p, enq_flags);
2309 
2310 	*ddsp_taskp = NULL;
2311 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
2312 		goto direct;
2313 
2314 	/*
2315 	 * If not directly dispatched, QUEUEING isn't clear yet and dispatch or
2316 	 * dequeue may be waiting. The store_release matches their load_acquire.
2317 	 */
2318 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_QUEUED | qseq);
2319 	return;
2320 
2321 direct:
2322 	direct_dispatch(sch, p, enq_flags);
2323 	return;
2324 
2325 local:
2326 	/*
2327 	 * For task-ordering, slice refill must be treated as implying the end
2328 	 * of the current slice. Otherwise, the longer @p stays on the CPU, the
2329 	 * higher priority it becomes from scx_prio_less()'s POV.
2330 	 */
2331 	touch_core_sched(rq, p);
2332 	refill_task_slice_dfl(p);
2333 local_norefill:
2334 	dispatch_enqueue(sch, &rq->scx.local_dsq, p, enq_flags);
2335 	return;
2336 
2337 global:
2338 	touch_core_sched(rq, p);	/* see the comment in local: */
2339 	refill_task_slice_dfl(p);
2340 	dispatch_enqueue(sch, find_global_dsq(p), p, enq_flags);
2341 }
2342 
2343 static bool task_runnable(const struct task_struct *p)
2344 {
2345 	return !list_empty(&p->scx.runnable_node);
2346 }
2347 
2348 static void set_task_runnable(struct rq *rq, struct task_struct *p)
2349 {
2350 	lockdep_assert_rq_held(rq);
2351 
2352 	if (p->scx.flags & SCX_TASK_RESET_RUNNABLE_AT) {
2353 		p->scx.runnable_at = jiffies;
2354 		p->scx.flags &= ~SCX_TASK_RESET_RUNNABLE_AT;
2355 	}
2356 
2357 	/*
2358 	 * list_add_tail() must be used. scx_bypass() depends on tasks being
2359 	 * appended to the runnable_list.
2360 	 */
2361 	list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list);
2362 }
2363 
2364 static void clr_task_runnable(struct task_struct *p, bool reset_runnable_at)
2365 {
2366 	list_del_init(&p->scx.runnable_node);
2367 	if (reset_runnable_at)
2368 		p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
2369 }
2370 
2371 static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int enq_flags)
2372 {
2373 	struct scx_sched *sch = scx_root;
2374 	int sticky_cpu = p->scx.sticky_cpu;
2375 
2376 	if (enq_flags & ENQUEUE_WAKEUP)
2377 		rq->scx.flags |= SCX_RQ_IN_WAKEUP;
2378 
2379 	enq_flags |= rq->scx.extra_enq_flags;
2380 
2381 	if (sticky_cpu >= 0)
2382 		p->scx.sticky_cpu = -1;
2383 
2384 	/*
2385 	 * Restoring a running task will be immediately followed by
2386 	 * set_next_task_scx() which expects the task to not be on the BPF
2387 	 * scheduler as tasks can only start running through local DSQs. Force
2388 	 * direct-dispatch into the local DSQ by setting the sticky_cpu.
2389 	 */
2390 	if (unlikely(enq_flags & ENQUEUE_RESTORE) && task_current(rq, p))
2391 		sticky_cpu = cpu_of(rq);
2392 
2393 	if (p->scx.flags & SCX_TASK_QUEUED) {
2394 		WARN_ON_ONCE(!task_runnable(p));
2395 		goto out;
2396 	}
2397 
2398 	set_task_runnable(rq, p);
2399 	p->scx.flags |= SCX_TASK_QUEUED;
2400 	rq->scx.nr_running++;
2401 	add_nr_running(rq, 1);
2402 
2403 	if (SCX_HAS_OP(sch, runnable) && !task_on_rq_migrating(p))
2404 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, runnable, rq, p, enq_flags);
2405 
2406 	if (enq_flags & SCX_ENQ_WAKEUP)
2407 		touch_core_sched(rq, p);
2408 
2409 	do_enqueue_task(rq, p, enq_flags, sticky_cpu);
2410 out:
2411 	rq->scx.flags &= ~SCX_RQ_IN_WAKEUP;
2412 
2413 	if ((enq_flags & SCX_ENQ_CPU_SELECTED) &&
2414 	    unlikely(cpu_of(rq) != p->scx.selected_cpu))
2415 		__scx_add_event(sch, SCX_EV_SELECT_CPU_FALLBACK, 1);
2416 }
2417 
2418 static void ops_dequeue(struct rq *rq, struct task_struct *p, u64 deq_flags)
2419 {
2420 	struct scx_sched *sch = scx_root;
2421 	unsigned long opss;
2422 
2423 	/* dequeue is always temporary, don't reset runnable_at */
2424 	clr_task_runnable(p, false);
2425 
2426 	/* acquire ensures that we see the preceding updates on QUEUED */
2427 	opss = atomic_long_read_acquire(&p->scx.ops_state);
2428 
2429 	switch (opss & SCX_OPSS_STATE_MASK) {
2430 	case SCX_OPSS_NONE:
2431 		break;
2432 	case SCX_OPSS_QUEUEING:
2433 		/*
2434 		 * QUEUEING is started and finished while holding @p's rq lock.
2435 		 * As we're holding the rq lock now, we shouldn't see QUEUEING.
2436 		 */
2437 		BUG();
2438 	case SCX_OPSS_QUEUED:
2439 		if (SCX_HAS_OP(sch, dequeue))
2440 			SCX_CALL_OP_TASK(sch, SCX_KF_REST, dequeue, rq,
2441 					 p, deq_flags);
2442 
2443 		if (atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
2444 					    SCX_OPSS_NONE))
2445 			break;
2446 		fallthrough;
2447 	case SCX_OPSS_DISPATCHING:
2448 		/*
2449 		 * If @p is being dispatched from the BPF scheduler to a DSQ,
2450 		 * wait for the transfer to complete so that @p doesn't get
2451 		 * added to its DSQ after dequeueing is complete.
2452 		 *
2453 		 * As we're waiting on DISPATCHING with the rq locked, the
2454 		 * dispatching side shouldn't try to lock the rq while
2455 		 * DISPATCHING is set. See dispatch_to_local_dsq().
2456 		 *
2457 		 * DISPATCHING shouldn't have qseq set and control can reach
2458 		 * here with NONE @opss from the above QUEUED case block.
2459 		 * Explicitly wait on %SCX_OPSS_DISPATCHING instead of @opss.
2460 		 */
2461 		wait_ops_state(p, SCX_OPSS_DISPATCHING);
2462 		BUG_ON(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
2463 		break;
2464 	}
2465 }
2466 
2467 static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int deq_flags)
2468 {
2469 	struct scx_sched *sch = scx_root;
2470 
2471 	if (!(p->scx.flags & SCX_TASK_QUEUED)) {
2472 		WARN_ON_ONCE(task_runnable(p));
2473 		return true;
2474 	}
2475 
2476 	ops_dequeue(rq, p, deq_flags);
2477 
2478 	/*
2479 	 * A currently running task which is going off @rq first gets dequeued
2480 	 * and then stops running. As we want running <-> stopping transitions
2481 	 * to be contained within runnable <-> quiescent transitions, trigger
2482 	 * ->stopping() early here instead of in put_prev_task_scx().
2483 	 *
2484 	 * @p may go through multiple stopping <-> running transitions between
2485 	 * here and put_prev_task_scx() if task attribute changes occur while
2486 	 * balance_scx() leaves @rq unlocked. However, they don't contain any
2487 	 * information meaningful to the BPF scheduler and can be suppressed by
2488 	 * skipping the callbacks if the task is !QUEUED.
2489 	 */
2490 	if (SCX_HAS_OP(sch, stopping) && task_current(rq, p)) {
2491 		update_curr_scx(rq);
2492 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, stopping, rq, p, false);
2493 	}
2494 
2495 	if (SCX_HAS_OP(sch, quiescent) && !task_on_rq_migrating(p))
2496 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, quiescent, rq, p, deq_flags);
2497 
2498 	if (deq_flags & SCX_DEQ_SLEEP)
2499 		p->scx.flags |= SCX_TASK_DEQD_FOR_SLEEP;
2500 	else
2501 		p->scx.flags &= ~SCX_TASK_DEQD_FOR_SLEEP;
2502 
2503 	p->scx.flags &= ~SCX_TASK_QUEUED;
2504 	rq->scx.nr_running--;
2505 	sub_nr_running(rq, 1);
2506 
2507 	dispatch_dequeue(rq, p);
2508 	return true;
2509 }
2510 
2511 static void yield_task_scx(struct rq *rq)
2512 {
2513 	struct scx_sched *sch = scx_root;
2514 	struct task_struct *p = rq->curr;
2515 
2516 	if (SCX_HAS_OP(sch, yield))
2517 		SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, yield, rq, p, NULL);
2518 	else
2519 		p->scx.slice = 0;
2520 }
2521 
2522 static bool yield_to_task_scx(struct rq *rq, struct task_struct *to)
2523 {
2524 	struct scx_sched *sch = scx_root;
2525 	struct task_struct *from = rq->curr;
2526 
2527 	if (SCX_HAS_OP(sch, yield))
2528 		return SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, yield, rq,
2529 					      from, to);
2530 	else
2531 		return false;
2532 }
2533 
2534 static void move_local_task_to_local_dsq(struct task_struct *p, u64 enq_flags,
2535 					 struct scx_dispatch_q *src_dsq,
2536 					 struct rq *dst_rq)
2537 {
2538 	struct scx_dispatch_q *dst_dsq = &dst_rq->scx.local_dsq;
2539 
2540 	/* @dsq is locked and @p is on @dst_rq */
2541 	lockdep_assert_held(&src_dsq->lock);
2542 	lockdep_assert_rq_held(dst_rq);
2543 
2544 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
2545 
2546 	if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT))
2547 		list_add(&p->scx.dsq_list.node, &dst_dsq->list);
2548 	else
2549 		list_add_tail(&p->scx.dsq_list.node, &dst_dsq->list);
2550 
2551 	dsq_mod_nr(dst_dsq, 1);
2552 	p->scx.dsq = dst_dsq;
2553 }
2554 
2555 /**
2556  * move_remote_task_to_local_dsq - Move a task from a foreign rq to a local DSQ
2557  * @p: task to move
2558  * @enq_flags: %SCX_ENQ_*
2559  * @src_rq: rq to move the task from, locked on entry, released on return
2560  * @dst_rq: rq to move the task into, locked on return
2561  *
2562  * Move @p which is currently on @src_rq to @dst_rq's local DSQ.
2563  */
2564 static void move_remote_task_to_local_dsq(struct task_struct *p, u64 enq_flags,
2565 					  struct rq *src_rq, struct rq *dst_rq)
2566 {
2567 	lockdep_assert_rq_held(src_rq);
2568 
2569 	/* the following marks @p MIGRATING which excludes dequeue */
2570 	deactivate_task(src_rq, p, 0);
2571 	set_task_cpu(p, cpu_of(dst_rq));
2572 	p->scx.sticky_cpu = cpu_of(dst_rq);
2573 
2574 	raw_spin_rq_unlock(src_rq);
2575 	raw_spin_rq_lock(dst_rq);
2576 
2577 	/*
2578 	 * We want to pass scx-specific enq_flags but activate_task() will
2579 	 * truncate the upper 32 bit. As we own @rq, we can pass them through
2580 	 * @rq->scx.extra_enq_flags instead.
2581 	 */
2582 	WARN_ON_ONCE(!cpumask_test_cpu(cpu_of(dst_rq), p->cpus_ptr));
2583 	WARN_ON_ONCE(dst_rq->scx.extra_enq_flags);
2584 	dst_rq->scx.extra_enq_flags = enq_flags;
2585 	activate_task(dst_rq, p, 0);
2586 	dst_rq->scx.extra_enq_flags = 0;
2587 }
2588 
2589 /*
2590  * Similar to kernel/sched/core.c::is_cpu_allowed(). However, there are two
2591  * differences:
2592  *
2593  * - is_cpu_allowed() asks "Can this task run on this CPU?" while
2594  *   task_can_run_on_remote_rq() asks "Can the BPF scheduler migrate the task to
2595  *   this CPU?".
2596  *
2597  *   While migration is disabled, is_cpu_allowed() has to say "yes" as the task
2598  *   must be allowed to finish on the CPU that it's currently on regardless of
2599  *   the CPU state. However, task_can_run_on_remote_rq() must say "no" as the
2600  *   BPF scheduler shouldn't attempt to migrate a task which has migration
2601  *   disabled.
2602  *
2603  * - The BPF scheduler is bypassed while the rq is offline and we can always say
2604  *   no to the BPF scheduler initiated migrations while offline.
2605  *
2606  * The caller must ensure that @p and @rq are on different CPUs.
2607  */
2608 static bool task_can_run_on_remote_rq(struct scx_sched *sch,
2609 				      struct task_struct *p, struct rq *rq,
2610 				      bool enforce)
2611 {
2612 	int cpu = cpu_of(rq);
2613 
2614 	WARN_ON_ONCE(task_cpu(p) == cpu);
2615 
2616 	/*
2617 	 * If @p has migration disabled, @p->cpus_ptr is updated to contain only
2618 	 * the pinned CPU in migrate_disable_switch() while @p is being switched
2619 	 * out. However, put_prev_task_scx() is called before @p->cpus_ptr is
2620 	 * updated and thus another CPU may see @p on a DSQ inbetween leading to
2621 	 * @p passing the below task_allowed_on_cpu() check while migration is
2622 	 * disabled.
2623 	 *
2624 	 * Test the migration disabled state first as the race window is narrow
2625 	 * and the BPF scheduler failing to check migration disabled state can
2626 	 * easily be masked if task_allowed_on_cpu() is done first.
2627 	 */
2628 	if (unlikely(is_migration_disabled(p))) {
2629 		if (enforce)
2630 			scx_error(sch, "SCX_DSQ_LOCAL[_ON] cannot move migration disabled %s[%d] from CPU %d to %d",
2631 				  p->comm, p->pid, task_cpu(p), cpu);
2632 		return false;
2633 	}
2634 
2635 	/*
2636 	 * We don't require the BPF scheduler to avoid dispatching to offline
2637 	 * CPUs mostly for convenience but also because CPUs can go offline
2638 	 * between scx_bpf_dsq_insert() calls and here. Trigger error iff the
2639 	 * picked CPU is outside the allowed mask.
2640 	 */
2641 	if (!task_allowed_on_cpu(p, cpu)) {
2642 		if (enforce)
2643 			scx_error(sch, "SCX_DSQ_LOCAL[_ON] target CPU %d not allowed for %s[%d]",
2644 				  cpu, p->comm, p->pid);
2645 		return false;
2646 	}
2647 
2648 	if (!scx_rq_online(rq)) {
2649 		if (enforce)
2650 			__scx_add_event(scx_root,
2651 					SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE, 1);
2652 		return false;
2653 	}
2654 
2655 	return true;
2656 }
2657 
2658 /**
2659  * unlink_dsq_and_lock_src_rq() - Unlink task from its DSQ and lock its task_rq
2660  * @p: target task
2661  * @dsq: locked DSQ @p is currently on
2662  * @src_rq: rq @p is currently on, stable with @dsq locked
2663  *
2664  * Called with @dsq locked but no rq's locked. We want to move @p to a different
2665  * DSQ, including any local DSQ, but are not locking @src_rq. Locking @src_rq is
2666  * required when transferring into a local DSQ. Even when transferring into a
2667  * non-local DSQ, it's better to use the same mechanism to protect against
2668  * dequeues and maintain the invariant that @p->scx.dsq can only change while
2669  * @src_rq is locked, which e.g. scx_dump_task() depends on.
2670  *
2671  * We want to grab @src_rq but that can deadlock if we try while locking @dsq,
2672  * so we want to unlink @p from @dsq, drop its lock and then lock @src_rq. As
2673  * this may race with dequeue, which can't drop the rq lock or fail, do a little
2674  * dancing from our side.
2675  *
2676  * @p->scx.holding_cpu is set to this CPU before @dsq is unlocked. If @p gets
2677  * dequeued after we unlock @dsq but before locking @src_rq, the holding_cpu
2678  * would be cleared to -1. While other cpus may have updated it to different
2679  * values afterwards, as this operation can't be preempted or recurse, the
2680  * holding_cpu can never become this CPU again before we're done. Thus, we can
2681  * tell whether we lost to dequeue by testing whether the holding_cpu still
2682  * points to this CPU. See dispatch_dequeue() for the counterpart.
2683  *
2684  * On return, @dsq is unlocked and @src_rq is locked. Returns %true if @p is
2685  * still valid. %false if lost to dequeue.
2686  */
2687 static bool unlink_dsq_and_lock_src_rq(struct task_struct *p,
2688 				       struct scx_dispatch_q *dsq,
2689 				       struct rq *src_rq)
2690 {
2691 	s32 cpu = raw_smp_processor_id();
2692 
2693 	lockdep_assert_held(&dsq->lock);
2694 
2695 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
2696 	task_unlink_from_dsq(p, dsq);
2697 	p->scx.holding_cpu = cpu;
2698 
2699 	raw_spin_unlock(&dsq->lock);
2700 	raw_spin_rq_lock(src_rq);
2701 
2702 	/* task_rq couldn't have changed if we're still the holding cpu */
2703 	return likely(p->scx.holding_cpu == cpu) &&
2704 		!WARN_ON_ONCE(src_rq != task_rq(p));
2705 }
2706 
2707 static bool consume_remote_task(struct rq *this_rq, struct task_struct *p,
2708 				struct scx_dispatch_q *dsq, struct rq *src_rq)
2709 {
2710 	raw_spin_rq_unlock(this_rq);
2711 
2712 	if (unlink_dsq_and_lock_src_rq(p, dsq, src_rq)) {
2713 		move_remote_task_to_local_dsq(p, 0, src_rq, this_rq);
2714 		return true;
2715 	} else {
2716 		raw_spin_rq_unlock(src_rq);
2717 		raw_spin_rq_lock(this_rq);
2718 		return false;
2719 	}
2720 }
2721 
2722 /**
2723  * move_task_between_dsqs() - Move a task from one DSQ to another
2724  * @sch: scx_sched being operated on
2725  * @p: target task
2726  * @enq_flags: %SCX_ENQ_*
2727  * @src_dsq: DSQ @p is currently on, must not be a local DSQ
2728  * @dst_dsq: DSQ @p is being moved to, can be any DSQ
2729  *
2730  * Must be called with @p's task_rq and @src_dsq locked. If @dst_dsq is a local
2731  * DSQ and @p is on a different CPU, @p will be migrated and thus its task_rq
2732  * will change. As @p's task_rq is locked, this function doesn't need to use the
2733  * holding_cpu mechanism.
2734  *
2735  * On return, @src_dsq is unlocked and only @p's new task_rq, which is the
2736  * return value, is locked.
2737  */
2738 static struct rq *move_task_between_dsqs(struct scx_sched *sch,
2739 					 struct task_struct *p, u64 enq_flags,
2740 					 struct scx_dispatch_q *src_dsq,
2741 					 struct scx_dispatch_q *dst_dsq)
2742 {
2743 	struct rq *src_rq = task_rq(p), *dst_rq;
2744 
2745 	BUG_ON(src_dsq->id == SCX_DSQ_LOCAL);
2746 	lockdep_assert_held(&src_dsq->lock);
2747 	lockdep_assert_rq_held(src_rq);
2748 
2749 	if (dst_dsq->id == SCX_DSQ_LOCAL) {
2750 		dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
2751 		if (src_rq != dst_rq &&
2752 		    unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) {
2753 			dst_dsq = find_global_dsq(p);
2754 			dst_rq = src_rq;
2755 		}
2756 	} else {
2757 		/* no need to migrate if destination is a non-local DSQ */
2758 		dst_rq = src_rq;
2759 	}
2760 
2761 	/*
2762 	 * Move @p into $dst_dsq. If $dst_dsq is the local DSQ of a different
2763 	 * CPU, @p will be migrated.
2764 	 */
2765 	if (dst_dsq->id == SCX_DSQ_LOCAL) {
2766 		/* @p is going from a non-local DSQ to a local DSQ */
2767 		if (src_rq == dst_rq) {
2768 			task_unlink_from_dsq(p, src_dsq);
2769 			move_local_task_to_local_dsq(p, enq_flags,
2770 						     src_dsq, dst_rq);
2771 			raw_spin_unlock(&src_dsq->lock);
2772 		} else {
2773 			raw_spin_unlock(&src_dsq->lock);
2774 			move_remote_task_to_local_dsq(p, enq_flags,
2775 						      src_rq, dst_rq);
2776 		}
2777 	} else {
2778 		/*
2779 		 * @p is going from a non-local DSQ to a non-local DSQ. As
2780 		 * $src_dsq is already locked, do an abbreviated dequeue.
2781 		 */
2782 		task_unlink_from_dsq(p, src_dsq);
2783 		p->scx.dsq = NULL;
2784 		raw_spin_unlock(&src_dsq->lock);
2785 
2786 		dispatch_enqueue(sch, dst_dsq, p, enq_flags);
2787 	}
2788 
2789 	return dst_rq;
2790 }
2791 
2792 /*
2793  * A poorly behaving BPF scheduler can live-lock the system by e.g. incessantly
2794  * banging on the same DSQ on a large NUMA system to the point where switching
2795  * to the bypass mode can take a long time. Inject artificial delays while the
2796  * bypass mode is switching to guarantee timely completion.
2797  */
2798 static void scx_breather(struct rq *rq)
2799 {
2800 	u64 until;
2801 
2802 	lockdep_assert_rq_held(rq);
2803 
2804 	if (likely(!atomic_read(&scx_breather_depth)))
2805 		return;
2806 
2807 	raw_spin_rq_unlock(rq);
2808 
2809 	until = ktime_get_ns() + NSEC_PER_MSEC;
2810 
2811 	do {
2812 		int cnt = 1024;
2813 		while (atomic_read(&scx_breather_depth) && --cnt)
2814 			cpu_relax();
2815 	} while (atomic_read(&scx_breather_depth) &&
2816 		 time_before64(ktime_get_ns(), until));
2817 
2818 	raw_spin_rq_lock(rq);
2819 }
2820 
2821 static bool consume_dispatch_q(struct scx_sched *sch, struct rq *rq,
2822 			       struct scx_dispatch_q *dsq)
2823 {
2824 	struct task_struct *p;
2825 retry:
2826 	/*
2827 	 * This retry loop can repeatedly race against scx_bypass() dequeueing
2828 	 * tasks from @dsq trying to put the system into the bypass mode. On
2829 	 * some multi-socket machines (e.g. 2x Intel 8480c), this can live-lock
2830 	 * the machine into soft lockups. Give a breather.
2831 	 */
2832 	scx_breather(rq);
2833 
2834 	/*
2835 	 * The caller can't expect to successfully consume a task if the task's
2836 	 * addition to @dsq isn't guaranteed to be visible somehow. Test
2837 	 * @dsq->list without locking and skip if it seems empty.
2838 	 */
2839 	if (list_empty(&dsq->list))
2840 		return false;
2841 
2842 	raw_spin_lock(&dsq->lock);
2843 
2844 	nldsq_for_each_task(p, dsq) {
2845 		struct rq *task_rq = task_rq(p);
2846 
2847 		if (rq == task_rq) {
2848 			task_unlink_from_dsq(p, dsq);
2849 			move_local_task_to_local_dsq(p, 0, dsq, rq);
2850 			raw_spin_unlock(&dsq->lock);
2851 			return true;
2852 		}
2853 
2854 		if (task_can_run_on_remote_rq(sch, p, rq, false)) {
2855 			if (likely(consume_remote_task(rq, p, dsq, task_rq)))
2856 				return true;
2857 			goto retry;
2858 		}
2859 	}
2860 
2861 	raw_spin_unlock(&dsq->lock);
2862 	return false;
2863 }
2864 
2865 static bool consume_global_dsq(struct scx_sched *sch, struct rq *rq)
2866 {
2867 	int node = cpu_to_node(cpu_of(rq));
2868 
2869 	return consume_dispatch_q(sch, rq, sch->global_dsqs[node]);
2870 }
2871 
2872 /**
2873  * dispatch_to_local_dsq - Dispatch a task to a local dsq
2874  * @sch: scx_sched being operated on
2875  * @rq: current rq which is locked
2876  * @dst_dsq: destination DSQ
2877  * @p: task to dispatch
2878  * @enq_flags: %SCX_ENQ_*
2879  *
2880  * We're holding @rq lock and want to dispatch @p to @dst_dsq which is a local
2881  * DSQ. This function performs all the synchronization dancing needed because
2882  * local DSQs are protected with rq locks.
2883  *
2884  * The caller must have exclusive ownership of @p (e.g. through
2885  * %SCX_OPSS_DISPATCHING).
2886  */
2887 static void dispatch_to_local_dsq(struct scx_sched *sch, struct rq *rq,
2888 				  struct scx_dispatch_q *dst_dsq,
2889 				  struct task_struct *p, u64 enq_flags)
2890 {
2891 	struct rq *src_rq = task_rq(p);
2892 	struct rq *dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
2893 	struct rq *locked_rq = rq;
2894 
2895 	/*
2896 	 * We're synchronized against dequeue through DISPATCHING. As @p can't
2897 	 * be dequeued, its task_rq and cpus_allowed are stable too.
2898 	 *
2899 	 * If dispatching to @rq that @p is already on, no lock dancing needed.
2900 	 */
2901 	if (rq == src_rq && rq == dst_rq) {
2902 		dispatch_enqueue(sch, dst_dsq, p,
2903 				 enq_flags | SCX_ENQ_CLEAR_OPSS);
2904 		return;
2905 	}
2906 
2907 	if (src_rq != dst_rq &&
2908 	    unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) {
2909 		dispatch_enqueue(sch, find_global_dsq(p), p,
2910 				 enq_flags | SCX_ENQ_CLEAR_OPSS);
2911 		return;
2912 	}
2913 
2914 	/*
2915 	 * @p is on a possibly remote @src_rq which we need to lock to move the
2916 	 * task. If dequeue is in progress, it'd be locking @src_rq and waiting
2917 	 * on DISPATCHING, so we can't grab @src_rq lock while holding
2918 	 * DISPATCHING.
2919 	 *
2920 	 * As DISPATCHING guarantees that @p is wholly ours, we can pretend that
2921 	 * we're moving from a DSQ and use the same mechanism - mark the task
2922 	 * under transfer with holding_cpu, release DISPATCHING and then follow
2923 	 * the same protocol. See unlink_dsq_and_lock_src_rq().
2924 	 */
2925 	p->scx.holding_cpu = raw_smp_processor_id();
2926 
2927 	/* store_release ensures that dequeue sees the above */
2928 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
2929 
2930 	/* switch to @src_rq lock */
2931 	if (locked_rq != src_rq) {
2932 		raw_spin_rq_unlock(locked_rq);
2933 		locked_rq = src_rq;
2934 		raw_spin_rq_lock(src_rq);
2935 	}
2936 
2937 	/* task_rq couldn't have changed if we're still the holding cpu */
2938 	if (likely(p->scx.holding_cpu == raw_smp_processor_id()) &&
2939 	    !WARN_ON_ONCE(src_rq != task_rq(p))) {
2940 		/*
2941 		 * If @p is staying on the same rq, there's no need to go
2942 		 * through the full deactivate/activate cycle. Optimize by
2943 		 * abbreviating move_remote_task_to_local_dsq().
2944 		 */
2945 		if (src_rq == dst_rq) {
2946 			p->scx.holding_cpu = -1;
2947 			dispatch_enqueue(sch, &dst_rq->scx.local_dsq, p,
2948 					 enq_flags);
2949 		} else {
2950 			move_remote_task_to_local_dsq(p, enq_flags,
2951 						      src_rq, dst_rq);
2952 			/* task has been moved to dst_rq, which is now locked */
2953 			locked_rq = dst_rq;
2954 		}
2955 
2956 		/* if the destination CPU is idle, wake it up */
2957 		if (sched_class_above(p->sched_class, dst_rq->curr->sched_class))
2958 			resched_curr(dst_rq);
2959 	}
2960 
2961 	/* switch back to @rq lock */
2962 	if (locked_rq != rq) {
2963 		raw_spin_rq_unlock(locked_rq);
2964 		raw_spin_rq_lock(rq);
2965 	}
2966 }
2967 
2968 /**
2969  * finish_dispatch - Asynchronously finish dispatching a task
2970  * @rq: current rq which is locked
2971  * @p: task to finish dispatching
2972  * @qseq_at_dispatch: qseq when @p started getting dispatched
2973  * @dsq_id: destination DSQ ID
2974  * @enq_flags: %SCX_ENQ_*
2975  *
2976  * Dispatching to local DSQs may need to wait for queueing to complete or
2977  * require rq lock dancing. As we don't wanna do either while inside
2978  * ops.dispatch() to avoid locking order inversion, we split dispatching into
2979  * two parts. scx_bpf_dsq_insert() which is called by ops.dispatch() records the
2980  * task and its qseq. Once ops.dispatch() returns, this function is called to
2981  * finish up.
2982  *
2983  * There is no guarantee that @p is still valid for dispatching or even that it
2984  * was valid in the first place. Make sure that the task is still owned by the
2985  * BPF scheduler and claim the ownership before dispatching.
2986  */
2987 static void finish_dispatch(struct scx_sched *sch, struct rq *rq,
2988 			    struct task_struct *p,
2989 			    unsigned long qseq_at_dispatch,
2990 			    u64 dsq_id, u64 enq_flags)
2991 {
2992 	struct scx_dispatch_q *dsq;
2993 	unsigned long opss;
2994 
2995 	touch_core_sched_dispatch(rq, p);
2996 retry:
2997 	/*
2998 	 * No need for _acquire here. @p is accessed only after a successful
2999 	 * try_cmpxchg to DISPATCHING.
3000 	 */
3001 	opss = atomic_long_read(&p->scx.ops_state);
3002 
3003 	switch (opss & SCX_OPSS_STATE_MASK) {
3004 	case SCX_OPSS_DISPATCHING:
3005 	case SCX_OPSS_NONE:
3006 		/* someone else already got to it */
3007 		return;
3008 	case SCX_OPSS_QUEUED:
3009 		/*
3010 		 * If qseq doesn't match, @p has gone through at least one
3011 		 * dispatch/dequeue and re-enqueue cycle between
3012 		 * scx_bpf_dsq_insert() and here and we have no claim on it.
3013 		 */
3014 		if ((opss & SCX_OPSS_QSEQ_MASK) != qseq_at_dispatch)
3015 			return;
3016 
3017 		/*
3018 		 * While we know @p is accessible, we don't yet have a claim on
3019 		 * it - the BPF scheduler is allowed to dispatch tasks
3020 		 * spuriously and there can be a racing dequeue attempt. Let's
3021 		 * claim @p by atomically transitioning it from QUEUED to
3022 		 * DISPATCHING.
3023 		 */
3024 		if (likely(atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
3025 						   SCX_OPSS_DISPATCHING)))
3026 			break;
3027 		goto retry;
3028 	case SCX_OPSS_QUEUEING:
3029 		/*
3030 		 * do_enqueue_task() is in the process of transferring the task
3031 		 * to the BPF scheduler while holding @p's rq lock. As we aren't
3032 		 * holding any kernel or BPF resource that the enqueue path may
3033 		 * depend upon, it's safe to wait.
3034 		 */
3035 		wait_ops_state(p, opss);
3036 		goto retry;
3037 	}
3038 
3039 	BUG_ON(!(p->scx.flags & SCX_TASK_QUEUED));
3040 
3041 	dsq = find_dsq_for_dispatch(sch, this_rq(), dsq_id, p);
3042 
3043 	if (dsq->id == SCX_DSQ_LOCAL)
3044 		dispatch_to_local_dsq(sch, rq, dsq, p, enq_flags);
3045 	else
3046 		dispatch_enqueue(sch, dsq, p, enq_flags | SCX_ENQ_CLEAR_OPSS);
3047 }
3048 
3049 static void flush_dispatch_buf(struct scx_sched *sch, struct rq *rq)
3050 {
3051 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
3052 	u32 u;
3053 
3054 	for (u = 0; u < dspc->cursor; u++) {
3055 		struct scx_dsp_buf_ent *ent = &dspc->buf[u];
3056 
3057 		finish_dispatch(sch, rq, ent->task, ent->qseq, ent->dsq_id,
3058 				ent->enq_flags);
3059 	}
3060 
3061 	dspc->nr_tasks += dspc->cursor;
3062 	dspc->cursor = 0;
3063 }
3064 
3065 static int balance_one(struct rq *rq, struct task_struct *prev)
3066 {
3067 	struct scx_sched *sch = scx_root;
3068 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
3069 	bool prev_on_scx = prev->sched_class == &ext_sched_class;
3070 	bool prev_on_rq = prev->scx.flags & SCX_TASK_QUEUED;
3071 	int nr_loops = SCX_DSP_MAX_LOOPS;
3072 
3073 	lockdep_assert_rq_held(rq);
3074 	rq->scx.flags |= SCX_RQ_IN_BALANCE;
3075 	rq->scx.flags &= ~(SCX_RQ_BAL_PENDING | SCX_RQ_BAL_KEEP);
3076 
3077 	if ((sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) &&
3078 	    unlikely(rq->scx.cpu_released)) {
3079 		/*
3080 		 * If the previous sched_class for the current CPU was not SCX,
3081 		 * notify the BPF scheduler that it again has control of the
3082 		 * core. This callback complements ->cpu_release(), which is
3083 		 * emitted in switch_class().
3084 		 */
3085 		if (SCX_HAS_OP(sch, cpu_acquire))
3086 			SCX_CALL_OP(sch, SCX_KF_REST, cpu_acquire, rq,
3087 				    cpu_of(rq), NULL);
3088 		rq->scx.cpu_released = false;
3089 	}
3090 
3091 	if (prev_on_scx) {
3092 		update_curr_scx(rq);
3093 
3094 		/*
3095 		 * If @prev is runnable & has slice left, it has priority and
3096 		 * fetching more just increases latency for the fetched tasks.
3097 		 * Tell pick_task_scx() to keep running @prev. If the BPF
3098 		 * scheduler wants to handle this explicitly, it should
3099 		 * implement ->cpu_release().
3100 		 *
3101 		 * See scx_disable_workfn() for the explanation on the bypassing
3102 		 * test.
3103 		 */
3104 		if (prev_on_rq && prev->scx.slice && !scx_rq_bypassing(rq)) {
3105 			rq->scx.flags |= SCX_RQ_BAL_KEEP;
3106 			goto has_tasks;
3107 		}
3108 	}
3109 
3110 	/* if there already are tasks to run, nothing to do */
3111 	if (rq->scx.local_dsq.nr)
3112 		goto has_tasks;
3113 
3114 	if (consume_global_dsq(sch, rq))
3115 		goto has_tasks;
3116 
3117 	if (unlikely(!SCX_HAS_OP(sch, dispatch)) ||
3118 	    scx_rq_bypassing(rq) || !scx_rq_online(rq))
3119 		goto no_tasks;
3120 
3121 	dspc->rq = rq;
3122 
3123 	/*
3124 	 * The dispatch loop. Because flush_dispatch_buf() may drop the rq lock,
3125 	 * the local DSQ might still end up empty after a successful
3126 	 * ops.dispatch(). If the local DSQ is empty even after ops.dispatch()
3127 	 * produced some tasks, retry. The BPF scheduler may depend on this
3128 	 * looping behavior to simplify its implementation.
3129 	 */
3130 	do {
3131 		dspc->nr_tasks = 0;
3132 
3133 		SCX_CALL_OP(sch, SCX_KF_DISPATCH, dispatch, rq,
3134 			    cpu_of(rq), prev_on_scx ? prev : NULL);
3135 
3136 		flush_dispatch_buf(sch, rq);
3137 
3138 		if (prev_on_rq && prev->scx.slice) {
3139 			rq->scx.flags |= SCX_RQ_BAL_KEEP;
3140 			goto has_tasks;
3141 		}
3142 		if (rq->scx.local_dsq.nr)
3143 			goto has_tasks;
3144 		if (consume_global_dsq(sch, rq))
3145 			goto has_tasks;
3146 
3147 		/*
3148 		 * ops.dispatch() can trap us in this loop by repeatedly
3149 		 * dispatching ineligible tasks. Break out once in a while to
3150 		 * allow the watchdog to run. As IRQ can't be enabled in
3151 		 * balance(), we want to complete this scheduling cycle and then
3152 		 * start a new one. IOW, we want to call resched_curr() on the
3153 		 * next, most likely idle, task, not the current one. Use
3154 		 * scx_bpf_kick_cpu() for deferred kicking.
3155 		 */
3156 		if (unlikely(!--nr_loops)) {
3157 			scx_bpf_kick_cpu(cpu_of(rq), 0);
3158 			break;
3159 		}
3160 	} while (dspc->nr_tasks);
3161 
3162 no_tasks:
3163 	/*
3164 	 * Didn't find another task to run. Keep running @prev unless
3165 	 * %SCX_OPS_ENQ_LAST is in effect.
3166 	 */
3167 	if (prev_on_rq &&
3168 	    (!(sch->ops.flags & SCX_OPS_ENQ_LAST) || scx_rq_bypassing(rq))) {
3169 		rq->scx.flags |= SCX_RQ_BAL_KEEP;
3170 		__scx_add_event(sch, SCX_EV_DISPATCH_KEEP_LAST, 1);
3171 		goto has_tasks;
3172 	}
3173 	rq->scx.flags &= ~SCX_RQ_IN_BALANCE;
3174 	return false;
3175 
3176 has_tasks:
3177 	rq->scx.flags &= ~SCX_RQ_IN_BALANCE;
3178 	return true;
3179 }
3180 
3181 static int balance_scx(struct rq *rq, struct task_struct *prev,
3182 		       struct rq_flags *rf)
3183 {
3184 	int ret;
3185 
3186 	rq_unpin_lock(rq, rf);
3187 
3188 	ret = balance_one(rq, prev);
3189 
3190 #ifdef CONFIG_SCHED_SMT
3191 	/*
3192 	 * When core-sched is enabled, this ops.balance() call will be followed
3193 	 * by pick_task_scx() on this CPU and the SMT siblings. Balance the
3194 	 * siblings too.
3195 	 */
3196 	if (sched_core_enabled(rq)) {
3197 		const struct cpumask *smt_mask = cpu_smt_mask(cpu_of(rq));
3198 		int scpu;
3199 
3200 		for_each_cpu_andnot(scpu, smt_mask, cpumask_of(cpu_of(rq))) {
3201 			struct rq *srq = cpu_rq(scpu);
3202 			struct task_struct *sprev = srq->curr;
3203 
3204 			WARN_ON_ONCE(__rq_lockp(rq) != __rq_lockp(srq));
3205 			update_rq_clock(srq);
3206 			balance_one(srq, sprev);
3207 		}
3208 	}
3209 #endif
3210 	rq_repin_lock(rq, rf);
3211 
3212 	return ret;
3213 }
3214 
3215 static void process_ddsp_deferred_locals(struct rq *rq)
3216 {
3217 	struct task_struct *p;
3218 
3219 	lockdep_assert_rq_held(rq);
3220 
3221 	/*
3222 	 * Now that @rq can be unlocked, execute the deferred enqueueing of
3223 	 * tasks directly dispatched to the local DSQs of other CPUs. See
3224 	 * direct_dispatch(). Keep popping from the head instead of using
3225 	 * list_for_each_entry_safe() as dispatch_local_dsq() may unlock @rq
3226 	 * temporarily.
3227 	 */
3228 	while ((p = list_first_entry_or_null(&rq->scx.ddsp_deferred_locals,
3229 				struct task_struct, scx.dsq_list.node))) {
3230 		struct scx_sched *sch = scx_root;
3231 		struct scx_dispatch_q *dsq;
3232 
3233 		list_del_init(&p->scx.dsq_list.node);
3234 
3235 		dsq = find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, p);
3236 		if (!WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL))
3237 			dispatch_to_local_dsq(sch, rq, dsq, p,
3238 					      p->scx.ddsp_enq_flags);
3239 	}
3240 }
3241 
3242 static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first)
3243 {
3244 	struct scx_sched *sch = scx_root;
3245 
3246 	if (p->scx.flags & SCX_TASK_QUEUED) {
3247 		/*
3248 		 * Core-sched might decide to execute @p before it is
3249 		 * dispatched. Call ops_dequeue() to notify the BPF scheduler.
3250 		 */
3251 		ops_dequeue(rq, p, SCX_DEQ_CORE_SCHED_EXEC);
3252 		dispatch_dequeue(rq, p);
3253 	}
3254 
3255 	p->se.exec_start = rq_clock_task(rq);
3256 
3257 	/* see dequeue_task_scx() on why we skip when !QUEUED */
3258 	if (SCX_HAS_OP(sch, running) && (p->scx.flags & SCX_TASK_QUEUED))
3259 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, running, rq, p);
3260 
3261 	clr_task_runnable(p, true);
3262 
3263 	/*
3264 	 * @p is getting newly scheduled or got kicked after someone updated its
3265 	 * slice. Refresh whether tick can be stopped. See scx_can_stop_tick().
3266 	 */
3267 	if ((p->scx.slice == SCX_SLICE_INF) !=
3268 	    (bool)(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) {
3269 		if (p->scx.slice == SCX_SLICE_INF)
3270 			rq->scx.flags |= SCX_RQ_CAN_STOP_TICK;
3271 		else
3272 			rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK;
3273 
3274 		sched_update_tick_dependency(rq);
3275 
3276 		/*
3277 		 * For now, let's refresh the load_avgs just when transitioning
3278 		 * in and out of nohz. In the future, we might want to add a
3279 		 * mechanism which calls the following periodically on
3280 		 * tick-stopped CPUs.
3281 		 */
3282 		update_other_load_avgs(rq);
3283 	}
3284 }
3285 
3286 static enum scx_cpu_preempt_reason
3287 preempt_reason_from_class(const struct sched_class *class)
3288 {
3289 	if (class == &stop_sched_class)
3290 		return SCX_CPU_PREEMPT_STOP;
3291 	if (class == &dl_sched_class)
3292 		return SCX_CPU_PREEMPT_DL;
3293 	if (class == &rt_sched_class)
3294 		return SCX_CPU_PREEMPT_RT;
3295 	return SCX_CPU_PREEMPT_UNKNOWN;
3296 }
3297 
3298 static void switch_class(struct rq *rq, struct task_struct *next)
3299 {
3300 	struct scx_sched *sch = scx_root;
3301 	const struct sched_class *next_class = next->sched_class;
3302 
3303 	/*
3304 	 * Pairs with the smp_load_acquire() issued by a CPU in
3305 	 * kick_cpus_irq_workfn() who is waiting for this CPU to perform a
3306 	 * resched.
3307 	 */
3308 	smp_store_release(&rq->scx.pnt_seq, rq->scx.pnt_seq + 1);
3309 	if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT))
3310 		return;
3311 
3312 	/*
3313 	 * The callback is conceptually meant to convey that the CPU is no
3314 	 * longer under the control of SCX. Therefore, don't invoke the callback
3315 	 * if the next class is below SCX (in which case the BPF scheduler has
3316 	 * actively decided not to schedule any tasks on the CPU).
3317 	 */
3318 	if (sched_class_above(&ext_sched_class, next_class))
3319 		return;
3320 
3321 	/*
3322 	 * At this point we know that SCX was preempted by a higher priority
3323 	 * sched_class, so invoke the ->cpu_release() callback if we have not
3324 	 * done so already. We only send the callback once between SCX being
3325 	 * preempted, and it regaining control of the CPU.
3326 	 *
3327 	 * ->cpu_release() complements ->cpu_acquire(), which is emitted the
3328 	 *  next time that balance_scx() is invoked.
3329 	 */
3330 	if (!rq->scx.cpu_released) {
3331 		if (SCX_HAS_OP(sch, cpu_release)) {
3332 			struct scx_cpu_release_args args = {
3333 				.reason = preempt_reason_from_class(next_class),
3334 				.task = next,
3335 			};
3336 
3337 			SCX_CALL_OP(sch, SCX_KF_CPU_RELEASE, cpu_release, rq,
3338 				    cpu_of(rq), &args);
3339 		}
3340 		rq->scx.cpu_released = true;
3341 	}
3342 }
3343 
3344 static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
3345 			      struct task_struct *next)
3346 {
3347 	struct scx_sched *sch = scx_root;
3348 	update_curr_scx(rq);
3349 
3350 	/* see dequeue_task_scx() on why we skip when !QUEUED */
3351 	if (SCX_HAS_OP(sch, stopping) && (p->scx.flags & SCX_TASK_QUEUED))
3352 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, stopping, rq, p, true);
3353 
3354 	if (p->scx.flags & SCX_TASK_QUEUED) {
3355 		set_task_runnable(rq, p);
3356 
3357 		/*
3358 		 * If @p has slice left and is being put, @p is getting
3359 		 * preempted by a higher priority scheduler class or core-sched
3360 		 * forcing a different task. Leave it at the head of the local
3361 		 * DSQ.
3362 		 */
3363 		if (p->scx.slice && !scx_rq_bypassing(rq)) {
3364 			dispatch_enqueue(sch, &rq->scx.local_dsq, p,
3365 					 SCX_ENQ_HEAD);
3366 			goto switch_class;
3367 		}
3368 
3369 		/*
3370 		 * If @p is runnable but we're about to enter a lower
3371 		 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell
3372 		 * ops.enqueue() that @p is the only one available for this cpu,
3373 		 * which should trigger an explicit follow-up scheduling event.
3374 		 */
3375 		if (sched_class_above(&ext_sched_class, next->sched_class)) {
3376 			WARN_ON_ONCE(!(sch->ops.flags & SCX_OPS_ENQ_LAST));
3377 			do_enqueue_task(rq, p, SCX_ENQ_LAST, -1);
3378 		} else {
3379 			do_enqueue_task(rq, p, 0, -1);
3380 		}
3381 	}
3382 
3383 switch_class:
3384 	if (next && next->sched_class != &ext_sched_class)
3385 		switch_class(rq, next);
3386 }
3387 
3388 static struct task_struct *first_local_task(struct rq *rq)
3389 {
3390 	return list_first_entry_or_null(&rq->scx.local_dsq.list,
3391 					struct task_struct, scx.dsq_list.node);
3392 }
3393 
3394 static struct task_struct *pick_task_scx(struct rq *rq)
3395 {
3396 	struct task_struct *prev = rq->curr;
3397 	struct task_struct *p;
3398 	bool keep_prev = rq->scx.flags & SCX_RQ_BAL_KEEP;
3399 	bool kick_idle = false;
3400 
3401 	/*
3402 	 * WORKAROUND:
3403 	 *
3404 	 * %SCX_RQ_BAL_KEEP should be set iff $prev is on SCX as it must just
3405 	 * have gone through balance_scx(). Unfortunately, there currently is a
3406 	 * bug where fair could say yes on balance() but no on pick_task(),
3407 	 * which then ends up calling pick_task_scx() without preceding
3408 	 * balance_scx().
3409 	 *
3410 	 * Keep running @prev if possible and avoid stalling from entering idle
3411 	 * without balancing.
3412 	 *
3413 	 * Once fair is fixed, remove the workaround and trigger WARN_ON_ONCE()
3414 	 * if pick_task_scx() is called without preceding balance_scx().
3415 	 */
3416 	if (unlikely(rq->scx.flags & SCX_RQ_BAL_PENDING)) {
3417 		if (prev->scx.flags & SCX_TASK_QUEUED) {
3418 			keep_prev = true;
3419 		} else {
3420 			keep_prev = false;
3421 			kick_idle = true;
3422 		}
3423 	} else if (unlikely(keep_prev &&
3424 			    prev->sched_class != &ext_sched_class)) {
3425 		/*
3426 		 * Can happen while enabling as SCX_RQ_BAL_PENDING assertion is
3427 		 * conditional on scx_enabled() and may have been skipped.
3428 		 */
3429 		WARN_ON_ONCE(scx_enable_state() == SCX_ENABLED);
3430 		keep_prev = false;
3431 	}
3432 
3433 	/*
3434 	 * If balance_scx() is telling us to keep running @prev, replenish slice
3435 	 * if necessary and keep running @prev. Otherwise, pop the first one
3436 	 * from the local DSQ.
3437 	 */
3438 	if (keep_prev) {
3439 		p = prev;
3440 		if (!p->scx.slice)
3441 			refill_task_slice_dfl(p);
3442 	} else {
3443 		p = first_local_task(rq);
3444 		if (!p) {
3445 			if (kick_idle)
3446 				scx_bpf_kick_cpu(cpu_of(rq), SCX_KICK_IDLE);
3447 			return NULL;
3448 		}
3449 
3450 		if (unlikely(!p->scx.slice)) {
3451 			struct scx_sched *sch = scx_root;
3452 
3453 			if (!scx_rq_bypassing(rq) && !sch->warned_zero_slice) {
3454 				printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in %s()\n",
3455 						p->comm, p->pid, __func__);
3456 				sch->warned_zero_slice = true;
3457 			}
3458 			refill_task_slice_dfl(p);
3459 		}
3460 	}
3461 
3462 	return p;
3463 }
3464 
3465 #ifdef CONFIG_SCHED_CORE
3466 /**
3467  * scx_prio_less - Task ordering for core-sched
3468  * @a: task A
3469  * @b: task B
3470  * @in_fi: in forced idle state
3471  *
3472  * Core-sched is implemented as an additional scheduling layer on top of the
3473  * usual sched_class'es and needs to find out the expected task ordering. For
3474  * SCX, core-sched calls this function to interrogate the task ordering.
3475  *
3476  * Unless overridden by ops.core_sched_before(), @p->scx.core_sched_at is used
3477  * to implement the default task ordering. The older the timestamp, the higher
3478  * priority the task - the global FIFO ordering matching the default scheduling
3479  * behavior.
3480  *
3481  * When ops.core_sched_before() is enabled, @p->scx.core_sched_at is used to
3482  * implement FIFO ordering within each local DSQ. See pick_task_scx().
3483  */
3484 bool scx_prio_less(const struct task_struct *a, const struct task_struct *b,
3485 		   bool in_fi)
3486 {
3487 	struct scx_sched *sch = scx_root;
3488 
3489 	/*
3490 	 * The const qualifiers are dropped from task_struct pointers when
3491 	 * calling ops.core_sched_before(). Accesses are controlled by the
3492 	 * verifier.
3493 	 */
3494 	if (SCX_HAS_OP(sch, core_sched_before) &&
3495 	    !scx_rq_bypassing(task_rq(a)))
3496 		return SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, core_sched_before,
3497 					      NULL,
3498 					      (struct task_struct *)a,
3499 					      (struct task_struct *)b);
3500 	else
3501 		return time_after64(a->scx.core_sched_at, b->scx.core_sched_at);
3502 }
3503 #endif	/* CONFIG_SCHED_CORE */
3504 
3505 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags)
3506 {
3507 	struct scx_sched *sch = scx_root;
3508 	bool rq_bypass;
3509 
3510 	/*
3511 	 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it
3512 	 * can be a good migration opportunity with low cache and memory
3513 	 * footprint. Returning a CPU different than @prev_cpu triggers
3514 	 * immediate rq migration. However, for SCX, as the current rq
3515 	 * association doesn't dictate where the task is going to run, this
3516 	 * doesn't fit well. If necessary, we can later add a dedicated method
3517 	 * which can decide to preempt self to force it through the regular
3518 	 * scheduling path.
3519 	 */
3520 	if (unlikely(wake_flags & WF_EXEC))
3521 		return prev_cpu;
3522 
3523 	rq_bypass = scx_rq_bypassing(task_rq(p));
3524 	if (likely(SCX_HAS_OP(sch, select_cpu)) && !rq_bypass) {
3525 		s32 cpu;
3526 		struct task_struct **ddsp_taskp;
3527 
3528 		ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
3529 		WARN_ON_ONCE(*ddsp_taskp);
3530 		*ddsp_taskp = p;
3531 
3532 		cpu = SCX_CALL_OP_TASK_RET(sch,
3533 					   SCX_KF_ENQUEUE | SCX_KF_SELECT_CPU,
3534 					   select_cpu, NULL, p, prev_cpu,
3535 					   wake_flags);
3536 		p->scx.selected_cpu = cpu;
3537 		*ddsp_taskp = NULL;
3538 		if (ops_cpu_valid(sch, cpu, "from ops.select_cpu()"))
3539 			return cpu;
3540 		else
3541 			return prev_cpu;
3542 	} else {
3543 		s32 cpu;
3544 
3545 		cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, NULL, 0);
3546 		if (cpu >= 0) {
3547 			refill_task_slice_dfl(p);
3548 			p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL;
3549 		} else {
3550 			cpu = prev_cpu;
3551 		}
3552 		p->scx.selected_cpu = cpu;
3553 
3554 		if (rq_bypass)
3555 			__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
3556 		return cpu;
3557 	}
3558 }
3559 
3560 static void task_woken_scx(struct rq *rq, struct task_struct *p)
3561 {
3562 	run_deferred(rq);
3563 }
3564 
3565 static void set_cpus_allowed_scx(struct task_struct *p,
3566 				 struct affinity_context *ac)
3567 {
3568 	struct scx_sched *sch = scx_root;
3569 
3570 	set_cpus_allowed_common(p, ac);
3571 
3572 	/*
3573 	 * The effective cpumask is stored in @p->cpus_ptr which may temporarily
3574 	 * differ from the configured one in @p->cpus_mask. Always tell the bpf
3575 	 * scheduler the effective one.
3576 	 *
3577 	 * Fine-grained memory write control is enforced by BPF making the const
3578 	 * designation pointless. Cast it away when calling the operation.
3579 	 */
3580 	if (SCX_HAS_OP(sch, set_cpumask))
3581 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, NULL,
3582 				 p, (struct cpumask *)p->cpus_ptr);
3583 }
3584 
3585 static void handle_hotplug(struct rq *rq, bool online)
3586 {
3587 	struct scx_sched *sch = scx_root;
3588 	int cpu = cpu_of(rq);
3589 
3590 	atomic_long_inc(&scx_hotplug_seq);
3591 
3592 	/*
3593 	 * scx_root updates are protected by cpus_read_lock() and will stay
3594 	 * stable here. Note that we can't depend on scx_enabled() test as the
3595 	 * hotplug ops need to be enabled before __scx_enabled is set.
3596 	 */
3597 	if (unlikely(!sch))
3598 		return;
3599 
3600 	if (scx_enabled())
3601 		scx_idle_update_selcpu_topology(&sch->ops);
3602 
3603 	if (online && SCX_HAS_OP(sch, cpu_online))
3604 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_online, NULL, cpu);
3605 	else if (!online && SCX_HAS_OP(sch, cpu_offline))
3606 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_offline, NULL, cpu);
3607 	else
3608 		scx_exit(sch, SCX_EXIT_UNREG_KERN,
3609 			 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
3610 			 "cpu %d going %s, exiting scheduler", cpu,
3611 			 online ? "online" : "offline");
3612 }
3613 
3614 void scx_rq_activate(struct rq *rq)
3615 {
3616 	handle_hotplug(rq, true);
3617 }
3618 
3619 void scx_rq_deactivate(struct rq *rq)
3620 {
3621 	handle_hotplug(rq, false);
3622 }
3623 
3624 static void rq_online_scx(struct rq *rq)
3625 {
3626 	rq->scx.flags |= SCX_RQ_ONLINE;
3627 }
3628 
3629 static void rq_offline_scx(struct rq *rq)
3630 {
3631 	rq->scx.flags &= ~SCX_RQ_ONLINE;
3632 }
3633 
3634 
3635 static bool check_rq_for_timeouts(struct rq *rq)
3636 {
3637 	struct scx_sched *sch;
3638 	struct task_struct *p;
3639 	struct rq_flags rf;
3640 	bool timed_out = false;
3641 
3642 	rq_lock_irqsave(rq, &rf);
3643 	sch = rcu_dereference_bh(scx_root);
3644 	if (unlikely(!sch))
3645 		goto out_unlock;
3646 
3647 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) {
3648 		unsigned long last_runnable = p->scx.runnable_at;
3649 
3650 		if (unlikely(time_after(jiffies,
3651 					last_runnable + scx_watchdog_timeout))) {
3652 			u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable);
3653 
3654 			scx_exit(sch, SCX_EXIT_ERROR_STALL, 0,
3655 				 "%s[%d] failed to run for %u.%03us",
3656 				 p->comm, p->pid, dur_ms / 1000, dur_ms % 1000);
3657 			timed_out = true;
3658 			break;
3659 		}
3660 	}
3661 out_unlock:
3662 	rq_unlock_irqrestore(rq, &rf);
3663 	return timed_out;
3664 }
3665 
3666 static void scx_watchdog_workfn(struct work_struct *work)
3667 {
3668 	int cpu;
3669 
3670 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
3671 
3672 	for_each_online_cpu(cpu) {
3673 		if (unlikely(check_rq_for_timeouts(cpu_rq(cpu))))
3674 			break;
3675 
3676 		cond_resched();
3677 	}
3678 	queue_delayed_work(system_unbound_wq, to_delayed_work(work),
3679 			   scx_watchdog_timeout / 2);
3680 }
3681 
3682 void scx_tick(struct rq *rq)
3683 {
3684 	struct scx_sched *sch;
3685 	unsigned long last_check;
3686 
3687 	if (!scx_enabled())
3688 		return;
3689 
3690 	sch = rcu_dereference_bh(scx_root);
3691 	if (unlikely(!sch))
3692 		return;
3693 
3694 	last_check = READ_ONCE(scx_watchdog_timestamp);
3695 	if (unlikely(time_after(jiffies,
3696 				last_check + READ_ONCE(scx_watchdog_timeout)))) {
3697 		u32 dur_ms = jiffies_to_msecs(jiffies - last_check);
3698 
3699 		scx_exit(sch, SCX_EXIT_ERROR_STALL, 0,
3700 			 "watchdog failed to check in for %u.%03us",
3701 			 dur_ms / 1000, dur_ms % 1000);
3702 	}
3703 
3704 	update_other_load_avgs(rq);
3705 }
3706 
3707 static void task_tick_scx(struct rq *rq, struct task_struct *curr, int queued)
3708 {
3709 	struct scx_sched *sch = scx_root;
3710 
3711 	update_curr_scx(rq);
3712 
3713 	/*
3714 	 * While disabling, always resched and refresh core-sched timestamp as
3715 	 * we can't trust the slice management or ops.core_sched_before().
3716 	 */
3717 	if (scx_rq_bypassing(rq)) {
3718 		curr->scx.slice = 0;
3719 		touch_core_sched(rq, curr);
3720 	} else if (SCX_HAS_OP(sch, tick)) {
3721 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, tick, rq, curr);
3722 	}
3723 
3724 	if (!curr->scx.slice)
3725 		resched_curr(rq);
3726 }
3727 
3728 #ifdef CONFIG_EXT_GROUP_SCHED
3729 static struct cgroup *tg_cgrp(struct task_group *tg)
3730 {
3731 	/*
3732 	 * If CGROUP_SCHED is disabled, @tg is NULL. If @tg is an autogroup,
3733 	 * @tg->css.cgroup is NULL. In both cases, @tg can be treated as the
3734 	 * root cgroup.
3735 	 */
3736 	if (tg && tg->css.cgroup)
3737 		return tg->css.cgroup;
3738 	else
3739 		return &cgrp_dfl_root.cgrp;
3740 }
3741 
3742 #define SCX_INIT_TASK_ARGS_CGROUP(tg)		.cgroup = tg_cgrp(tg),
3743 
3744 #else	/* CONFIG_EXT_GROUP_SCHED */
3745 
3746 #define SCX_INIT_TASK_ARGS_CGROUP(tg)
3747 
3748 #endif	/* CONFIG_EXT_GROUP_SCHED */
3749 
3750 static enum scx_task_state scx_get_task_state(const struct task_struct *p)
3751 {
3752 	return (p->scx.flags & SCX_TASK_STATE_MASK) >> SCX_TASK_STATE_SHIFT;
3753 }
3754 
3755 static void scx_set_task_state(struct task_struct *p, enum scx_task_state state)
3756 {
3757 	enum scx_task_state prev_state = scx_get_task_state(p);
3758 	bool warn = false;
3759 
3760 	BUILD_BUG_ON(SCX_TASK_NR_STATES > (1 << SCX_TASK_STATE_BITS));
3761 
3762 	switch (state) {
3763 	case SCX_TASK_NONE:
3764 		break;
3765 	case SCX_TASK_INIT:
3766 		warn = prev_state != SCX_TASK_NONE;
3767 		break;
3768 	case SCX_TASK_READY:
3769 		warn = prev_state == SCX_TASK_NONE;
3770 		break;
3771 	case SCX_TASK_ENABLED:
3772 		warn = prev_state != SCX_TASK_READY;
3773 		break;
3774 	default:
3775 		warn = true;
3776 		return;
3777 	}
3778 
3779 	WARN_ONCE(warn, "sched_ext: Invalid task state transition %d -> %d for %s[%d]",
3780 		  prev_state, state, p->comm, p->pid);
3781 
3782 	p->scx.flags &= ~SCX_TASK_STATE_MASK;
3783 	p->scx.flags |= state << SCX_TASK_STATE_SHIFT;
3784 }
3785 
3786 static int scx_init_task(struct task_struct *p, struct task_group *tg, bool fork)
3787 {
3788 	struct scx_sched *sch = scx_root;
3789 	int ret;
3790 
3791 	p->scx.disallow = false;
3792 
3793 	if (SCX_HAS_OP(sch, init_task)) {
3794 		struct scx_init_task_args args = {
3795 			SCX_INIT_TASK_ARGS_CGROUP(tg)
3796 			.fork = fork,
3797 		};
3798 
3799 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init_task, NULL,
3800 				      p, &args);
3801 		if (unlikely(ret)) {
3802 			ret = ops_sanitize_err(sch, "init_task", ret);
3803 			return ret;
3804 		}
3805 	}
3806 
3807 	scx_set_task_state(p, SCX_TASK_INIT);
3808 
3809 	if (p->scx.disallow) {
3810 		if (!fork) {
3811 			struct rq *rq;
3812 			struct rq_flags rf;
3813 
3814 			rq = task_rq_lock(p, &rf);
3815 
3816 			/*
3817 			 * We're in the load path and @p->policy will be applied
3818 			 * right after. Reverting @p->policy here and rejecting
3819 			 * %SCHED_EXT transitions from scx_check_setscheduler()
3820 			 * guarantees that if ops.init_task() sets @p->disallow,
3821 			 * @p can never be in SCX.
3822 			 */
3823 			if (p->policy == SCHED_EXT) {
3824 				p->policy = SCHED_NORMAL;
3825 				atomic_long_inc(&scx_nr_rejected);
3826 			}
3827 
3828 			task_rq_unlock(rq, p, &rf);
3829 		} else if (p->policy == SCHED_EXT) {
3830 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] during fork",
3831 				  p->comm, p->pid);
3832 		}
3833 	}
3834 
3835 	p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
3836 	return 0;
3837 }
3838 
3839 static void scx_enable_task(struct task_struct *p)
3840 {
3841 	struct scx_sched *sch = scx_root;
3842 	struct rq *rq = task_rq(p);
3843 	u32 weight;
3844 
3845 	lockdep_assert_rq_held(rq);
3846 
3847 	/*
3848 	 * Set the weight before calling ops.enable() so that the scheduler
3849 	 * doesn't see a stale value if they inspect the task struct.
3850 	 */
3851 	if (task_has_idle_policy(p))
3852 		weight = WEIGHT_IDLEPRIO;
3853 	else
3854 		weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO];
3855 
3856 	p->scx.weight = sched_weight_to_cgroup(weight);
3857 
3858 	if (SCX_HAS_OP(sch, enable))
3859 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, enable, rq, p);
3860 	scx_set_task_state(p, SCX_TASK_ENABLED);
3861 
3862 	if (SCX_HAS_OP(sch, set_weight))
3863 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq,
3864 				 p, p->scx.weight);
3865 }
3866 
3867 static void scx_disable_task(struct task_struct *p)
3868 {
3869 	struct scx_sched *sch = scx_root;
3870 	struct rq *rq = task_rq(p);
3871 
3872 	lockdep_assert_rq_held(rq);
3873 	WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED);
3874 
3875 	if (SCX_HAS_OP(sch, disable))
3876 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, disable, rq, p);
3877 	scx_set_task_state(p, SCX_TASK_READY);
3878 }
3879 
3880 static void scx_exit_task(struct task_struct *p)
3881 {
3882 	struct scx_sched *sch = scx_root;
3883 	struct scx_exit_task_args args = {
3884 		.cancelled = false,
3885 	};
3886 
3887 	lockdep_assert_rq_held(task_rq(p));
3888 
3889 	switch (scx_get_task_state(p)) {
3890 	case SCX_TASK_NONE:
3891 		return;
3892 	case SCX_TASK_INIT:
3893 		args.cancelled = true;
3894 		break;
3895 	case SCX_TASK_READY:
3896 		break;
3897 	case SCX_TASK_ENABLED:
3898 		scx_disable_task(p);
3899 		break;
3900 	default:
3901 		WARN_ON_ONCE(true);
3902 		return;
3903 	}
3904 
3905 	if (SCX_HAS_OP(sch, exit_task))
3906 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, exit_task, task_rq(p),
3907 				 p, &args);
3908 	scx_set_task_state(p, SCX_TASK_NONE);
3909 }
3910 
3911 void init_scx_entity(struct sched_ext_entity *scx)
3912 {
3913 	memset(scx, 0, sizeof(*scx));
3914 	INIT_LIST_HEAD(&scx->dsq_list.node);
3915 	RB_CLEAR_NODE(&scx->dsq_priq);
3916 	scx->sticky_cpu = -1;
3917 	scx->holding_cpu = -1;
3918 	INIT_LIST_HEAD(&scx->runnable_node);
3919 	scx->runnable_at = jiffies;
3920 	scx->ddsp_dsq_id = SCX_DSQ_INVALID;
3921 	scx->slice = SCX_SLICE_DFL;
3922 }
3923 
3924 void scx_pre_fork(struct task_struct *p)
3925 {
3926 	/*
3927 	 * BPF scheduler enable/disable paths want to be able to iterate and
3928 	 * update all tasks which can become complex when racing forks. As
3929 	 * enable/disable are very cold paths, let's use a percpu_rwsem to
3930 	 * exclude forks.
3931 	 */
3932 	percpu_down_read(&scx_fork_rwsem);
3933 }
3934 
3935 int scx_fork(struct task_struct *p)
3936 {
3937 	percpu_rwsem_assert_held(&scx_fork_rwsem);
3938 
3939 	if (scx_init_task_enabled)
3940 		return scx_init_task(p, task_group(p), true);
3941 	else
3942 		return 0;
3943 }
3944 
3945 void scx_post_fork(struct task_struct *p)
3946 {
3947 	if (scx_init_task_enabled) {
3948 		scx_set_task_state(p, SCX_TASK_READY);
3949 
3950 		/*
3951 		 * Enable the task immediately if it's running on sched_ext.
3952 		 * Otherwise, it'll be enabled in switching_to_scx() if and
3953 		 * when it's ever configured to run with a SCHED_EXT policy.
3954 		 */
3955 		if (p->sched_class == &ext_sched_class) {
3956 			struct rq_flags rf;
3957 			struct rq *rq;
3958 
3959 			rq = task_rq_lock(p, &rf);
3960 			scx_enable_task(p);
3961 			task_rq_unlock(rq, p, &rf);
3962 		}
3963 	}
3964 
3965 	spin_lock_irq(&scx_tasks_lock);
3966 	list_add_tail(&p->scx.tasks_node, &scx_tasks);
3967 	spin_unlock_irq(&scx_tasks_lock);
3968 
3969 	percpu_up_read(&scx_fork_rwsem);
3970 }
3971 
3972 void scx_cancel_fork(struct task_struct *p)
3973 {
3974 	if (scx_enabled()) {
3975 		struct rq *rq;
3976 		struct rq_flags rf;
3977 
3978 		rq = task_rq_lock(p, &rf);
3979 		WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY);
3980 		scx_exit_task(p);
3981 		task_rq_unlock(rq, p, &rf);
3982 	}
3983 
3984 	percpu_up_read(&scx_fork_rwsem);
3985 }
3986 
3987 void sched_ext_free(struct task_struct *p)
3988 {
3989 	unsigned long flags;
3990 
3991 	spin_lock_irqsave(&scx_tasks_lock, flags);
3992 	list_del_init(&p->scx.tasks_node);
3993 	spin_unlock_irqrestore(&scx_tasks_lock, flags);
3994 
3995 	/*
3996 	 * @p is off scx_tasks and wholly ours. scx_enable()'s READY -> ENABLED
3997 	 * transitions can't race us. Disable ops for @p.
3998 	 */
3999 	if (scx_get_task_state(p) != SCX_TASK_NONE) {
4000 		struct rq_flags rf;
4001 		struct rq *rq;
4002 
4003 		rq = task_rq_lock(p, &rf);
4004 		scx_exit_task(p);
4005 		task_rq_unlock(rq, p, &rf);
4006 	}
4007 }
4008 
4009 static void reweight_task_scx(struct rq *rq, struct task_struct *p,
4010 			      const struct load_weight *lw)
4011 {
4012 	struct scx_sched *sch = scx_root;
4013 
4014 	lockdep_assert_rq_held(task_rq(p));
4015 
4016 	p->scx.weight = sched_weight_to_cgroup(scale_load_down(lw->weight));
4017 	if (SCX_HAS_OP(sch, set_weight))
4018 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq,
4019 				 p, p->scx.weight);
4020 }
4021 
4022 static void prio_changed_scx(struct rq *rq, struct task_struct *p, int oldprio)
4023 {
4024 }
4025 
4026 static void switching_to_scx(struct rq *rq, struct task_struct *p)
4027 {
4028 	struct scx_sched *sch = scx_root;
4029 
4030 	scx_enable_task(p);
4031 
4032 	/*
4033 	 * set_cpus_allowed_scx() is not called while @p is associated with a
4034 	 * different scheduler class. Keep the BPF scheduler up-to-date.
4035 	 */
4036 	if (SCX_HAS_OP(sch, set_cpumask))
4037 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, rq,
4038 				 p, (struct cpumask *)p->cpus_ptr);
4039 }
4040 
4041 static void switched_from_scx(struct rq *rq, struct task_struct *p)
4042 {
4043 	scx_disable_task(p);
4044 }
4045 
4046 static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p,int wake_flags) {}
4047 static void switched_to_scx(struct rq *rq, struct task_struct *p) {}
4048 
4049 int scx_check_setscheduler(struct task_struct *p, int policy)
4050 {
4051 	lockdep_assert_rq_held(task_rq(p));
4052 
4053 	/* if disallow, reject transitioning into SCX */
4054 	if (scx_enabled() && READ_ONCE(p->scx.disallow) &&
4055 	    p->policy != policy && policy == SCHED_EXT)
4056 		return -EACCES;
4057 
4058 	return 0;
4059 }
4060 
4061 #ifdef CONFIG_NO_HZ_FULL
4062 bool scx_can_stop_tick(struct rq *rq)
4063 {
4064 	struct task_struct *p = rq->curr;
4065 
4066 	if (scx_rq_bypassing(rq))
4067 		return false;
4068 
4069 	if (p->sched_class != &ext_sched_class)
4070 		return true;
4071 
4072 	/*
4073 	 * @rq can dispatch from different DSQs, so we can't tell whether it
4074 	 * needs the tick or not by looking at nr_running. Allow stopping ticks
4075 	 * iff the BPF scheduler indicated so. See set_next_task_scx().
4076 	 */
4077 	return rq->scx.flags & SCX_RQ_CAN_STOP_TICK;
4078 }
4079 #endif
4080 
4081 #ifdef CONFIG_EXT_GROUP_SCHED
4082 
4083 DEFINE_STATIC_PERCPU_RWSEM(scx_cgroup_rwsem);
4084 static bool scx_cgroup_enabled;
4085 
4086 void scx_tg_init(struct task_group *tg)
4087 {
4088 	tg->scx.weight = CGROUP_WEIGHT_DFL;
4089 	tg->scx.bw_period_us = default_bw_period_us();
4090 	tg->scx.bw_quota_us = RUNTIME_INF;
4091 }
4092 
4093 int scx_tg_online(struct task_group *tg)
4094 {
4095 	struct scx_sched *sch = scx_root;
4096 	int ret = 0;
4097 
4098 	WARN_ON_ONCE(tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED));
4099 
4100 	percpu_down_read(&scx_cgroup_rwsem);
4101 
4102 	if (scx_cgroup_enabled) {
4103 		if (SCX_HAS_OP(sch, cgroup_init)) {
4104 			struct scx_cgroup_init_args args =
4105 				{ .weight = tg->scx.weight,
4106 				  .bw_period_us = tg->scx.bw_period_us,
4107 				  .bw_quota_us = tg->scx.bw_quota_us,
4108 				  .bw_burst_us = tg->scx.bw_burst_us };
4109 
4110 			ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init,
4111 					      NULL, tg->css.cgroup, &args);
4112 			if (ret)
4113 				ret = ops_sanitize_err(sch, "cgroup_init", ret);
4114 		}
4115 		if (ret == 0)
4116 			tg->scx.flags |= SCX_TG_ONLINE | SCX_TG_INITED;
4117 	} else {
4118 		tg->scx.flags |= SCX_TG_ONLINE;
4119 	}
4120 
4121 	percpu_up_read(&scx_cgroup_rwsem);
4122 	return ret;
4123 }
4124 
4125 void scx_tg_offline(struct task_group *tg)
4126 {
4127 	struct scx_sched *sch = scx_root;
4128 
4129 	WARN_ON_ONCE(!(tg->scx.flags & SCX_TG_ONLINE));
4130 
4131 	percpu_down_read(&scx_cgroup_rwsem);
4132 
4133 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_exit) &&
4134 	    (tg->scx.flags & SCX_TG_INITED))
4135 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL,
4136 			    tg->css.cgroup);
4137 	tg->scx.flags &= ~(SCX_TG_ONLINE | SCX_TG_INITED);
4138 
4139 	percpu_up_read(&scx_cgroup_rwsem);
4140 }
4141 
4142 int scx_cgroup_can_attach(struct cgroup_taskset *tset)
4143 {
4144 	struct scx_sched *sch = scx_root;
4145 	struct cgroup_subsys_state *css;
4146 	struct task_struct *p;
4147 	int ret;
4148 
4149 	/* released in scx_finish/cancel_attach() */
4150 	percpu_down_read(&scx_cgroup_rwsem);
4151 
4152 	if (!scx_cgroup_enabled)
4153 		return 0;
4154 
4155 	cgroup_taskset_for_each(p, css, tset) {
4156 		struct cgroup *from = tg_cgrp(task_group(p));
4157 		struct cgroup *to = tg_cgrp(css_tg(css));
4158 
4159 		WARN_ON_ONCE(p->scx.cgrp_moving_from);
4160 
4161 		/*
4162 		 * sched_move_task() omits identity migrations. Let's match the
4163 		 * behavior so that ops.cgroup_prep_move() and ops.cgroup_move()
4164 		 * always match one-to-one.
4165 		 */
4166 		if (from == to)
4167 			continue;
4168 
4169 		if (SCX_HAS_OP(sch, cgroup_prep_move)) {
4170 			ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED,
4171 					      cgroup_prep_move, NULL,
4172 					      p, from, css->cgroup);
4173 			if (ret)
4174 				goto err;
4175 		}
4176 
4177 		p->scx.cgrp_moving_from = from;
4178 	}
4179 
4180 	return 0;
4181 
4182 err:
4183 	cgroup_taskset_for_each(p, css, tset) {
4184 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
4185 		    p->scx.cgrp_moving_from)
4186 			SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL,
4187 				    p, p->scx.cgrp_moving_from, css->cgroup);
4188 		p->scx.cgrp_moving_from = NULL;
4189 	}
4190 
4191 	percpu_up_read(&scx_cgroup_rwsem);
4192 	return ops_sanitize_err(sch, "cgroup_prep_move", ret);
4193 }
4194 
4195 void scx_cgroup_move_task(struct task_struct *p)
4196 {
4197 	struct scx_sched *sch = scx_root;
4198 
4199 	if (!scx_cgroup_enabled)
4200 		return;
4201 
4202 	/*
4203 	 * @p must have ops.cgroup_prep_move() called on it and thus
4204 	 * cgrp_moving_from set.
4205 	 */
4206 	if (SCX_HAS_OP(sch, cgroup_move) &&
4207 	    !WARN_ON_ONCE(!p->scx.cgrp_moving_from))
4208 		SCX_CALL_OP_TASK(sch, SCX_KF_UNLOCKED, cgroup_move, NULL,
4209 				 p, p->scx.cgrp_moving_from,
4210 				 tg_cgrp(task_group(p)));
4211 	p->scx.cgrp_moving_from = NULL;
4212 }
4213 
4214 void scx_cgroup_finish_attach(void)
4215 {
4216 	percpu_up_read(&scx_cgroup_rwsem);
4217 }
4218 
4219 void scx_cgroup_cancel_attach(struct cgroup_taskset *tset)
4220 {
4221 	struct scx_sched *sch = scx_root;
4222 	struct cgroup_subsys_state *css;
4223 	struct task_struct *p;
4224 
4225 	if (!scx_cgroup_enabled)
4226 		goto out_unlock;
4227 
4228 	cgroup_taskset_for_each(p, css, tset) {
4229 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
4230 		    p->scx.cgrp_moving_from)
4231 			SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL,
4232 				    p, p->scx.cgrp_moving_from, css->cgroup);
4233 		p->scx.cgrp_moving_from = NULL;
4234 	}
4235 out_unlock:
4236 	percpu_up_read(&scx_cgroup_rwsem);
4237 }
4238 
4239 void scx_group_set_weight(struct task_group *tg, unsigned long weight)
4240 {
4241 	struct scx_sched *sch = scx_root;
4242 
4243 	percpu_down_read(&scx_cgroup_rwsem);
4244 
4245 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_weight) &&
4246 	    tg->scx.weight != weight)
4247 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_weight, NULL,
4248 			    tg_cgrp(tg), weight);
4249 
4250 	tg->scx.weight = weight;
4251 
4252 	percpu_up_read(&scx_cgroup_rwsem);
4253 }
4254 
4255 void scx_group_set_idle(struct task_group *tg, bool idle)
4256 {
4257 	/* TODO: Implement ops->cgroup_set_idle() */
4258 }
4259 
4260 void scx_group_set_bandwidth(struct task_group *tg,
4261 			     u64 period_us, u64 quota_us, u64 burst_us)
4262 {
4263 	struct scx_sched *sch = scx_root;
4264 
4265 	percpu_down_read(&scx_cgroup_rwsem);
4266 
4267 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_bandwidth) &&
4268 	    (tg->scx.bw_period_us != period_us ||
4269 	     tg->scx.bw_quota_us != quota_us ||
4270 	     tg->scx.bw_burst_us != burst_us))
4271 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_bandwidth, NULL,
4272 			    tg_cgrp(tg), period_us, quota_us, burst_us);
4273 
4274 	tg->scx.bw_period_us = period_us;
4275 	tg->scx.bw_quota_us = quota_us;
4276 	tg->scx.bw_burst_us = burst_us;
4277 
4278 	percpu_up_read(&scx_cgroup_rwsem);
4279 }
4280 
4281 static void scx_cgroup_lock(void)
4282 {
4283 	percpu_down_write(&scx_cgroup_rwsem);
4284 }
4285 
4286 static void scx_cgroup_unlock(void)
4287 {
4288 	percpu_up_write(&scx_cgroup_rwsem);
4289 }
4290 
4291 #else	/* CONFIG_EXT_GROUP_SCHED */
4292 
4293 static inline void scx_cgroup_lock(void) {}
4294 static inline void scx_cgroup_unlock(void) {}
4295 
4296 #endif	/* CONFIG_EXT_GROUP_SCHED */
4297 
4298 /*
4299  * Omitted operations:
4300  *
4301  * - wakeup_preempt: NOOP as it isn't useful in the wakeup path because the task
4302  *   isn't tied to the CPU at that point. Preemption is implemented by resetting
4303  *   the victim task's slice to 0 and triggering reschedule on the target CPU.
4304  *
4305  * - migrate_task_rq: Unnecessary as task to cpu mapping is transient.
4306  *
4307  * - task_fork/dead: We need fork/dead notifications for all tasks regardless of
4308  *   their current sched_class. Call them directly from sched core instead.
4309  */
4310 DEFINE_SCHED_CLASS(ext) = {
4311 	.enqueue_task		= enqueue_task_scx,
4312 	.dequeue_task		= dequeue_task_scx,
4313 	.yield_task		= yield_task_scx,
4314 	.yield_to_task		= yield_to_task_scx,
4315 
4316 	.wakeup_preempt		= wakeup_preempt_scx,
4317 
4318 	.balance		= balance_scx,
4319 	.pick_task		= pick_task_scx,
4320 
4321 	.put_prev_task		= put_prev_task_scx,
4322 	.set_next_task		= set_next_task_scx,
4323 
4324 	.select_task_rq		= select_task_rq_scx,
4325 	.task_woken		= task_woken_scx,
4326 	.set_cpus_allowed	= set_cpus_allowed_scx,
4327 
4328 	.rq_online		= rq_online_scx,
4329 	.rq_offline		= rq_offline_scx,
4330 
4331 	.task_tick		= task_tick_scx,
4332 
4333 	.switching_to		= switching_to_scx,
4334 	.switched_from		= switched_from_scx,
4335 	.switched_to		= switched_to_scx,
4336 	.reweight_task		= reweight_task_scx,
4337 	.prio_changed		= prio_changed_scx,
4338 
4339 	.update_curr		= update_curr_scx,
4340 
4341 #ifdef CONFIG_UCLAMP_TASK
4342 	.uclamp_enabled		= 1,
4343 #endif
4344 };
4345 
4346 static void init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id)
4347 {
4348 	memset(dsq, 0, sizeof(*dsq));
4349 
4350 	raw_spin_lock_init(&dsq->lock);
4351 	INIT_LIST_HEAD(&dsq->list);
4352 	dsq->id = dsq_id;
4353 }
4354 
4355 static void free_dsq_irq_workfn(struct irq_work *irq_work)
4356 {
4357 	struct llist_node *to_free = llist_del_all(&dsqs_to_free);
4358 	struct scx_dispatch_q *dsq, *tmp_dsq;
4359 
4360 	llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node)
4361 		kfree_rcu(dsq, rcu);
4362 }
4363 
4364 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn);
4365 
4366 static void destroy_dsq(struct scx_sched *sch, u64 dsq_id)
4367 {
4368 	struct scx_dispatch_q *dsq;
4369 	unsigned long flags;
4370 
4371 	rcu_read_lock();
4372 
4373 	dsq = find_user_dsq(sch, dsq_id);
4374 	if (!dsq)
4375 		goto out_unlock_rcu;
4376 
4377 	raw_spin_lock_irqsave(&dsq->lock, flags);
4378 
4379 	if (dsq->nr) {
4380 		scx_error(sch, "attempting to destroy in-use dsq 0x%016llx (nr=%u)",
4381 			  dsq->id, dsq->nr);
4382 		goto out_unlock_dsq;
4383 	}
4384 
4385 	if (rhashtable_remove_fast(&sch->dsq_hash, &dsq->hash_node,
4386 				   dsq_hash_params))
4387 		goto out_unlock_dsq;
4388 
4389 	/*
4390 	 * Mark dead by invalidating ->id to prevent dispatch_enqueue() from
4391 	 * queueing more tasks. As this function can be called from anywhere,
4392 	 * freeing is bounced through an irq work to avoid nesting RCU
4393 	 * operations inside scheduler locks.
4394 	 */
4395 	dsq->id = SCX_DSQ_INVALID;
4396 	llist_add(&dsq->free_node, &dsqs_to_free);
4397 	irq_work_queue(&free_dsq_irq_work);
4398 
4399 out_unlock_dsq:
4400 	raw_spin_unlock_irqrestore(&dsq->lock, flags);
4401 out_unlock_rcu:
4402 	rcu_read_unlock();
4403 }
4404 
4405 #ifdef CONFIG_EXT_GROUP_SCHED
4406 static void scx_cgroup_exit(struct scx_sched *sch)
4407 {
4408 	struct cgroup_subsys_state *css;
4409 
4410 	percpu_rwsem_assert_held(&scx_cgroup_rwsem);
4411 
4412 	scx_cgroup_enabled = false;
4413 
4414 	/*
4415 	 * scx_tg_on/offline() are excluded through scx_cgroup_rwsem. If we walk
4416 	 * cgroups and exit all the inited ones, all online cgroups are exited.
4417 	 */
4418 	rcu_read_lock();
4419 	css_for_each_descendant_post(css, &root_task_group.css) {
4420 		struct task_group *tg = css_tg(css);
4421 
4422 		if (!(tg->scx.flags & SCX_TG_INITED))
4423 			continue;
4424 		tg->scx.flags &= ~SCX_TG_INITED;
4425 
4426 		if (!sch->ops.cgroup_exit)
4427 			continue;
4428 
4429 		if (WARN_ON_ONCE(!css_tryget(css)))
4430 			continue;
4431 		rcu_read_unlock();
4432 
4433 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL,
4434 			    css->cgroup);
4435 
4436 		rcu_read_lock();
4437 		css_put(css);
4438 	}
4439 	rcu_read_unlock();
4440 }
4441 
4442 static int scx_cgroup_init(struct scx_sched *sch)
4443 {
4444 	struct cgroup_subsys_state *css;
4445 	int ret;
4446 
4447 	percpu_rwsem_assert_held(&scx_cgroup_rwsem);
4448 
4449 	/*
4450 	 * scx_tg_on/offline() are excluded through scx_cgroup_rwsem. If we walk
4451 	 * cgroups and init, all online cgroups are initialized.
4452 	 */
4453 	rcu_read_lock();
4454 	css_for_each_descendant_pre(css, &root_task_group.css) {
4455 		struct task_group *tg = css_tg(css);
4456 		struct scx_cgroup_init_args args = {
4457 			.weight = tg->scx.weight,
4458 			.bw_period_us = tg->scx.bw_period_us,
4459 			.bw_quota_us = tg->scx.bw_quota_us,
4460 			.bw_burst_us = tg->scx.bw_burst_us,
4461 		};
4462 
4463 		if ((tg->scx.flags &
4464 		     (SCX_TG_ONLINE | SCX_TG_INITED)) != SCX_TG_ONLINE)
4465 			continue;
4466 
4467 		if (!sch->ops.cgroup_init) {
4468 			tg->scx.flags |= SCX_TG_INITED;
4469 			continue;
4470 		}
4471 
4472 		if (WARN_ON_ONCE(!css_tryget(css)))
4473 			continue;
4474 		rcu_read_unlock();
4475 
4476 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init, NULL,
4477 				      css->cgroup, &args);
4478 		if (ret) {
4479 			css_put(css);
4480 			scx_error(sch, "ops.cgroup_init() failed (%d)", ret);
4481 			return ret;
4482 		}
4483 		tg->scx.flags |= SCX_TG_INITED;
4484 
4485 		rcu_read_lock();
4486 		css_put(css);
4487 	}
4488 	rcu_read_unlock();
4489 
4490 	WARN_ON_ONCE(scx_cgroup_enabled);
4491 	scx_cgroup_enabled = true;
4492 
4493 	return 0;
4494 }
4495 
4496 #else
4497 static void scx_cgroup_exit(struct scx_sched *sch) {}
4498 static int scx_cgroup_init(struct scx_sched *sch) { return 0; }
4499 #endif
4500 
4501 
4502 /********************************************************************************
4503  * Sysfs interface and ops enable/disable.
4504  */
4505 
4506 #define SCX_ATTR(_name)								\
4507 	static struct kobj_attribute scx_attr_##_name = {			\
4508 		.attr = { .name = __stringify(_name), .mode = 0444 },		\
4509 		.show = scx_attr_##_name##_show,				\
4510 	}
4511 
4512 static ssize_t scx_attr_state_show(struct kobject *kobj,
4513 				   struct kobj_attribute *ka, char *buf)
4514 {
4515 	return sysfs_emit(buf, "%s\n", scx_enable_state_str[scx_enable_state()]);
4516 }
4517 SCX_ATTR(state);
4518 
4519 static ssize_t scx_attr_switch_all_show(struct kobject *kobj,
4520 					struct kobj_attribute *ka, char *buf)
4521 {
4522 	return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all));
4523 }
4524 SCX_ATTR(switch_all);
4525 
4526 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj,
4527 					 struct kobj_attribute *ka, char *buf)
4528 {
4529 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected));
4530 }
4531 SCX_ATTR(nr_rejected);
4532 
4533 static ssize_t scx_attr_hotplug_seq_show(struct kobject *kobj,
4534 					 struct kobj_attribute *ka, char *buf)
4535 {
4536 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_hotplug_seq));
4537 }
4538 SCX_ATTR(hotplug_seq);
4539 
4540 static ssize_t scx_attr_enable_seq_show(struct kobject *kobj,
4541 					struct kobj_attribute *ka, char *buf)
4542 {
4543 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_enable_seq));
4544 }
4545 SCX_ATTR(enable_seq);
4546 
4547 static struct attribute *scx_global_attrs[] = {
4548 	&scx_attr_state.attr,
4549 	&scx_attr_switch_all.attr,
4550 	&scx_attr_nr_rejected.attr,
4551 	&scx_attr_hotplug_seq.attr,
4552 	&scx_attr_enable_seq.attr,
4553 	NULL,
4554 };
4555 
4556 static const struct attribute_group scx_global_attr_group = {
4557 	.attrs = scx_global_attrs,
4558 };
4559 
4560 static void free_exit_info(struct scx_exit_info *ei);
4561 
4562 static void scx_sched_free_rcu_work(struct work_struct *work)
4563 {
4564 	struct rcu_work *rcu_work = to_rcu_work(work);
4565 	struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work);
4566 	struct rhashtable_iter rht_iter;
4567 	struct scx_dispatch_q *dsq;
4568 	int node;
4569 
4570 	kthread_stop(sch->helper->task);
4571 	free_percpu(sch->event_stats_cpu);
4572 
4573 	for_each_node_state(node, N_POSSIBLE)
4574 		kfree(sch->global_dsqs[node]);
4575 	kfree(sch->global_dsqs);
4576 
4577 	rhashtable_walk_enter(&sch->dsq_hash, &rht_iter);
4578 	do {
4579 		rhashtable_walk_start(&rht_iter);
4580 
4581 		while ((dsq = rhashtable_walk_next(&rht_iter)) && !IS_ERR(dsq))
4582 			destroy_dsq(sch, dsq->id);
4583 
4584 		rhashtable_walk_stop(&rht_iter);
4585 	} while (dsq == ERR_PTR(-EAGAIN));
4586 	rhashtable_walk_exit(&rht_iter);
4587 
4588 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
4589 	free_exit_info(sch->exit_info);
4590 	kfree(sch);
4591 }
4592 
4593 static void scx_kobj_release(struct kobject *kobj)
4594 {
4595 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
4596 
4597 	INIT_RCU_WORK(&sch->rcu_work, scx_sched_free_rcu_work);
4598 	queue_rcu_work(system_unbound_wq, &sch->rcu_work);
4599 }
4600 
4601 static ssize_t scx_attr_ops_show(struct kobject *kobj,
4602 				 struct kobj_attribute *ka, char *buf)
4603 {
4604 	return sysfs_emit(buf, "%s\n", scx_root->ops.name);
4605 }
4606 SCX_ATTR(ops);
4607 
4608 #define scx_attr_event_show(buf, at, events, kind) ({				\
4609 	sysfs_emit_at(buf, at, "%s %llu\n", #kind, (events)->kind);		\
4610 })
4611 
4612 static ssize_t scx_attr_events_show(struct kobject *kobj,
4613 				    struct kobj_attribute *ka, char *buf)
4614 {
4615 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
4616 	struct scx_event_stats events;
4617 	int at = 0;
4618 
4619 	scx_read_events(sch, &events);
4620 	at += scx_attr_event_show(buf, at, &events, SCX_EV_SELECT_CPU_FALLBACK);
4621 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
4622 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_KEEP_LAST);
4623 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_EXITING);
4624 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
4625 	at += scx_attr_event_show(buf, at, &events, SCX_EV_REFILL_SLICE_DFL);
4626 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DURATION);
4627 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DISPATCH);
4628 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_ACTIVATE);
4629 	return at;
4630 }
4631 SCX_ATTR(events);
4632 
4633 static struct attribute *scx_sched_attrs[] = {
4634 	&scx_attr_ops.attr,
4635 	&scx_attr_events.attr,
4636 	NULL,
4637 };
4638 ATTRIBUTE_GROUPS(scx_sched);
4639 
4640 static const struct kobj_type scx_ktype = {
4641 	.release = scx_kobj_release,
4642 	.sysfs_ops = &kobj_sysfs_ops,
4643 	.default_groups = scx_sched_groups,
4644 };
4645 
4646 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
4647 {
4648 	return add_uevent_var(env, "SCXOPS=%s", scx_root->ops.name);
4649 }
4650 
4651 static const struct kset_uevent_ops scx_uevent_ops = {
4652 	.uevent = scx_uevent,
4653 };
4654 
4655 /*
4656  * Used by sched_fork() and __setscheduler_prio() to pick the matching
4657  * sched_class. dl/rt are already handled.
4658  */
4659 bool task_should_scx(int policy)
4660 {
4661 	if (!scx_enabled() || unlikely(scx_enable_state() == SCX_DISABLING))
4662 		return false;
4663 	if (READ_ONCE(scx_switching_all))
4664 		return true;
4665 	return policy == SCHED_EXT;
4666 }
4667 
4668 bool scx_allow_ttwu_queue(const struct task_struct *p)
4669 {
4670 	return !scx_enabled() ||
4671 		(scx_root->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP) ||
4672 		p->sched_class != &ext_sched_class;
4673 }
4674 
4675 /**
4676  * scx_softlockup - sched_ext softlockup handler
4677  * @dur_s: number of seconds of CPU stuck due to soft lockup
4678  *
4679  * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can
4680  * live-lock the system by making many CPUs target the same DSQ to the point
4681  * where soft-lockup detection triggers. This function is called from
4682  * soft-lockup watchdog when the triggering point is close and tries to unjam
4683  * the system by enabling the breather and aborting the BPF scheduler.
4684  */
4685 void scx_softlockup(u32 dur_s)
4686 {
4687 	struct scx_sched *sch;
4688 
4689 	rcu_read_lock();
4690 
4691 	sch = rcu_dereference(scx_root);
4692 	if (unlikely(!sch))
4693 		goto out_unlock;
4694 
4695 	switch (scx_enable_state()) {
4696 	case SCX_ENABLING:
4697 	case SCX_ENABLED:
4698 		break;
4699 	default:
4700 		goto out_unlock;
4701 	}
4702 
4703 	/* allow only one instance, cleared at the end of scx_bypass() */
4704 	if (test_and_set_bit(0, &scx_in_softlockup))
4705 		goto out_unlock;
4706 
4707 	printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU%d stuck for %us, disabling \"%s\"\n",
4708 			smp_processor_id(), dur_s, scx_root->ops.name);
4709 
4710 	/*
4711 	 * Some CPUs may be trapped in the dispatch paths. Enable breather
4712 	 * immediately; otherwise, we might even be able to get to scx_bypass().
4713 	 */
4714 	atomic_inc(&scx_breather_depth);
4715 
4716 	scx_error(sch, "soft lockup - CPU#%d stuck for %us", smp_processor_id(), dur_s);
4717 out_unlock:
4718 	rcu_read_unlock();
4719 }
4720 
4721 static void scx_clear_softlockup(void)
4722 {
4723 	if (test_and_clear_bit(0, &scx_in_softlockup))
4724 		atomic_dec(&scx_breather_depth);
4725 }
4726 
4727 /**
4728  * scx_bypass - [Un]bypass scx_ops and guarantee forward progress
4729  * @bypass: true for bypass, false for unbypass
4730  *
4731  * Bypassing guarantees that all runnable tasks make forward progress without
4732  * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might
4733  * be held by tasks that the BPF scheduler is forgetting to run, which
4734  * unfortunately also excludes toggling the static branches.
4735  *
4736  * Let's work around by overriding a couple ops and modifying behaviors based on
4737  * the DISABLING state and then cycling the queued tasks through dequeue/enqueue
4738  * to force global FIFO scheduling.
4739  *
4740  * - ops.select_cpu() is ignored and the default select_cpu() is used.
4741  *
4742  * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order.
4743  *   %SCX_OPS_ENQ_LAST is also ignored.
4744  *
4745  * - ops.dispatch() is ignored.
4746  *
4747  * - balance_scx() does not set %SCX_RQ_BAL_KEEP on non-zero slice as slice
4748  *   can't be trusted. Whenever a tick triggers, the running task is rotated to
4749  *   the tail of the queue with core_sched_at touched.
4750  *
4751  * - pick_next_task() suppresses zero slice warning.
4752  *
4753  * - scx_bpf_kick_cpu() is disabled to avoid irq_work malfunction during PM
4754  *   operations.
4755  *
4756  * - scx_prio_less() reverts to the default core_sched_at order.
4757  */
4758 static void scx_bypass(bool bypass)
4759 {
4760 	static DEFINE_RAW_SPINLOCK(bypass_lock);
4761 	static unsigned long bypass_timestamp;
4762 	struct scx_sched *sch;
4763 	unsigned long flags;
4764 	int cpu;
4765 
4766 	raw_spin_lock_irqsave(&bypass_lock, flags);
4767 	sch = rcu_dereference_bh(scx_root);
4768 
4769 	if (bypass) {
4770 		scx_bypass_depth++;
4771 		WARN_ON_ONCE(scx_bypass_depth <= 0);
4772 		if (scx_bypass_depth != 1)
4773 			goto unlock;
4774 		bypass_timestamp = ktime_get_ns();
4775 		if (sch)
4776 			scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1);
4777 	} else {
4778 		scx_bypass_depth--;
4779 		WARN_ON_ONCE(scx_bypass_depth < 0);
4780 		if (scx_bypass_depth != 0)
4781 			goto unlock;
4782 		if (sch)
4783 			scx_add_event(sch, SCX_EV_BYPASS_DURATION,
4784 				      ktime_get_ns() - bypass_timestamp);
4785 	}
4786 
4787 	atomic_inc(&scx_breather_depth);
4788 
4789 	/*
4790 	 * No task property is changing. We just need to make sure all currently
4791 	 * queued tasks are re-queued according to the new scx_rq_bypassing()
4792 	 * state. As an optimization, walk each rq's runnable_list instead of
4793 	 * the scx_tasks list.
4794 	 *
4795 	 * This function can't trust the scheduler and thus can't use
4796 	 * cpus_read_lock(). Walk all possible CPUs instead of online.
4797 	 */
4798 	for_each_possible_cpu(cpu) {
4799 		struct rq *rq = cpu_rq(cpu);
4800 		struct task_struct *p, *n;
4801 
4802 		raw_spin_rq_lock(rq);
4803 
4804 		if (bypass) {
4805 			WARN_ON_ONCE(rq->scx.flags & SCX_RQ_BYPASSING);
4806 			rq->scx.flags |= SCX_RQ_BYPASSING;
4807 		} else {
4808 			WARN_ON_ONCE(!(rq->scx.flags & SCX_RQ_BYPASSING));
4809 			rq->scx.flags &= ~SCX_RQ_BYPASSING;
4810 		}
4811 
4812 		/*
4813 		 * We need to guarantee that no tasks are on the BPF scheduler
4814 		 * while bypassing. Either we see enabled or the enable path
4815 		 * sees scx_rq_bypassing() before moving tasks to SCX.
4816 		 */
4817 		if (!scx_enabled()) {
4818 			raw_spin_rq_unlock(rq);
4819 			continue;
4820 		}
4821 
4822 		/*
4823 		 * The use of list_for_each_entry_safe_reverse() is required
4824 		 * because each task is going to be removed from and added back
4825 		 * to the runnable_list during iteration. Because they're added
4826 		 * to the tail of the list, safe reverse iteration can still
4827 		 * visit all nodes.
4828 		 */
4829 		list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list,
4830 						 scx.runnable_node) {
4831 			struct sched_enq_and_set_ctx ctx;
4832 
4833 			/* cycling deq/enq is enough, see the function comment */
4834 			sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
4835 			sched_enq_and_set_task(&ctx);
4836 		}
4837 
4838 		/* resched to restore ticks and idle state */
4839 		if (cpu_online(cpu) || cpu == smp_processor_id())
4840 			resched_curr(rq);
4841 
4842 		raw_spin_rq_unlock(rq);
4843 	}
4844 
4845 	atomic_dec(&scx_breather_depth);
4846 unlock:
4847 	raw_spin_unlock_irqrestore(&bypass_lock, flags);
4848 	scx_clear_softlockup();
4849 }
4850 
4851 static void free_exit_info(struct scx_exit_info *ei)
4852 {
4853 	kvfree(ei->dump);
4854 	kfree(ei->msg);
4855 	kfree(ei->bt);
4856 	kfree(ei);
4857 }
4858 
4859 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
4860 {
4861 	struct scx_exit_info *ei;
4862 
4863 	ei = kzalloc(sizeof(*ei), GFP_KERNEL);
4864 	if (!ei)
4865 		return NULL;
4866 
4867 	ei->bt = kcalloc(SCX_EXIT_BT_LEN, sizeof(ei->bt[0]), GFP_KERNEL);
4868 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
4869 	ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL);
4870 
4871 	if (!ei->bt || !ei->msg || !ei->dump) {
4872 		free_exit_info(ei);
4873 		return NULL;
4874 	}
4875 
4876 	return ei;
4877 }
4878 
4879 static const char *scx_exit_reason(enum scx_exit_kind kind)
4880 {
4881 	switch (kind) {
4882 	case SCX_EXIT_UNREG:
4883 		return "unregistered from user space";
4884 	case SCX_EXIT_UNREG_BPF:
4885 		return "unregistered from BPF";
4886 	case SCX_EXIT_UNREG_KERN:
4887 		return "unregistered from the main kernel";
4888 	case SCX_EXIT_SYSRQ:
4889 		return "disabled by sysrq-S";
4890 	case SCX_EXIT_ERROR:
4891 		return "runtime error";
4892 	case SCX_EXIT_ERROR_BPF:
4893 		return "scx_bpf_error";
4894 	case SCX_EXIT_ERROR_STALL:
4895 		return "runnable task stall";
4896 	default:
4897 		return "<UNKNOWN>";
4898 	}
4899 }
4900 
4901 static void scx_disable_workfn(struct kthread_work *work)
4902 {
4903 	struct scx_sched *sch = container_of(work, struct scx_sched, disable_work);
4904 	struct scx_exit_info *ei = sch->exit_info;
4905 	struct scx_task_iter sti;
4906 	struct task_struct *p;
4907 	int kind, cpu;
4908 
4909 	kind = atomic_read(&sch->exit_kind);
4910 	while (true) {
4911 		if (kind == SCX_EXIT_DONE)	/* already disabled? */
4912 			return;
4913 		WARN_ON_ONCE(kind == SCX_EXIT_NONE);
4914 		if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE))
4915 			break;
4916 	}
4917 	ei->kind = kind;
4918 	ei->reason = scx_exit_reason(ei->kind);
4919 
4920 	/* guarantee forward progress by bypassing scx_ops */
4921 	scx_bypass(true);
4922 
4923 	switch (scx_set_enable_state(SCX_DISABLING)) {
4924 	case SCX_DISABLING:
4925 		WARN_ONCE(true, "sched_ext: duplicate disabling instance?");
4926 		break;
4927 	case SCX_DISABLED:
4928 		pr_warn("sched_ext: ops error detected without ops (%s)\n",
4929 			sch->exit_info->msg);
4930 		WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
4931 		goto done;
4932 	default:
4933 		break;
4934 	}
4935 
4936 	/*
4937 	 * Here, every runnable task is guaranteed to make forward progress and
4938 	 * we can safely use blocking synchronization constructs. Actually
4939 	 * disable ops.
4940 	 */
4941 	mutex_lock(&scx_enable_mutex);
4942 
4943 	static_branch_disable(&__scx_switched_all);
4944 	WRITE_ONCE(scx_switching_all, false);
4945 
4946 	/*
4947 	 * Shut down cgroup support before tasks so that the cgroup attach path
4948 	 * doesn't race against scx_exit_task().
4949 	 */
4950 	scx_cgroup_lock();
4951 	scx_cgroup_exit(sch);
4952 	scx_cgroup_unlock();
4953 
4954 	/*
4955 	 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones
4956 	 * must be switched out and exited synchronously.
4957 	 */
4958 	percpu_down_write(&scx_fork_rwsem);
4959 
4960 	scx_init_task_enabled = false;
4961 
4962 	scx_task_iter_start(&sti);
4963 	while ((p = scx_task_iter_next_locked(&sti))) {
4964 		const struct sched_class *old_class = p->sched_class;
4965 		const struct sched_class *new_class =
4966 			__setscheduler_class(p->policy, p->prio);
4967 		struct sched_enq_and_set_ctx ctx;
4968 
4969 		if (old_class != new_class && p->se.sched_delayed)
4970 			dequeue_task(task_rq(p), p, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
4971 
4972 		sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
4973 
4974 		p->sched_class = new_class;
4975 		check_class_changing(task_rq(p), p, old_class);
4976 
4977 		sched_enq_and_set_task(&ctx);
4978 
4979 		check_class_changed(task_rq(p), p, old_class, p->prio);
4980 		scx_exit_task(p);
4981 	}
4982 	scx_task_iter_stop(&sti);
4983 	percpu_up_write(&scx_fork_rwsem);
4984 
4985 	/*
4986 	 * Invalidate all the rq clocks to prevent getting outdated
4987 	 * rq clocks from a previous scx scheduler.
4988 	 */
4989 	for_each_possible_cpu(cpu) {
4990 		struct rq *rq = cpu_rq(cpu);
4991 		scx_rq_clock_invalidate(rq);
4992 	}
4993 
4994 	/* no task is on scx, turn off all the switches and flush in-progress calls */
4995 	static_branch_disable(&__scx_enabled);
4996 	bitmap_zero(sch->has_op, SCX_OPI_END);
4997 	scx_idle_disable();
4998 	synchronize_rcu();
4999 
5000 	if (ei->kind >= SCX_EXIT_ERROR) {
5001 		pr_err("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
5002 		       sch->ops.name, ei->reason);
5003 
5004 		if (ei->msg[0] != '\0')
5005 			pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg);
5006 #ifdef CONFIG_STACKTRACE
5007 		stack_trace_print(ei->bt, ei->bt_len, 2);
5008 #endif
5009 	} else {
5010 		pr_info("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
5011 			sch->ops.name, ei->reason);
5012 	}
5013 
5014 	if (sch->ops.exit)
5015 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, exit, NULL, ei);
5016 
5017 	cancel_delayed_work_sync(&scx_watchdog_work);
5018 
5019 	/*
5020 	 * scx_root clearing must be inside cpus_read_lock(). See
5021 	 * handle_hotplug().
5022 	 */
5023 	cpus_read_lock();
5024 	RCU_INIT_POINTER(scx_root, NULL);
5025 	cpus_read_unlock();
5026 
5027 	/*
5028 	 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs
5029 	 * could observe an object of the same name still in the hierarchy when
5030 	 * the next scheduler is loaded.
5031 	 */
5032 	kobject_del(&sch->kobj);
5033 
5034 	free_percpu(scx_dsp_ctx);
5035 	scx_dsp_ctx = NULL;
5036 	scx_dsp_max_batch = 0;
5037 
5038 	mutex_unlock(&scx_enable_mutex);
5039 
5040 	WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
5041 done:
5042 	scx_bypass(false);
5043 }
5044 
5045 static void scx_disable(enum scx_exit_kind kind)
5046 {
5047 	int none = SCX_EXIT_NONE;
5048 	struct scx_sched *sch;
5049 
5050 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
5051 		kind = SCX_EXIT_ERROR;
5052 
5053 	rcu_read_lock();
5054 	sch = rcu_dereference(scx_root);
5055 	if (sch) {
5056 		atomic_try_cmpxchg(&sch->exit_kind, &none, kind);
5057 		kthread_queue_work(sch->helper, &sch->disable_work);
5058 	}
5059 	rcu_read_unlock();
5060 }
5061 
5062 static void dump_newline(struct seq_buf *s)
5063 {
5064 	trace_sched_ext_dump("");
5065 
5066 	/* @s may be zero sized and seq_buf triggers WARN if so */
5067 	if (s->size)
5068 		seq_buf_putc(s, '\n');
5069 }
5070 
5071 static __printf(2, 3) void dump_line(struct seq_buf *s, const char *fmt, ...)
5072 {
5073 	va_list args;
5074 
5075 #ifdef CONFIG_TRACEPOINTS
5076 	if (trace_sched_ext_dump_enabled()) {
5077 		/* protected by scx_dump_state()::dump_lock */
5078 		static char line_buf[SCX_EXIT_MSG_LEN];
5079 
5080 		va_start(args, fmt);
5081 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
5082 		va_end(args);
5083 
5084 		trace_sched_ext_dump(line_buf);
5085 	}
5086 #endif
5087 	/* @s may be zero sized and seq_buf triggers WARN if so */
5088 	if (s->size) {
5089 		va_start(args, fmt);
5090 		seq_buf_vprintf(s, fmt, args);
5091 		va_end(args);
5092 
5093 		seq_buf_putc(s, '\n');
5094 	}
5095 }
5096 
5097 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
5098 			     const unsigned long *bt, unsigned int len)
5099 {
5100 	unsigned int i;
5101 
5102 	for (i = 0; i < len; i++)
5103 		dump_line(s, "%s%pS", prefix, (void *)bt[i]);
5104 }
5105 
5106 static void ops_dump_init(struct seq_buf *s, const char *prefix)
5107 {
5108 	struct scx_dump_data *dd = &scx_dump_data;
5109 
5110 	lockdep_assert_irqs_disabled();
5111 
5112 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
5113 	dd->first = true;
5114 	dd->cursor = 0;
5115 	dd->s = s;
5116 	dd->prefix = prefix;
5117 }
5118 
5119 static void ops_dump_flush(void)
5120 {
5121 	struct scx_dump_data *dd = &scx_dump_data;
5122 	char *line = dd->buf.line;
5123 
5124 	if (!dd->cursor)
5125 		return;
5126 
5127 	/*
5128 	 * There's something to flush and this is the first line. Insert a blank
5129 	 * line to distinguish ops dump.
5130 	 */
5131 	if (dd->first) {
5132 		dump_newline(dd->s);
5133 		dd->first = false;
5134 	}
5135 
5136 	/*
5137 	 * There may be multiple lines in $line. Scan and emit each line
5138 	 * separately.
5139 	 */
5140 	while (true) {
5141 		char *end = line;
5142 		char c;
5143 
5144 		while (*end != '\n' && *end != '\0')
5145 			end++;
5146 
5147 		/*
5148 		 * If $line overflowed, it may not have newline at the end.
5149 		 * Always emit with a newline.
5150 		 */
5151 		c = *end;
5152 		*end = '\0';
5153 		dump_line(dd->s, "%s%s", dd->prefix, line);
5154 		if (c == '\0')
5155 			break;
5156 
5157 		/* move to the next line */
5158 		end++;
5159 		if (*end == '\0')
5160 			break;
5161 		line = end;
5162 	}
5163 
5164 	dd->cursor = 0;
5165 }
5166 
5167 static void ops_dump_exit(void)
5168 {
5169 	ops_dump_flush();
5170 	scx_dump_data.cpu = -1;
5171 }
5172 
5173 static void scx_dump_task(struct seq_buf *s, struct scx_dump_ctx *dctx,
5174 			  struct task_struct *p, char marker)
5175 {
5176 	static unsigned long bt[SCX_EXIT_BT_LEN];
5177 	struct scx_sched *sch = scx_root;
5178 	char dsq_id_buf[19] = "(n/a)";
5179 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
5180 	unsigned int bt_len = 0;
5181 
5182 	if (p->scx.dsq)
5183 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
5184 			  (unsigned long long)p->scx.dsq->id);
5185 
5186 	dump_newline(s);
5187 	dump_line(s, " %c%c %s[%d] %+ldms",
5188 		  marker, task_state_to_char(p), p->comm, p->pid,
5189 		  jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
5190 	dump_line(s, "      scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu",
5191 		  scx_get_task_state(p), p->scx.flags & ~SCX_TASK_STATE_MASK,
5192 		  p->scx.dsq_flags, ops_state & SCX_OPSS_STATE_MASK,
5193 		  ops_state >> SCX_OPSS_QSEQ_SHIFT);
5194 	dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
5195 		  p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
5196 	dump_line(s, "      dsq_vtime=%llu slice=%llu weight=%u",
5197 		  p->scx.dsq_vtime, p->scx.slice, p->scx.weight);
5198 	dump_line(s, "      cpus=%*pb", cpumask_pr_args(p->cpus_ptr));
5199 
5200 	if (SCX_HAS_OP(sch, dump_task)) {
5201 		ops_dump_init(s, "    ");
5202 		SCX_CALL_OP(sch, SCX_KF_REST, dump_task, NULL, dctx, p);
5203 		ops_dump_exit();
5204 	}
5205 
5206 #ifdef CONFIG_STACKTRACE
5207 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
5208 #endif
5209 	if (bt_len) {
5210 		dump_newline(s);
5211 		dump_stack_trace(s, "    ", bt, bt_len);
5212 	}
5213 }
5214 
5215 static void scx_dump_state(struct scx_exit_info *ei, size_t dump_len)
5216 {
5217 	static DEFINE_SPINLOCK(dump_lock);
5218 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
5219 	struct scx_sched *sch = scx_root;
5220 	struct scx_dump_ctx dctx = {
5221 		.kind = ei->kind,
5222 		.exit_code = ei->exit_code,
5223 		.reason = ei->reason,
5224 		.at_ns = ktime_get_ns(),
5225 		.at_jiffies = jiffies,
5226 	};
5227 	struct seq_buf s;
5228 	struct scx_event_stats events;
5229 	unsigned long flags;
5230 	char *buf;
5231 	int cpu;
5232 
5233 	spin_lock_irqsave(&dump_lock, flags);
5234 
5235 	seq_buf_init(&s, ei->dump, dump_len);
5236 
5237 	if (ei->kind == SCX_EXIT_NONE) {
5238 		dump_line(&s, "Debug dump triggered by %s", ei->reason);
5239 	} else {
5240 		dump_line(&s, "%s[%d] triggered exit kind %d:",
5241 			  current->comm, current->pid, ei->kind);
5242 		dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
5243 		dump_newline(&s);
5244 		dump_line(&s, "Backtrace:");
5245 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
5246 	}
5247 
5248 	if (SCX_HAS_OP(sch, dump)) {
5249 		ops_dump_init(&s, "");
5250 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, dump, NULL, &dctx);
5251 		ops_dump_exit();
5252 	}
5253 
5254 	dump_newline(&s);
5255 	dump_line(&s, "CPU states");
5256 	dump_line(&s, "----------");
5257 
5258 	for_each_possible_cpu(cpu) {
5259 		struct rq *rq = cpu_rq(cpu);
5260 		struct rq_flags rf;
5261 		struct task_struct *p;
5262 		struct seq_buf ns;
5263 		size_t avail, used;
5264 		bool idle;
5265 
5266 		rq_lock(rq, &rf);
5267 
5268 		idle = list_empty(&rq->scx.runnable_list) &&
5269 			rq->curr->sched_class == &idle_sched_class;
5270 
5271 		if (idle && !SCX_HAS_OP(sch, dump_cpu))
5272 			goto next;
5273 
5274 		/*
5275 		 * We don't yet know whether ops.dump_cpu() will produce output
5276 		 * and we may want to skip the default CPU dump if it doesn't.
5277 		 * Use a nested seq_buf to generate the standard dump so that we
5278 		 * can decide whether to commit later.
5279 		 */
5280 		avail = seq_buf_get_buf(&s, &buf);
5281 		seq_buf_init(&ns, buf, avail);
5282 
5283 		dump_newline(&ns);
5284 		dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu pnt_seq=%lu",
5285 			  cpu, rq->scx.nr_running, rq->scx.flags,
5286 			  rq->scx.cpu_released, rq->scx.ops_qseq,
5287 			  rq->scx.pnt_seq);
5288 		dump_line(&ns, "          curr=%s[%d] class=%ps",
5289 			  rq->curr->comm, rq->curr->pid,
5290 			  rq->curr->sched_class);
5291 		if (!cpumask_empty(rq->scx.cpus_to_kick))
5292 			dump_line(&ns, "  cpus_to_kick   : %*pb",
5293 				  cpumask_pr_args(rq->scx.cpus_to_kick));
5294 		if (!cpumask_empty(rq->scx.cpus_to_kick_if_idle))
5295 			dump_line(&ns, "  idle_to_kick   : %*pb",
5296 				  cpumask_pr_args(rq->scx.cpus_to_kick_if_idle));
5297 		if (!cpumask_empty(rq->scx.cpus_to_preempt))
5298 			dump_line(&ns, "  cpus_to_preempt: %*pb",
5299 				  cpumask_pr_args(rq->scx.cpus_to_preempt));
5300 		if (!cpumask_empty(rq->scx.cpus_to_wait))
5301 			dump_line(&ns, "  cpus_to_wait   : %*pb",
5302 				  cpumask_pr_args(rq->scx.cpus_to_wait));
5303 
5304 		used = seq_buf_used(&ns);
5305 		if (SCX_HAS_OP(sch, dump_cpu)) {
5306 			ops_dump_init(&ns, "  ");
5307 			SCX_CALL_OP(sch, SCX_KF_REST, dump_cpu, NULL,
5308 				    &dctx, cpu, idle);
5309 			ops_dump_exit();
5310 		}
5311 
5312 		/*
5313 		 * If idle && nothing generated by ops.dump_cpu(), there's
5314 		 * nothing interesting. Skip.
5315 		 */
5316 		if (idle && used == seq_buf_used(&ns))
5317 			goto next;
5318 
5319 		/*
5320 		 * $s may already have overflowed when $ns was created. If so,
5321 		 * calling commit on it will trigger BUG.
5322 		 */
5323 		if (avail) {
5324 			seq_buf_commit(&s, seq_buf_used(&ns));
5325 			if (seq_buf_has_overflowed(&ns))
5326 				seq_buf_set_overflow(&s);
5327 		}
5328 
5329 		if (rq->curr->sched_class == &ext_sched_class)
5330 			scx_dump_task(&s, &dctx, rq->curr, '*');
5331 
5332 		list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
5333 			scx_dump_task(&s, &dctx, p, ' ');
5334 	next:
5335 		rq_unlock(rq, &rf);
5336 	}
5337 
5338 	dump_newline(&s);
5339 	dump_line(&s, "Event counters");
5340 	dump_line(&s, "--------------");
5341 
5342 	scx_read_events(sch, &events);
5343 	scx_dump_event(s, &events, SCX_EV_SELECT_CPU_FALLBACK);
5344 	scx_dump_event(s, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
5345 	scx_dump_event(s, &events, SCX_EV_DISPATCH_KEEP_LAST);
5346 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_EXITING);
5347 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
5348 	scx_dump_event(s, &events, SCX_EV_REFILL_SLICE_DFL);
5349 	scx_dump_event(s, &events, SCX_EV_BYPASS_DURATION);
5350 	scx_dump_event(s, &events, SCX_EV_BYPASS_DISPATCH);
5351 	scx_dump_event(s, &events, SCX_EV_BYPASS_ACTIVATE);
5352 
5353 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
5354 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
5355 		       trunc_marker, sizeof(trunc_marker));
5356 
5357 	spin_unlock_irqrestore(&dump_lock, flags);
5358 }
5359 
5360 static void scx_error_irq_workfn(struct irq_work *irq_work)
5361 {
5362 	struct scx_sched *sch = container_of(irq_work, struct scx_sched, error_irq_work);
5363 	struct scx_exit_info *ei = sch->exit_info;
5364 
5365 	if (ei->kind >= SCX_EXIT_ERROR)
5366 		scx_dump_state(ei, sch->ops.exit_dump_len);
5367 
5368 	kthread_queue_work(sch->helper, &sch->disable_work);
5369 }
5370 
5371 static void scx_vexit(struct scx_sched *sch,
5372 		      enum scx_exit_kind kind, s64 exit_code,
5373 		      const char *fmt, va_list args)
5374 {
5375 	struct scx_exit_info *ei = sch->exit_info;
5376 	int none = SCX_EXIT_NONE;
5377 
5378 	if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind))
5379 		return;
5380 
5381 	ei->exit_code = exit_code;
5382 #ifdef CONFIG_STACKTRACE
5383 	if (kind >= SCX_EXIT_ERROR)
5384 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
5385 #endif
5386 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
5387 
5388 	/*
5389 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
5390 	 * in scx_disable_workfn().
5391 	 */
5392 	ei->kind = kind;
5393 	ei->reason = scx_exit_reason(ei->kind);
5394 
5395 	irq_work_queue(&sch->error_irq_work);
5396 }
5397 
5398 static struct scx_sched *scx_alloc_and_add_sched(struct sched_ext_ops *ops)
5399 {
5400 	struct scx_sched *sch;
5401 	int node, ret;
5402 
5403 	sch = kzalloc(sizeof(*sch), GFP_KERNEL);
5404 	if (!sch)
5405 		return ERR_PTR(-ENOMEM);
5406 
5407 	sch->exit_info = alloc_exit_info(ops->exit_dump_len);
5408 	if (!sch->exit_info) {
5409 		ret = -ENOMEM;
5410 		goto err_free_sch;
5411 	}
5412 
5413 	ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params);
5414 	if (ret < 0)
5415 		goto err_free_ei;
5416 
5417 	sch->global_dsqs = kcalloc(nr_node_ids, sizeof(sch->global_dsqs[0]),
5418 				   GFP_KERNEL);
5419 	if (!sch->global_dsqs) {
5420 		ret = -ENOMEM;
5421 		goto err_free_hash;
5422 	}
5423 
5424 	for_each_node_state(node, N_POSSIBLE) {
5425 		struct scx_dispatch_q *dsq;
5426 
5427 		dsq = kzalloc_node(sizeof(*dsq), GFP_KERNEL, node);
5428 		if (!dsq) {
5429 			ret = -ENOMEM;
5430 			goto err_free_gdsqs;
5431 		}
5432 
5433 		init_dsq(dsq, SCX_DSQ_GLOBAL);
5434 		sch->global_dsqs[node] = dsq;
5435 	}
5436 
5437 	sch->event_stats_cpu = alloc_percpu(struct scx_event_stats);
5438 	if (!sch->event_stats_cpu)
5439 		goto err_free_gdsqs;
5440 
5441 	sch->helper = kthread_run_worker(0, "sched_ext_helper");
5442 	if (!sch->helper)
5443 		goto err_free_event_stats;
5444 	sched_set_fifo(sch->helper->task);
5445 
5446 	atomic_set(&sch->exit_kind, SCX_EXIT_NONE);
5447 	init_irq_work(&sch->error_irq_work, scx_error_irq_workfn);
5448 	kthread_init_work(&sch->disable_work, scx_disable_workfn);
5449 	sch->ops = *ops;
5450 	ops->priv = sch;
5451 
5452 	sch->kobj.kset = scx_kset;
5453 	ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root");
5454 	if (ret < 0)
5455 		goto err_stop_helper;
5456 
5457 	return sch;
5458 
5459 err_stop_helper:
5460 	kthread_stop(sch->helper->task);
5461 err_free_event_stats:
5462 	free_percpu(sch->event_stats_cpu);
5463 err_free_gdsqs:
5464 	for_each_node_state(node, N_POSSIBLE)
5465 		kfree(sch->global_dsqs[node]);
5466 	kfree(sch->global_dsqs);
5467 err_free_hash:
5468 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
5469 err_free_ei:
5470 	free_exit_info(sch->exit_info);
5471 err_free_sch:
5472 	kfree(sch);
5473 	return ERR_PTR(ret);
5474 }
5475 
5476 static void check_hotplug_seq(struct scx_sched *sch,
5477 			      const struct sched_ext_ops *ops)
5478 {
5479 	unsigned long long global_hotplug_seq;
5480 
5481 	/*
5482 	 * If a hotplug event has occurred between when a scheduler was
5483 	 * initialized, and when we were able to attach, exit and notify user
5484 	 * space about it.
5485 	 */
5486 	if (ops->hotplug_seq) {
5487 		global_hotplug_seq = atomic_long_read(&scx_hotplug_seq);
5488 		if (ops->hotplug_seq != global_hotplug_seq) {
5489 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
5490 				 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
5491 				 "expected hotplug seq %llu did not match actual %llu",
5492 				 ops->hotplug_seq, global_hotplug_seq);
5493 		}
5494 	}
5495 }
5496 
5497 static int validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
5498 {
5499 	/*
5500 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
5501 	 * ops.enqueue() callback isn't implemented.
5502 	 */
5503 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
5504 		scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
5505 		return -EINVAL;
5506 	}
5507 
5508 	/*
5509 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle
5510 	 * selection policy to be enabled.
5511 	 */
5512 	if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) &&
5513 	    (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) {
5514 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled");
5515 		return -EINVAL;
5516 	}
5517 
5518 	if (ops->flags & SCX_OPS_HAS_CGROUP_WEIGHT)
5519 		pr_warn("SCX_OPS_HAS_CGROUP_WEIGHT is deprecated and a noop\n");
5520 
5521 	return 0;
5522 }
5523 
5524 static int scx_enable(struct sched_ext_ops *ops, struct bpf_link *link)
5525 {
5526 	struct scx_sched *sch;
5527 	struct scx_task_iter sti;
5528 	struct task_struct *p;
5529 	unsigned long timeout;
5530 	int i, cpu, ret;
5531 
5532 	if (!cpumask_equal(housekeeping_cpumask(HK_TYPE_DOMAIN),
5533 			   cpu_possible_mask)) {
5534 		pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n");
5535 		return -EINVAL;
5536 	}
5537 
5538 	mutex_lock(&scx_enable_mutex);
5539 
5540 	if (scx_enable_state() != SCX_DISABLED) {
5541 		ret = -EBUSY;
5542 		goto err_unlock;
5543 	}
5544 
5545 	sch = scx_alloc_and_add_sched(ops);
5546 	if (IS_ERR(sch)) {
5547 		ret = PTR_ERR(sch);
5548 		goto err_unlock;
5549 	}
5550 
5551 	/*
5552 	 * Transition to ENABLING and clear exit info to arm the disable path.
5553 	 * Failure triggers full disabling from here on.
5554 	 */
5555 	WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED);
5556 	WARN_ON_ONCE(scx_root);
5557 
5558 	atomic_long_set(&scx_nr_rejected, 0);
5559 
5560 	for_each_possible_cpu(cpu)
5561 		cpu_rq(cpu)->scx.cpuperf_target = SCX_CPUPERF_ONE;
5562 
5563 	/*
5564 	 * Keep CPUs stable during enable so that the BPF scheduler can track
5565 	 * online CPUs by watching ->on/offline_cpu() after ->init().
5566 	 */
5567 	cpus_read_lock();
5568 
5569 	/*
5570 	 * Make the scheduler instance visible. Must be inside cpus_read_lock().
5571 	 * See handle_hotplug().
5572 	 */
5573 	rcu_assign_pointer(scx_root, sch);
5574 
5575 	scx_idle_enable(ops);
5576 
5577 	if (sch->ops.init) {
5578 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init, NULL);
5579 		if (ret) {
5580 			ret = ops_sanitize_err(sch, "init", ret);
5581 			cpus_read_unlock();
5582 			scx_error(sch, "ops.init() failed (%d)", ret);
5583 			goto err_disable;
5584 		}
5585 	}
5586 
5587 	for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++)
5588 		if (((void (**)(void))ops)[i])
5589 			set_bit(i, sch->has_op);
5590 
5591 	check_hotplug_seq(sch, ops);
5592 	scx_idle_update_selcpu_topology(ops);
5593 
5594 	cpus_read_unlock();
5595 
5596 	ret = validate_ops(sch, ops);
5597 	if (ret)
5598 		goto err_disable;
5599 
5600 	WARN_ON_ONCE(scx_dsp_ctx);
5601 	scx_dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
5602 	scx_dsp_ctx = __alloc_percpu(struct_size_t(struct scx_dsp_ctx, buf,
5603 						   scx_dsp_max_batch),
5604 				     __alignof__(struct scx_dsp_ctx));
5605 	if (!scx_dsp_ctx) {
5606 		ret = -ENOMEM;
5607 		goto err_disable;
5608 	}
5609 
5610 	if (ops->timeout_ms)
5611 		timeout = msecs_to_jiffies(ops->timeout_ms);
5612 	else
5613 		timeout = SCX_WATCHDOG_MAX_TIMEOUT;
5614 
5615 	WRITE_ONCE(scx_watchdog_timeout, timeout);
5616 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
5617 	queue_delayed_work(system_unbound_wq, &scx_watchdog_work,
5618 			   scx_watchdog_timeout / 2);
5619 
5620 	/*
5621 	 * Once __scx_enabled is set, %current can be switched to SCX anytime.
5622 	 * This can lead to stalls as some BPF schedulers (e.g. userspace
5623 	 * scheduling) may not function correctly before all tasks are switched.
5624 	 * Init in bypass mode to guarantee forward progress.
5625 	 */
5626 	scx_bypass(true);
5627 
5628 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
5629 		if (((void (**)(void))ops)[i])
5630 			set_bit(i, sch->has_op);
5631 
5632 	if (sch->ops.cpu_acquire || sch->ops.cpu_release)
5633 		sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT;
5634 
5635 	/*
5636 	 * Lock out forks, cgroup on/offlining and moves before opening the
5637 	 * floodgate so that they don't wander into the operations prematurely.
5638 	 */
5639 	percpu_down_write(&scx_fork_rwsem);
5640 
5641 	WARN_ON_ONCE(scx_init_task_enabled);
5642 	scx_init_task_enabled = true;
5643 
5644 	/*
5645 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
5646 	 * preventing new tasks from being added. No need to exclude tasks
5647 	 * leaving as sched_ext_free() can handle both prepped and enabled
5648 	 * tasks. Prep all tasks first and then enable them with preemption
5649 	 * disabled.
5650 	 *
5651 	 * All cgroups should be initialized before scx_init_task() so that the
5652 	 * BPF scheduler can reliably track each task's cgroup membership from
5653 	 * scx_init_task(). Lock out cgroup on/offlining and task migrations
5654 	 * while tasks are being initialized so that scx_cgroup_can_attach()
5655 	 * never sees uninitialized tasks.
5656 	 */
5657 	scx_cgroup_lock();
5658 	ret = scx_cgroup_init(sch);
5659 	if (ret)
5660 		goto err_disable_unlock_all;
5661 
5662 	scx_task_iter_start(&sti);
5663 	while ((p = scx_task_iter_next_locked(&sti))) {
5664 		/*
5665 		 * @p may already be dead, have lost all its usages counts and
5666 		 * be waiting for RCU grace period before being freed. @p can't
5667 		 * be initialized for SCX in such cases and should be ignored.
5668 		 */
5669 		if (!tryget_task_struct(p))
5670 			continue;
5671 
5672 		scx_task_iter_unlock(&sti);
5673 
5674 		ret = scx_init_task(p, task_group(p), false);
5675 		if (ret) {
5676 			put_task_struct(p);
5677 			scx_task_iter_relock(&sti);
5678 			scx_task_iter_stop(&sti);
5679 			scx_error(sch, "ops.init_task() failed (%d) for %s[%d]",
5680 				  ret, p->comm, p->pid);
5681 			goto err_disable_unlock_all;
5682 		}
5683 
5684 		scx_set_task_state(p, SCX_TASK_READY);
5685 
5686 		put_task_struct(p);
5687 		scx_task_iter_relock(&sti);
5688 	}
5689 	scx_task_iter_stop(&sti);
5690 	scx_cgroup_unlock();
5691 	percpu_up_write(&scx_fork_rwsem);
5692 
5693 	/*
5694 	 * All tasks are READY. It's safe to turn on scx_enabled() and switch
5695 	 * all eligible tasks.
5696 	 */
5697 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
5698 	static_branch_enable(&__scx_enabled);
5699 
5700 	/*
5701 	 * We're fully committed and can't fail. The task READY -> ENABLED
5702 	 * transitions here are synchronized against sched_ext_free() through
5703 	 * scx_tasks_lock.
5704 	 */
5705 	percpu_down_write(&scx_fork_rwsem);
5706 	scx_task_iter_start(&sti);
5707 	while ((p = scx_task_iter_next_locked(&sti))) {
5708 		const struct sched_class *old_class = p->sched_class;
5709 		const struct sched_class *new_class =
5710 			__setscheduler_class(p->policy, p->prio);
5711 		struct sched_enq_and_set_ctx ctx;
5712 
5713 		if (old_class != new_class && p->se.sched_delayed)
5714 			dequeue_task(task_rq(p), p, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
5715 
5716 		sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
5717 
5718 		p->scx.slice = SCX_SLICE_DFL;
5719 		p->sched_class = new_class;
5720 		check_class_changing(task_rq(p), p, old_class);
5721 
5722 		sched_enq_and_set_task(&ctx);
5723 
5724 		check_class_changed(task_rq(p), p, old_class, p->prio);
5725 	}
5726 	scx_task_iter_stop(&sti);
5727 	percpu_up_write(&scx_fork_rwsem);
5728 
5729 	scx_bypass(false);
5730 
5731 	if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) {
5732 		WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE);
5733 		goto err_disable;
5734 	}
5735 
5736 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
5737 		static_branch_enable(&__scx_switched_all);
5738 
5739 	pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n",
5740 		sch->ops.name, scx_switched_all() ? "" : " (partial)");
5741 	kobject_uevent(&sch->kobj, KOBJ_ADD);
5742 	mutex_unlock(&scx_enable_mutex);
5743 
5744 	atomic_long_inc(&scx_enable_seq);
5745 
5746 	return 0;
5747 
5748 err_unlock:
5749 	mutex_unlock(&scx_enable_mutex);
5750 	return ret;
5751 
5752 err_disable_unlock_all:
5753 	scx_cgroup_unlock();
5754 	percpu_up_write(&scx_fork_rwsem);
5755 	scx_bypass(false);
5756 err_disable:
5757 	mutex_unlock(&scx_enable_mutex);
5758 	/*
5759 	 * Returning an error code here would not pass all the error information
5760 	 * to userspace. Record errno using scx_error() for cases scx_error()
5761 	 * wasn't already invoked and exit indicating success so that the error
5762 	 * is notified through ops.exit() with all the details.
5763 	 *
5764 	 * Flush scx_disable_work to ensure that error is reported before init
5765 	 * completion. sch's base reference will be put by bpf_scx_unreg().
5766 	 */
5767 	scx_error(sch, "scx_enable() failed (%d)", ret);
5768 	kthread_flush_work(&sch->disable_work);
5769 	return 0;
5770 }
5771 
5772 
5773 /********************************************************************************
5774  * bpf_struct_ops plumbing.
5775  */
5776 #include <linux/bpf_verifier.h>
5777 #include <linux/bpf.h>
5778 #include <linux/btf.h>
5779 
5780 static const struct btf_type *task_struct_type;
5781 
5782 static bool bpf_scx_is_valid_access(int off, int size,
5783 				    enum bpf_access_type type,
5784 				    const struct bpf_prog *prog,
5785 				    struct bpf_insn_access_aux *info)
5786 {
5787 	if (type != BPF_READ)
5788 		return false;
5789 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
5790 		return false;
5791 	if (off % size != 0)
5792 		return false;
5793 
5794 	return btf_ctx_access(off, size, type, prog, info);
5795 }
5796 
5797 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
5798 				     const struct bpf_reg_state *reg, int off,
5799 				     int size)
5800 {
5801 	const struct btf_type *t;
5802 
5803 	t = btf_type_by_id(reg->btf, reg->btf_id);
5804 	if (t == task_struct_type) {
5805 		if (off >= offsetof(struct task_struct, scx.slice) &&
5806 		    off + size <= offsetofend(struct task_struct, scx.slice))
5807 			return SCALAR_VALUE;
5808 		if (off >= offsetof(struct task_struct, scx.dsq_vtime) &&
5809 		    off + size <= offsetofend(struct task_struct, scx.dsq_vtime))
5810 			return SCALAR_VALUE;
5811 		if (off >= offsetof(struct task_struct, scx.disallow) &&
5812 		    off + size <= offsetofend(struct task_struct, scx.disallow))
5813 			return SCALAR_VALUE;
5814 	}
5815 
5816 	return -EACCES;
5817 }
5818 
5819 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
5820 	.get_func_proto = bpf_base_func_proto,
5821 	.is_valid_access = bpf_scx_is_valid_access,
5822 	.btf_struct_access = bpf_scx_btf_struct_access,
5823 };
5824 
5825 static int bpf_scx_init_member(const struct btf_type *t,
5826 			       const struct btf_member *member,
5827 			       void *kdata, const void *udata)
5828 {
5829 	const struct sched_ext_ops *uops = udata;
5830 	struct sched_ext_ops *ops = kdata;
5831 	u32 moff = __btf_member_bit_offset(t, member) / 8;
5832 	int ret;
5833 
5834 	switch (moff) {
5835 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
5836 		if (*(u32 *)(udata + moff) > INT_MAX)
5837 			return -E2BIG;
5838 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
5839 		return 1;
5840 	case offsetof(struct sched_ext_ops, flags):
5841 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
5842 			return -EINVAL;
5843 		ops->flags = *(u64 *)(udata + moff);
5844 		return 1;
5845 	case offsetof(struct sched_ext_ops, name):
5846 		ret = bpf_obj_name_cpy(ops->name, uops->name,
5847 				       sizeof(ops->name));
5848 		if (ret < 0)
5849 			return ret;
5850 		if (ret == 0)
5851 			return -EINVAL;
5852 		return 1;
5853 	case offsetof(struct sched_ext_ops, timeout_ms):
5854 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
5855 		    SCX_WATCHDOG_MAX_TIMEOUT)
5856 			return -E2BIG;
5857 		ops->timeout_ms = *(u32 *)(udata + moff);
5858 		return 1;
5859 	case offsetof(struct sched_ext_ops, exit_dump_len):
5860 		ops->exit_dump_len =
5861 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
5862 		return 1;
5863 	case offsetof(struct sched_ext_ops, hotplug_seq):
5864 		ops->hotplug_seq = *(u64 *)(udata + moff);
5865 		return 1;
5866 	}
5867 
5868 	return 0;
5869 }
5870 
5871 static int bpf_scx_check_member(const struct btf_type *t,
5872 				const struct btf_member *member,
5873 				const struct bpf_prog *prog)
5874 {
5875 	u32 moff = __btf_member_bit_offset(t, member) / 8;
5876 
5877 	switch (moff) {
5878 	case offsetof(struct sched_ext_ops, init_task):
5879 #ifdef CONFIG_EXT_GROUP_SCHED
5880 	case offsetof(struct sched_ext_ops, cgroup_init):
5881 	case offsetof(struct sched_ext_ops, cgroup_exit):
5882 	case offsetof(struct sched_ext_ops, cgroup_prep_move):
5883 #endif
5884 	case offsetof(struct sched_ext_ops, cpu_online):
5885 	case offsetof(struct sched_ext_ops, cpu_offline):
5886 	case offsetof(struct sched_ext_ops, init):
5887 	case offsetof(struct sched_ext_ops, exit):
5888 		break;
5889 	default:
5890 		if (prog->sleepable)
5891 			return -EINVAL;
5892 	}
5893 
5894 	return 0;
5895 }
5896 
5897 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
5898 {
5899 	return scx_enable(kdata, link);
5900 }
5901 
5902 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
5903 {
5904 	struct sched_ext_ops *ops = kdata;
5905 	struct scx_sched *sch = ops->priv;
5906 
5907 	scx_disable(SCX_EXIT_UNREG);
5908 	kthread_flush_work(&sch->disable_work);
5909 	kobject_put(&sch->kobj);
5910 }
5911 
5912 static int bpf_scx_init(struct btf *btf)
5913 {
5914 	task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]);
5915 
5916 	return 0;
5917 }
5918 
5919 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
5920 {
5921 	/*
5922 	 * sched_ext does not support updating the actively-loaded BPF
5923 	 * scheduler, as registering a BPF scheduler can always fail if the
5924 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
5925 	 * etc. Similarly, we can always race with unregistration happening
5926 	 * elsewhere, such as with sysrq.
5927 	 */
5928 	return -EOPNOTSUPP;
5929 }
5930 
5931 static int bpf_scx_validate(void *kdata)
5932 {
5933 	return 0;
5934 }
5935 
5936 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
5937 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
5938 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
5939 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {}
5940 static void sched_ext_ops__tick(struct task_struct *p) {}
5941 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {}
5942 static void sched_ext_ops__running(struct task_struct *p) {}
5943 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {}
5944 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {}
5945 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; }
5946 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; }
5947 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {}
5948 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {}
5949 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {}
5950 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {}
5951 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {}
5952 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
5953 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {}
5954 static void sched_ext_ops__enable(struct task_struct *p) {}
5955 static void sched_ext_ops__disable(struct task_struct *p) {}
5956 #ifdef CONFIG_EXT_GROUP_SCHED
5957 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; }
5958 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {}
5959 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; }
5960 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
5961 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
5962 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
5963 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
5964 #endif
5965 static void sched_ext_ops__cpu_online(s32 cpu) {}
5966 static void sched_ext_ops__cpu_offline(s32 cpu) {}
5967 static s32 sched_ext_ops__init(void) { return -EINVAL; }
5968 static void sched_ext_ops__exit(struct scx_exit_info *info) {}
5969 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {}
5970 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {}
5971 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {}
5972 
5973 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
5974 	.select_cpu		= sched_ext_ops__select_cpu,
5975 	.enqueue		= sched_ext_ops__enqueue,
5976 	.dequeue		= sched_ext_ops__dequeue,
5977 	.dispatch		= sched_ext_ops__dispatch,
5978 	.tick			= sched_ext_ops__tick,
5979 	.runnable		= sched_ext_ops__runnable,
5980 	.running		= sched_ext_ops__running,
5981 	.stopping		= sched_ext_ops__stopping,
5982 	.quiescent		= sched_ext_ops__quiescent,
5983 	.yield			= sched_ext_ops__yield,
5984 	.core_sched_before	= sched_ext_ops__core_sched_before,
5985 	.set_weight		= sched_ext_ops__set_weight,
5986 	.set_cpumask		= sched_ext_ops__set_cpumask,
5987 	.update_idle		= sched_ext_ops__update_idle,
5988 	.cpu_acquire		= sched_ext_ops__cpu_acquire,
5989 	.cpu_release		= sched_ext_ops__cpu_release,
5990 	.init_task		= sched_ext_ops__init_task,
5991 	.exit_task		= sched_ext_ops__exit_task,
5992 	.enable			= sched_ext_ops__enable,
5993 	.disable		= sched_ext_ops__disable,
5994 #ifdef CONFIG_EXT_GROUP_SCHED
5995 	.cgroup_init		= sched_ext_ops__cgroup_init,
5996 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
5997 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
5998 	.cgroup_move		= sched_ext_ops__cgroup_move,
5999 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
6000 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
6001 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
6002 #endif
6003 	.cpu_online		= sched_ext_ops__cpu_online,
6004 	.cpu_offline		= sched_ext_ops__cpu_offline,
6005 	.init			= sched_ext_ops__init,
6006 	.exit			= sched_ext_ops__exit,
6007 	.dump			= sched_ext_ops__dump,
6008 	.dump_cpu		= sched_ext_ops__dump_cpu,
6009 	.dump_task		= sched_ext_ops__dump_task,
6010 };
6011 
6012 static struct bpf_struct_ops bpf_sched_ext_ops = {
6013 	.verifier_ops = &bpf_scx_verifier_ops,
6014 	.reg = bpf_scx_reg,
6015 	.unreg = bpf_scx_unreg,
6016 	.check_member = bpf_scx_check_member,
6017 	.init_member = bpf_scx_init_member,
6018 	.init = bpf_scx_init,
6019 	.update = bpf_scx_update,
6020 	.validate = bpf_scx_validate,
6021 	.name = "sched_ext_ops",
6022 	.owner = THIS_MODULE,
6023 	.cfi_stubs = &__bpf_ops_sched_ext_ops
6024 };
6025 
6026 
6027 /********************************************************************************
6028  * System integration and init.
6029  */
6030 
6031 static void sysrq_handle_sched_ext_reset(u8 key)
6032 {
6033 	scx_disable(SCX_EXIT_SYSRQ);
6034 }
6035 
6036 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
6037 	.handler	= sysrq_handle_sched_ext_reset,
6038 	.help_msg	= "reset-sched-ext(S)",
6039 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
6040 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
6041 };
6042 
6043 static void sysrq_handle_sched_ext_dump(u8 key)
6044 {
6045 	struct scx_exit_info ei = { .kind = SCX_EXIT_NONE, .reason = "SysRq-D" };
6046 
6047 	if (scx_enabled())
6048 		scx_dump_state(&ei, 0);
6049 }
6050 
6051 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
6052 	.handler	= sysrq_handle_sched_ext_dump,
6053 	.help_msg	= "dump-sched-ext(D)",
6054 	.action_msg	= "Trigger sched_ext debug dump",
6055 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
6056 };
6057 
6058 static bool can_skip_idle_kick(struct rq *rq)
6059 {
6060 	lockdep_assert_rq_held(rq);
6061 
6062 	/*
6063 	 * We can skip idle kicking if @rq is going to go through at least one
6064 	 * full SCX scheduling cycle before going idle. Just checking whether
6065 	 * curr is not idle is insufficient because we could be racing
6066 	 * balance_one() trying to pull the next task from a remote rq, which
6067 	 * may fail, and @rq may become idle afterwards.
6068 	 *
6069 	 * The race window is small and we don't and can't guarantee that @rq is
6070 	 * only kicked while idle anyway. Skip only when sure.
6071 	 */
6072 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_BALANCE);
6073 }
6074 
6075 static bool kick_one_cpu(s32 cpu, struct rq *this_rq, unsigned long *pseqs)
6076 {
6077 	struct rq *rq = cpu_rq(cpu);
6078 	struct scx_rq *this_scx = &this_rq->scx;
6079 	bool should_wait = false;
6080 	unsigned long flags;
6081 
6082 	raw_spin_rq_lock_irqsave(rq, flags);
6083 
6084 	/*
6085 	 * During CPU hotplug, a CPU may depend on kicking itself to make
6086 	 * forward progress. Allow kicking self regardless of online state.
6087 	 */
6088 	if (cpu_online(cpu) || cpu == cpu_of(this_rq)) {
6089 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_preempt)) {
6090 			if (rq->curr->sched_class == &ext_sched_class)
6091 				rq->curr->scx.slice = 0;
6092 			cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
6093 		}
6094 
6095 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_wait)) {
6096 			pseqs[cpu] = rq->scx.pnt_seq;
6097 			should_wait = true;
6098 		}
6099 
6100 		resched_curr(rq);
6101 	} else {
6102 		cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
6103 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
6104 	}
6105 
6106 	raw_spin_rq_unlock_irqrestore(rq, flags);
6107 
6108 	return should_wait;
6109 }
6110 
6111 static void kick_one_cpu_if_idle(s32 cpu, struct rq *this_rq)
6112 {
6113 	struct rq *rq = cpu_rq(cpu);
6114 	unsigned long flags;
6115 
6116 	raw_spin_rq_lock_irqsave(rq, flags);
6117 
6118 	if (!can_skip_idle_kick(rq) &&
6119 	    (cpu_online(cpu) || cpu == cpu_of(this_rq)))
6120 		resched_curr(rq);
6121 
6122 	raw_spin_rq_unlock_irqrestore(rq, flags);
6123 }
6124 
6125 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
6126 {
6127 	struct rq *this_rq = this_rq();
6128 	struct scx_rq *this_scx = &this_rq->scx;
6129 	unsigned long *pseqs = this_cpu_ptr(scx_kick_cpus_pnt_seqs);
6130 	bool should_wait = false;
6131 	s32 cpu;
6132 
6133 	for_each_cpu(cpu, this_scx->cpus_to_kick) {
6134 		should_wait |= kick_one_cpu(cpu, this_rq, pseqs);
6135 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick);
6136 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
6137 	}
6138 
6139 	for_each_cpu(cpu, this_scx->cpus_to_kick_if_idle) {
6140 		kick_one_cpu_if_idle(cpu, this_rq);
6141 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
6142 	}
6143 
6144 	if (!should_wait)
6145 		return;
6146 
6147 	for_each_cpu(cpu, this_scx->cpus_to_wait) {
6148 		unsigned long *wait_pnt_seq = &cpu_rq(cpu)->scx.pnt_seq;
6149 
6150 		if (cpu != cpu_of(this_rq)) {
6151 			/*
6152 			 * Pairs with smp_store_release() issued by this CPU in
6153 			 * switch_class() on the resched path.
6154 			 *
6155 			 * We busy-wait here to guarantee that no other task can
6156 			 * be scheduled on our core before the target CPU has
6157 			 * entered the resched path.
6158 			 */
6159 			while (smp_load_acquire(wait_pnt_seq) == pseqs[cpu])
6160 				cpu_relax();
6161 		}
6162 
6163 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
6164 	}
6165 }
6166 
6167 /**
6168  * print_scx_info - print out sched_ext scheduler state
6169  * @log_lvl: the log level to use when printing
6170  * @p: target task
6171  *
6172  * If a sched_ext scheduler is enabled, print the name and state of the
6173  * scheduler. If @p is on sched_ext, print further information about the task.
6174  *
6175  * This function can be safely called on any task as long as the task_struct
6176  * itself is accessible. While safe, this function isn't synchronized and may
6177  * print out mixups or garbages of limited length.
6178  */
6179 void print_scx_info(const char *log_lvl, struct task_struct *p)
6180 {
6181 	struct scx_sched *sch = scx_root;
6182 	enum scx_enable_state state = scx_enable_state();
6183 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
6184 	char runnable_at_buf[22] = "?";
6185 	struct sched_class *class;
6186 	unsigned long runnable_at;
6187 
6188 	if (state == SCX_DISABLED)
6189 		return;
6190 
6191 	/*
6192 	 * Carefully check if the task was running on sched_ext, and then
6193 	 * carefully copy the time it's been runnable, and its state.
6194 	 */
6195 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
6196 	    class != &ext_sched_class) {
6197 		printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name,
6198 		       scx_enable_state_str[state], all);
6199 		return;
6200 	}
6201 
6202 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
6203 				      sizeof(runnable_at)))
6204 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
6205 			  jiffies_delta_msecs(runnable_at, jiffies));
6206 
6207 	/* print everything onto one line to conserve console space */
6208 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
6209 	       log_lvl, sch->ops.name, scx_enable_state_str[state], all,
6210 	       runnable_at_buf);
6211 }
6212 
6213 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr)
6214 {
6215 	/*
6216 	 * SCX schedulers often have userspace components which are sometimes
6217 	 * involved in critial scheduling paths. PM operations involve freezing
6218 	 * userspace which can lead to scheduling misbehaviors including stalls.
6219 	 * Let's bypass while PM operations are in progress.
6220 	 */
6221 	switch (event) {
6222 	case PM_HIBERNATION_PREPARE:
6223 	case PM_SUSPEND_PREPARE:
6224 	case PM_RESTORE_PREPARE:
6225 		scx_bypass(true);
6226 		break;
6227 	case PM_POST_HIBERNATION:
6228 	case PM_POST_SUSPEND:
6229 	case PM_POST_RESTORE:
6230 		scx_bypass(false);
6231 		break;
6232 	}
6233 
6234 	return NOTIFY_OK;
6235 }
6236 
6237 static struct notifier_block scx_pm_notifier = {
6238 	.notifier_call = scx_pm_handler,
6239 };
6240 
6241 void __init init_sched_ext_class(void)
6242 {
6243 	s32 cpu, v;
6244 
6245 	/*
6246 	 * The following is to prevent the compiler from optimizing out the enum
6247 	 * definitions so that BPF scheduler implementations can use them
6248 	 * through the generated vmlinux.h.
6249 	 */
6250 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT |
6251 		   SCX_TG_ONLINE);
6252 
6253 	scx_idle_init_masks();
6254 
6255 	scx_kick_cpus_pnt_seqs =
6256 		__alloc_percpu(sizeof(scx_kick_cpus_pnt_seqs[0]) * nr_cpu_ids,
6257 			       __alignof__(scx_kick_cpus_pnt_seqs[0]));
6258 	BUG_ON(!scx_kick_cpus_pnt_seqs);
6259 
6260 	for_each_possible_cpu(cpu) {
6261 		struct rq *rq = cpu_rq(cpu);
6262 		int  n = cpu_to_node(cpu);
6263 
6264 		init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL);
6265 		INIT_LIST_HEAD(&rq->scx.runnable_list);
6266 		INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals);
6267 
6268 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick, GFP_KERNEL, n));
6269 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick_if_idle, GFP_KERNEL, n));
6270 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_preempt, GFP_KERNEL, n));
6271 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_wait, GFP_KERNEL, n));
6272 		init_irq_work(&rq->scx.deferred_irq_work, deferred_irq_workfn);
6273 		init_irq_work(&rq->scx.kick_cpus_irq_work, kick_cpus_irq_workfn);
6274 
6275 		if (cpu_online(cpu))
6276 			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
6277 	}
6278 
6279 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
6280 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
6281 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
6282 }
6283 
6284 
6285 /********************************************************************************
6286  * Helpers that can be called from the BPF scheduler.
6287  */
6288 static bool scx_dsq_insert_preamble(struct task_struct *p, u64 enq_flags)
6289 {
6290 	if (!scx_kf_allowed(SCX_KF_ENQUEUE | SCX_KF_DISPATCH))
6291 		return false;
6292 
6293 	lockdep_assert_irqs_disabled();
6294 
6295 	if (unlikely(!p)) {
6296 		scx_kf_error("called with NULL task");
6297 		return false;
6298 	}
6299 
6300 	if (unlikely(enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
6301 		scx_kf_error("invalid enq_flags 0x%llx", enq_flags);
6302 		return false;
6303 	}
6304 
6305 	return true;
6306 }
6307 
6308 static void scx_dsq_insert_commit(struct task_struct *p, u64 dsq_id,
6309 				  u64 enq_flags)
6310 {
6311 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
6312 	struct task_struct *ddsp_task;
6313 
6314 	ddsp_task = __this_cpu_read(direct_dispatch_task);
6315 	if (ddsp_task) {
6316 		mark_direct_dispatch(ddsp_task, p, dsq_id, enq_flags);
6317 		return;
6318 	}
6319 
6320 	if (unlikely(dspc->cursor >= scx_dsp_max_batch)) {
6321 		scx_kf_error("dispatch buffer overflow");
6322 		return;
6323 	}
6324 
6325 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
6326 		.task = p,
6327 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
6328 		.dsq_id = dsq_id,
6329 		.enq_flags = enq_flags,
6330 	};
6331 }
6332 
6333 __bpf_kfunc_start_defs();
6334 
6335 /**
6336  * scx_bpf_dsq_insert - Insert a task into the FIFO queue of a DSQ
6337  * @p: task_struct to insert
6338  * @dsq_id: DSQ to insert into
6339  * @slice: duration @p can run for in nsecs, 0 to keep the current value
6340  * @enq_flags: SCX_ENQ_*
6341  *
6342  * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to
6343  * call this function spuriously. Can be called from ops.enqueue(),
6344  * ops.select_cpu(), and ops.dispatch().
6345  *
6346  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
6347  * and @p must match the task being enqueued.
6348  *
6349  * When called from ops.select_cpu(), @enq_flags and @dsp_id are stored, and @p
6350  * will be directly inserted into the corresponding dispatch queue after
6351  * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be
6352  * inserted into the local DSQ of the CPU returned by ops.select_cpu().
6353  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
6354  * task is inserted.
6355  *
6356  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
6357  * and this function can be called upto ops.dispatch_max_batch times to insert
6358  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
6359  * remaining slots. scx_bpf_consume() flushes the batch and resets the counter.
6360  *
6361  * This function doesn't have any locking restrictions and may be called under
6362  * BPF locks (in the future when BPF introduces more flexible locking).
6363  *
6364  * @p is allowed to run for @slice. The scheduling path is triggered on slice
6365  * exhaustion. If zero, the current residual slice is maintained. If
6366  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
6367  * scx_bpf_kick_cpu() to trigger scheduling.
6368  */
6369 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id, u64 slice,
6370 				    u64 enq_flags)
6371 {
6372 	if (!scx_dsq_insert_preamble(p, enq_flags))
6373 		return;
6374 
6375 	if (slice)
6376 		p->scx.slice = slice;
6377 	else
6378 		p->scx.slice = p->scx.slice ?: 1;
6379 
6380 	scx_dsq_insert_commit(p, dsq_id, enq_flags);
6381 }
6382 
6383 /* for backward compatibility, will be removed in v6.15 */
6384 __bpf_kfunc void scx_bpf_dispatch(struct task_struct *p, u64 dsq_id, u64 slice,
6385 				  u64 enq_flags)
6386 {
6387 	printk_deferred_once(KERN_WARNING "sched_ext: scx_bpf_dispatch() renamed to scx_bpf_dsq_insert()");
6388 	scx_bpf_dsq_insert(p, dsq_id, slice, enq_flags);
6389 }
6390 
6391 /**
6392  * scx_bpf_dsq_insert_vtime - Insert a task into the vtime priority queue of a DSQ
6393  * @p: task_struct to insert
6394  * @dsq_id: DSQ to insert into
6395  * @slice: duration @p can run for in nsecs, 0 to keep the current value
6396  * @vtime: @p's ordering inside the vtime-sorted queue of the target DSQ
6397  * @enq_flags: SCX_ENQ_*
6398  *
6399  * Insert @p into the vtime priority queue of the DSQ identified by @dsq_id.
6400  * Tasks queued into the priority queue are ordered by @vtime. All other aspects
6401  * are identical to scx_bpf_dsq_insert().
6402  *
6403  * @vtime ordering is according to time_before64() which considers wrapping. A
6404  * numerically larger vtime may indicate an earlier position in the ordering and
6405  * vice-versa.
6406  *
6407  * A DSQ can only be used as a FIFO or priority queue at any given time and this
6408  * function must not be called on a DSQ which already has one or more FIFO tasks
6409  * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and
6410  * SCX_DSQ_GLOBAL) cannot be used as priority queues.
6411  */
6412 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id,
6413 					  u64 slice, u64 vtime, u64 enq_flags)
6414 {
6415 	if (!scx_dsq_insert_preamble(p, enq_flags))
6416 		return;
6417 
6418 	if (slice)
6419 		p->scx.slice = slice;
6420 	else
6421 		p->scx.slice = p->scx.slice ?: 1;
6422 
6423 	p->scx.dsq_vtime = vtime;
6424 
6425 	scx_dsq_insert_commit(p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
6426 }
6427 
6428 /* for backward compatibility, will be removed in v6.15 */
6429 __bpf_kfunc void scx_bpf_dispatch_vtime(struct task_struct *p, u64 dsq_id,
6430 					u64 slice, u64 vtime, u64 enq_flags)
6431 {
6432 	printk_deferred_once(KERN_WARNING "sched_ext: scx_bpf_dispatch_vtime() renamed to scx_bpf_dsq_insert_vtime()");
6433 	scx_bpf_dsq_insert_vtime(p, dsq_id, slice, vtime, enq_flags);
6434 }
6435 
6436 __bpf_kfunc_end_defs();
6437 
6438 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
6439 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_RCU)
6440 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU)
6441 BTF_ID_FLAGS(func, scx_bpf_dispatch, KF_RCU)
6442 BTF_ID_FLAGS(func, scx_bpf_dispatch_vtime, KF_RCU)
6443 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
6444 
6445 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
6446 	.owner			= THIS_MODULE,
6447 	.set			= &scx_kfunc_ids_enqueue_dispatch,
6448 };
6449 
6450 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit,
6451 			 struct task_struct *p, u64 dsq_id, u64 enq_flags)
6452 {
6453 	struct scx_sched *sch = scx_root;
6454 	struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq;
6455 	struct rq *this_rq, *src_rq, *locked_rq;
6456 	bool dispatched = false;
6457 	bool in_balance;
6458 	unsigned long flags;
6459 
6460 	if (!scx_kf_allowed_if_unlocked() && !scx_kf_allowed(SCX_KF_DISPATCH))
6461 		return false;
6462 
6463 	/*
6464 	 * Can be called from either ops.dispatch() locking this_rq() or any
6465 	 * context where no rq lock is held. If latter, lock @p's task_rq which
6466 	 * we'll likely need anyway.
6467 	 */
6468 	src_rq = task_rq(p);
6469 
6470 	local_irq_save(flags);
6471 	this_rq = this_rq();
6472 	in_balance = this_rq->scx.flags & SCX_RQ_IN_BALANCE;
6473 
6474 	if (in_balance) {
6475 		if (this_rq != src_rq) {
6476 			raw_spin_rq_unlock(this_rq);
6477 			raw_spin_rq_lock(src_rq);
6478 		}
6479 	} else {
6480 		raw_spin_rq_lock(src_rq);
6481 	}
6482 
6483 	/*
6484 	 * If the BPF scheduler keeps calling this function repeatedly, it can
6485 	 * cause similar live-lock conditions as consume_dispatch_q(). Insert a
6486 	 * breather if necessary.
6487 	 */
6488 	scx_breather(src_rq);
6489 
6490 	locked_rq = src_rq;
6491 	raw_spin_lock(&src_dsq->lock);
6492 
6493 	/*
6494 	 * Did someone else get to it? @p could have already left $src_dsq, got
6495 	 * re-enqueud, or be in the process of being consumed by someone else.
6496 	 */
6497 	if (unlikely(p->scx.dsq != src_dsq ||
6498 		     u32_before(kit->cursor.priv, p->scx.dsq_seq) ||
6499 		     p->scx.holding_cpu >= 0) ||
6500 	    WARN_ON_ONCE(src_rq != task_rq(p))) {
6501 		raw_spin_unlock(&src_dsq->lock);
6502 		goto out;
6503 	}
6504 
6505 	/* @p is still on $src_dsq and stable, determine the destination */
6506 	dst_dsq = find_dsq_for_dispatch(sch, this_rq, dsq_id, p);
6507 
6508 	/*
6509 	 * Apply vtime and slice updates before moving so that the new time is
6510 	 * visible before inserting into $dst_dsq. @p is still on $src_dsq but
6511 	 * this is safe as we're locking it.
6512 	 */
6513 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME)
6514 		p->scx.dsq_vtime = kit->vtime;
6515 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE)
6516 		p->scx.slice = kit->slice;
6517 
6518 	/* execute move */
6519 	locked_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq);
6520 	dispatched = true;
6521 out:
6522 	if (in_balance) {
6523 		if (this_rq != locked_rq) {
6524 			raw_spin_rq_unlock(locked_rq);
6525 			raw_spin_rq_lock(this_rq);
6526 		}
6527 	} else {
6528 		raw_spin_rq_unlock_irqrestore(locked_rq, flags);
6529 	}
6530 
6531 	kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE |
6532 			       __SCX_DSQ_ITER_HAS_VTIME);
6533 	return dispatched;
6534 }
6535 
6536 __bpf_kfunc_start_defs();
6537 
6538 /**
6539  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
6540  *
6541  * Can only be called from ops.dispatch().
6542  */
6543 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(void)
6544 {
6545 	if (!scx_kf_allowed(SCX_KF_DISPATCH))
6546 		return 0;
6547 
6548 	return scx_dsp_max_batch - __this_cpu_read(scx_dsp_ctx->cursor);
6549 }
6550 
6551 /**
6552  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
6553  *
6554  * Cancel the latest dispatch. Can be called multiple times to cancel further
6555  * dispatches. Can only be called from ops.dispatch().
6556  */
6557 __bpf_kfunc void scx_bpf_dispatch_cancel(void)
6558 {
6559 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
6560 
6561 	if (!scx_kf_allowed(SCX_KF_DISPATCH))
6562 		return;
6563 
6564 	if (dspc->cursor > 0)
6565 		dspc->cursor--;
6566 	else
6567 		scx_kf_error("dispatch buffer underflow");
6568 }
6569 
6570 /**
6571  * scx_bpf_dsq_move_to_local - move a task from a DSQ to the current CPU's local DSQ
6572  * @dsq_id: DSQ to move task from
6573  *
6574  * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's
6575  * local DSQ for execution. Can only be called from ops.dispatch().
6576  *
6577  * This function flushes the in-flight dispatches from scx_bpf_dsq_insert()
6578  * before trying to move from the specified DSQ. It may also grab rq locks and
6579  * thus can't be called under any BPF locks.
6580  *
6581  * Returns %true if a task has been moved, %false if there isn't any task to
6582  * move.
6583  */
6584 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id)
6585 {
6586 	struct scx_sched *sch = scx_root;
6587 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
6588 	struct scx_dispatch_q *dsq;
6589 
6590 	if (!scx_kf_allowed(SCX_KF_DISPATCH))
6591 		return false;
6592 
6593 	flush_dispatch_buf(sch, dspc->rq);
6594 
6595 	dsq = find_user_dsq(sch, dsq_id);
6596 	if (unlikely(!dsq)) {
6597 		scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id);
6598 		return false;
6599 	}
6600 
6601 	if (consume_dispatch_q(sch, dspc->rq, dsq)) {
6602 		/*
6603 		 * A successfully consumed task can be dequeued before it starts
6604 		 * running while the CPU is trying to migrate other dispatched
6605 		 * tasks. Bump nr_tasks to tell balance_scx() to retry on empty
6606 		 * local DSQ.
6607 		 */
6608 		dspc->nr_tasks++;
6609 		return true;
6610 	} else {
6611 		return false;
6612 	}
6613 }
6614 
6615 /* for backward compatibility, will be removed in v6.15 */
6616 __bpf_kfunc bool scx_bpf_consume(u64 dsq_id)
6617 {
6618 	printk_deferred_once(KERN_WARNING "sched_ext: scx_bpf_consume() renamed to scx_bpf_dsq_move_to_local()");
6619 	return scx_bpf_dsq_move_to_local(dsq_id);
6620 }
6621 
6622 /**
6623  * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs
6624  * @it__iter: DSQ iterator in progress
6625  * @slice: duration the moved task can run for in nsecs
6626  *
6627  * Override the slice of the next task that will be moved from @it__iter using
6628  * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous
6629  * slice duration is kept.
6630  */
6631 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter,
6632 					    u64 slice)
6633 {
6634 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
6635 
6636 	kit->slice = slice;
6637 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE;
6638 }
6639 
6640 /* for backward compatibility, will be removed in v6.15 */
6641 __bpf_kfunc void scx_bpf_dispatch_from_dsq_set_slice(
6642 			struct bpf_iter_scx_dsq *it__iter, u64 slice)
6643 {
6644 	printk_deferred_once(KERN_WARNING "sched_ext: scx_bpf_dispatch_from_dsq_set_slice() renamed to scx_bpf_dsq_move_set_slice()");
6645 	scx_bpf_dsq_move_set_slice(it__iter, slice);
6646 }
6647 
6648 /**
6649  * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs
6650  * @it__iter: DSQ iterator in progress
6651  * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ
6652  *
6653  * Override the vtime of the next task that will be moved from @it__iter using
6654  * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice
6655  * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the
6656  * override is ignored and cleared.
6657  */
6658 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter,
6659 					    u64 vtime)
6660 {
6661 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
6662 
6663 	kit->vtime = vtime;
6664 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME;
6665 }
6666 
6667 /* for backward compatibility, will be removed in v6.15 */
6668 __bpf_kfunc void scx_bpf_dispatch_from_dsq_set_vtime(
6669 			struct bpf_iter_scx_dsq *it__iter, u64 vtime)
6670 {
6671 	printk_deferred_once(KERN_WARNING "sched_ext: scx_bpf_dispatch_from_dsq_set_vtime() renamed to scx_bpf_dsq_move_set_vtime()");
6672 	scx_bpf_dsq_move_set_vtime(it__iter, vtime);
6673 }
6674 
6675 /**
6676  * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ
6677  * @it__iter: DSQ iterator in progress
6678  * @p: task to transfer
6679  * @dsq_id: DSQ to move @p to
6680  * @enq_flags: SCX_ENQ_*
6681  *
6682  * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ
6683  * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can
6684  * be the destination.
6685  *
6686  * For the transfer to be successful, @p must still be on the DSQ and have been
6687  * queued before the DSQ iteration started. This function doesn't care whether
6688  * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have
6689  * been queued before the iteration started.
6690  *
6691  * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update.
6692  *
6693  * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq
6694  * lock (e.g. BPF timers or SYSCALL programs).
6695  *
6696  * Returns %true if @p has been consumed, %false if @p had already been consumed
6697  * or dequeued.
6698  */
6699 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter,
6700 				  struct task_struct *p, u64 dsq_id,
6701 				  u64 enq_flags)
6702 {
6703 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
6704 			    p, dsq_id, enq_flags);
6705 }
6706 
6707 /* for backward compatibility, will be removed in v6.15 */
6708 __bpf_kfunc bool scx_bpf_dispatch_from_dsq(struct bpf_iter_scx_dsq *it__iter,
6709 					   struct task_struct *p, u64 dsq_id,
6710 					   u64 enq_flags)
6711 {
6712 	printk_deferred_once(KERN_WARNING "sched_ext: scx_bpf_dispatch_from_dsq() renamed to scx_bpf_dsq_move()");
6713 	return scx_bpf_dsq_move(it__iter, p, dsq_id, enq_flags);
6714 }
6715 
6716 /**
6717  * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ
6718  * @it__iter: DSQ iterator in progress
6719  * @p: task to transfer
6720  * @dsq_id: DSQ to move @p to
6721  * @enq_flags: SCX_ENQ_*
6722  *
6723  * Transfer @p which is on the DSQ currently iterated by @it__iter to the
6724  * priority queue of the DSQ specified by @dsq_id. The destination must be a
6725  * user DSQ as only user DSQs support priority queue.
6726  *
6727  * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice()
6728  * and scx_bpf_dsq_move_set_vtime() to update.
6729  *
6730  * All other aspects are identical to scx_bpf_dsq_move(). See
6731  * scx_bpf_dsq_insert_vtime() for more information on @vtime.
6732  */
6733 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter,
6734 					struct task_struct *p, u64 dsq_id,
6735 					u64 enq_flags)
6736 {
6737 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
6738 			    p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
6739 }
6740 
6741 /* for backward compatibility, will be removed in v6.15 */
6742 __bpf_kfunc bool scx_bpf_dispatch_vtime_from_dsq(struct bpf_iter_scx_dsq *it__iter,
6743 						 struct task_struct *p, u64 dsq_id,
6744 						 u64 enq_flags)
6745 {
6746 	printk_deferred_once(KERN_WARNING "sched_ext: scx_bpf_dispatch_from_dsq_vtime() renamed to scx_bpf_dsq_move_vtime()");
6747 	return scx_bpf_dsq_move_vtime(it__iter, p, dsq_id, enq_flags);
6748 }
6749 
6750 __bpf_kfunc_end_defs();
6751 
6752 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
6753 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots)
6754 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel)
6755 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local)
6756 BTF_ID_FLAGS(func, scx_bpf_consume)
6757 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice)
6758 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime)
6759 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
6760 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
6761 BTF_ID_FLAGS(func, scx_bpf_dispatch_from_dsq_set_slice)
6762 BTF_ID_FLAGS(func, scx_bpf_dispatch_from_dsq_set_vtime)
6763 BTF_ID_FLAGS(func, scx_bpf_dispatch_from_dsq, KF_RCU)
6764 BTF_ID_FLAGS(func, scx_bpf_dispatch_vtime_from_dsq, KF_RCU)
6765 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
6766 
6767 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
6768 	.owner			= THIS_MODULE,
6769 	.set			= &scx_kfunc_ids_dispatch,
6770 };
6771 
6772 __bpf_kfunc_start_defs();
6773 
6774 /**
6775  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
6776  *
6777  * Iterate over all of the tasks currently enqueued on the local DSQ of the
6778  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
6779  * processed tasks. Can only be called from ops.cpu_release().
6780  */
6781 __bpf_kfunc u32 scx_bpf_reenqueue_local(void)
6782 {
6783 	LIST_HEAD(tasks);
6784 	u32 nr_enqueued = 0;
6785 	struct rq *rq;
6786 	struct task_struct *p, *n;
6787 
6788 	if (!scx_kf_allowed(SCX_KF_CPU_RELEASE))
6789 		return 0;
6790 
6791 	rq = cpu_rq(smp_processor_id());
6792 	lockdep_assert_rq_held(rq);
6793 
6794 	/*
6795 	 * The BPF scheduler may choose to dispatch tasks back to
6796 	 * @rq->scx.local_dsq. Move all candidate tasks off to a private list
6797 	 * first to avoid processing the same tasks repeatedly.
6798 	 */
6799 	list_for_each_entry_safe(p, n, &rq->scx.local_dsq.list,
6800 				 scx.dsq_list.node) {
6801 		/*
6802 		 * If @p is being migrated, @p's current CPU may not agree with
6803 		 * its allowed CPUs and the migration_cpu_stop is about to
6804 		 * deactivate and re-activate @p anyway. Skip re-enqueueing.
6805 		 *
6806 		 * While racing sched property changes may also dequeue and
6807 		 * re-enqueue a migrating task while its current CPU and allowed
6808 		 * CPUs disagree, they use %ENQUEUE_RESTORE which is bypassed to
6809 		 * the current local DSQ for running tasks and thus are not
6810 		 * visible to the BPF scheduler.
6811 		 *
6812 		 * Also skip re-enqueueing tasks that can only run on this
6813 		 * CPU, as they would just be re-added to the same local
6814 		 * DSQ without any benefit.
6815 		 */
6816 		if (p->migration_pending || is_migration_disabled(p) || p->nr_cpus_allowed == 1)
6817 			continue;
6818 
6819 		dispatch_dequeue(rq, p);
6820 		list_add_tail(&p->scx.dsq_list.node, &tasks);
6821 	}
6822 
6823 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
6824 		list_del_init(&p->scx.dsq_list.node);
6825 		do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
6826 		nr_enqueued++;
6827 	}
6828 
6829 	return nr_enqueued;
6830 }
6831 
6832 __bpf_kfunc_end_defs();
6833 
6834 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
6835 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local)
6836 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
6837 
6838 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
6839 	.owner			= THIS_MODULE,
6840 	.set			= &scx_kfunc_ids_cpu_release,
6841 };
6842 
6843 __bpf_kfunc_start_defs();
6844 
6845 /**
6846  * scx_bpf_create_dsq - Create a custom DSQ
6847  * @dsq_id: DSQ to create
6848  * @node: NUMA node to allocate from
6849  *
6850  * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable
6851  * scx callback, and any BPF_PROG_TYPE_SYSCALL prog.
6852  */
6853 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node)
6854 {
6855 	struct scx_dispatch_q *dsq;
6856 	struct scx_sched *sch;
6857 	s32 ret;
6858 
6859 	if (unlikely(node >= (int)nr_node_ids ||
6860 		     (node < 0 && node != NUMA_NO_NODE)))
6861 		return -EINVAL;
6862 
6863 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN))
6864 		return -EINVAL;
6865 
6866 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
6867 	if (!dsq)
6868 		return -ENOMEM;
6869 
6870 	init_dsq(dsq, dsq_id);
6871 
6872 	rcu_read_lock();
6873 
6874 	sch = rcu_dereference(scx_root);
6875 	if (sch)
6876 		ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node,
6877 						    dsq_hash_params);
6878 	else
6879 		ret = -ENODEV;
6880 
6881 	rcu_read_unlock();
6882 	if (ret)
6883 		kfree(dsq);
6884 	return ret;
6885 }
6886 
6887 __bpf_kfunc_end_defs();
6888 
6889 BTF_KFUNCS_START(scx_kfunc_ids_unlocked)
6890 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_SLEEPABLE)
6891 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice)
6892 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime)
6893 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
6894 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
6895 BTF_ID_FLAGS(func, scx_bpf_dispatch_from_dsq_set_slice)
6896 BTF_ID_FLAGS(func, scx_bpf_dispatch_from_dsq_set_vtime)
6897 BTF_ID_FLAGS(func, scx_bpf_dispatch_from_dsq, KF_RCU)
6898 BTF_ID_FLAGS(func, scx_bpf_dispatch_vtime_from_dsq, KF_RCU)
6899 BTF_KFUNCS_END(scx_kfunc_ids_unlocked)
6900 
6901 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = {
6902 	.owner			= THIS_MODULE,
6903 	.set			= &scx_kfunc_ids_unlocked,
6904 };
6905 
6906 __bpf_kfunc_start_defs();
6907 
6908 /**
6909  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
6910  * @cpu: cpu to kick
6911  * @flags: %SCX_KICK_* flags
6912  *
6913  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
6914  * trigger rescheduling on a busy CPU. This can be called from any online
6915  * scx_ops operation and the actual kicking is performed asynchronously through
6916  * an irq work.
6917  */
6918 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags)
6919 {
6920 	struct rq *this_rq;
6921 	unsigned long irq_flags;
6922 
6923 	if (!kf_cpu_valid(cpu, NULL))
6924 		return;
6925 
6926 	local_irq_save(irq_flags);
6927 
6928 	this_rq = this_rq();
6929 
6930 	/*
6931 	 * While bypassing for PM ops, IRQ handling may not be online which can
6932 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
6933 	 * IRQ status update. Suppress kicking.
6934 	 */
6935 	if (scx_rq_bypassing(this_rq))
6936 		goto out;
6937 
6938 	/*
6939 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
6940 	 * rq locks. We can probably be smarter and avoid bouncing if called
6941 	 * from ops which don't hold a rq lock.
6942 	 */
6943 	if (flags & SCX_KICK_IDLE) {
6944 		struct rq *target_rq = cpu_rq(cpu);
6945 
6946 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT)))
6947 			scx_kf_error("PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
6948 
6949 		if (raw_spin_rq_trylock(target_rq)) {
6950 			if (can_skip_idle_kick(target_rq)) {
6951 				raw_spin_rq_unlock(target_rq);
6952 				goto out;
6953 			}
6954 			raw_spin_rq_unlock(target_rq);
6955 		}
6956 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick_if_idle);
6957 	} else {
6958 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick);
6959 
6960 		if (flags & SCX_KICK_PREEMPT)
6961 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_preempt);
6962 		if (flags & SCX_KICK_WAIT)
6963 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_wait);
6964 	}
6965 
6966 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
6967 out:
6968 	local_irq_restore(irq_flags);
6969 }
6970 
6971 /**
6972  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
6973  * @dsq_id: id of the DSQ
6974  *
6975  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
6976  * -%ENOENT is returned.
6977  */
6978 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id)
6979 {
6980 	struct scx_sched *sch;
6981 	struct scx_dispatch_q *dsq;
6982 	s32 ret;
6983 
6984 	preempt_disable();
6985 
6986 	sch = rcu_dereference_sched(scx_root);
6987 	if (unlikely(!sch)) {
6988 		ret = -ENODEV;
6989 		goto out;
6990 	}
6991 
6992 	if (dsq_id == SCX_DSQ_LOCAL) {
6993 		ret = READ_ONCE(this_rq()->scx.local_dsq.nr);
6994 		goto out;
6995 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
6996 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
6997 
6998 		if (ops_cpu_valid(sch, cpu, NULL)) {
6999 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
7000 			goto out;
7001 		}
7002 	} else {
7003 		dsq = find_user_dsq(sch, dsq_id);
7004 		if (dsq) {
7005 			ret = READ_ONCE(dsq->nr);
7006 			goto out;
7007 		}
7008 	}
7009 	ret = -ENOENT;
7010 out:
7011 	preempt_enable();
7012 	return ret;
7013 }
7014 
7015 /**
7016  * scx_bpf_destroy_dsq - Destroy a custom DSQ
7017  * @dsq_id: DSQ to destroy
7018  *
7019  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
7020  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
7021  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
7022  * which doesn't exist. Can be called from any online scx_ops operations.
7023  */
7024 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id)
7025 {
7026 	struct scx_sched *sch;
7027 
7028 	rcu_read_lock();
7029 	sch = rcu_dereference(scx_root);
7030 	if (sch)
7031 		destroy_dsq(sch, dsq_id);
7032 	rcu_read_unlock();
7033 }
7034 
7035 /**
7036  * bpf_iter_scx_dsq_new - Create a DSQ iterator
7037  * @it: iterator to initialize
7038  * @dsq_id: DSQ to iterate
7039  * @flags: %SCX_DSQ_ITER_*
7040  *
7041  * Initialize BPF iterator @it which can be used with bpf_for_each() to walk
7042  * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes
7043  * tasks which are already queued when this function is invoked.
7044  */
7045 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id,
7046 				     u64 flags)
7047 {
7048 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
7049 	struct scx_sched *sch;
7050 
7051 	BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) >
7052 		     sizeof(struct bpf_iter_scx_dsq));
7053 	BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) !=
7054 		     __alignof__(struct bpf_iter_scx_dsq));
7055 
7056 	/*
7057 	 * next() and destroy() will be called regardless of the return value.
7058 	 * Always clear $kit->dsq.
7059 	 */
7060 	kit->dsq = NULL;
7061 
7062 	sch = rcu_dereference_check(scx_root, rcu_read_lock_bh_held());
7063 	if (unlikely(!sch))
7064 		return -ENODEV;
7065 
7066 	if (flags & ~__SCX_DSQ_ITER_USER_FLAGS)
7067 		return -EINVAL;
7068 
7069 	kit->dsq = find_user_dsq(sch, dsq_id);
7070 	if (!kit->dsq)
7071 		return -ENOENT;
7072 
7073 	INIT_LIST_HEAD(&kit->cursor.node);
7074 	kit->cursor.flags = SCX_DSQ_LNODE_ITER_CURSOR | flags;
7075 	kit->cursor.priv = READ_ONCE(kit->dsq->seq);
7076 
7077 	return 0;
7078 }
7079 
7080 /**
7081  * bpf_iter_scx_dsq_next - Progress a DSQ iterator
7082  * @it: iterator to progress
7083  *
7084  * Return the next task. See bpf_iter_scx_dsq_new().
7085  */
7086 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it)
7087 {
7088 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
7089 	bool rev = kit->cursor.flags & SCX_DSQ_ITER_REV;
7090 	struct task_struct *p;
7091 	unsigned long flags;
7092 
7093 	if (!kit->dsq)
7094 		return NULL;
7095 
7096 	raw_spin_lock_irqsave(&kit->dsq->lock, flags);
7097 
7098 	if (list_empty(&kit->cursor.node))
7099 		p = NULL;
7100 	else
7101 		p = container_of(&kit->cursor, struct task_struct, scx.dsq_list);
7102 
7103 	/*
7104 	 * Only tasks which were queued before the iteration started are
7105 	 * visible. This bounds BPF iterations and guarantees that vtime never
7106 	 * jumps in the other direction while iterating.
7107 	 */
7108 	do {
7109 		p = nldsq_next_task(kit->dsq, p, rev);
7110 	} while (p && unlikely(u32_before(kit->cursor.priv, p->scx.dsq_seq)));
7111 
7112 	if (p) {
7113 		if (rev)
7114 			list_move_tail(&kit->cursor.node, &p->scx.dsq_list.node);
7115 		else
7116 			list_move(&kit->cursor.node, &p->scx.dsq_list.node);
7117 	} else {
7118 		list_del_init(&kit->cursor.node);
7119 	}
7120 
7121 	raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
7122 
7123 	return p;
7124 }
7125 
7126 /**
7127  * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator
7128  * @it: iterator to destroy
7129  *
7130  * Undo scx_iter_scx_dsq_new().
7131  */
7132 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it)
7133 {
7134 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
7135 
7136 	if (!kit->dsq)
7137 		return;
7138 
7139 	if (!list_empty(&kit->cursor.node)) {
7140 		unsigned long flags;
7141 
7142 		raw_spin_lock_irqsave(&kit->dsq->lock, flags);
7143 		list_del_init(&kit->cursor.node);
7144 		raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
7145 	}
7146 	kit->dsq = NULL;
7147 }
7148 
7149 __bpf_kfunc_end_defs();
7150 
7151 static s32 __bstr_format(u64 *data_buf, char *line_buf, size_t line_size,
7152 			 char *fmt, unsigned long long *data, u32 data__sz)
7153 {
7154 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
7155 	s32 ret;
7156 
7157 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
7158 	    (data__sz && !data)) {
7159 		scx_kf_error("invalid data=%p and data__sz=%u", (void *)data, data__sz);
7160 		return -EINVAL;
7161 	}
7162 
7163 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
7164 	if (ret < 0) {
7165 		scx_kf_error("failed to read data fields (%d)", ret);
7166 		return ret;
7167 	}
7168 
7169 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
7170 				  &bprintf_data);
7171 	if (ret < 0) {
7172 		scx_kf_error("format preparation failed (%d)", ret);
7173 		return ret;
7174 	}
7175 
7176 	ret = bstr_printf(line_buf, line_size, fmt,
7177 			  bprintf_data.bin_args);
7178 	bpf_bprintf_cleanup(&bprintf_data);
7179 	if (ret < 0) {
7180 		scx_kf_error("(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
7181 		return ret;
7182 	}
7183 
7184 	return ret;
7185 }
7186 
7187 static s32 bstr_format(struct scx_bstr_buf *buf,
7188 		       char *fmt, unsigned long long *data, u32 data__sz)
7189 {
7190 	return __bstr_format(buf->data, buf->line, sizeof(buf->line),
7191 			     fmt, data, data__sz);
7192 }
7193 
7194 __bpf_kfunc_start_defs();
7195 
7196 /**
7197  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
7198  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
7199  * @fmt: error message format string
7200  * @data: format string parameters packaged using ___bpf_fill() macro
7201  * @data__sz: @data len, must end in '__sz' for the verifier
7202  *
7203  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
7204  * disabling.
7205  */
7206 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
7207 				   unsigned long long *data, u32 data__sz)
7208 {
7209 	unsigned long flags;
7210 
7211 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
7212 	if (bstr_format(&scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
7213 		scx_kf_exit(SCX_EXIT_UNREG_BPF, exit_code, "%s", scx_exit_bstr_buf.line);
7214 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
7215 }
7216 
7217 /**
7218  * scx_bpf_error_bstr - Indicate fatal error
7219  * @fmt: error message format string
7220  * @data: format string parameters packaged using ___bpf_fill() macro
7221  * @data__sz: @data len, must end in '__sz' for the verifier
7222  *
7223  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
7224  * disabling.
7225  */
7226 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
7227 				    u32 data__sz)
7228 {
7229 	unsigned long flags;
7230 
7231 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
7232 	if (bstr_format(&scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
7233 		scx_kf_exit(SCX_EXIT_ERROR_BPF, 0, "%s", scx_exit_bstr_buf.line);
7234 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
7235 }
7236 
7237 /**
7238  * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler
7239  * @fmt: format string
7240  * @data: format string parameters packaged using ___bpf_fill() macro
7241  * @data__sz: @data len, must end in '__sz' for the verifier
7242  *
7243  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
7244  * dump_task() to generate extra debug dump specific to the BPF scheduler.
7245  *
7246  * The extra dump may be multiple lines. A single line may be split over
7247  * multiple calls. The last line is automatically terminated.
7248  */
7249 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
7250 				   u32 data__sz)
7251 {
7252 	struct scx_dump_data *dd = &scx_dump_data;
7253 	struct scx_bstr_buf *buf = &dd->buf;
7254 	s32 ret;
7255 
7256 	if (raw_smp_processor_id() != dd->cpu) {
7257 		scx_kf_error("scx_bpf_dump() must only be called from ops.dump() and friends");
7258 		return;
7259 	}
7260 
7261 	/* append the formatted string to the line buf */
7262 	ret = __bstr_format(buf->data, buf->line + dd->cursor,
7263 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
7264 	if (ret < 0) {
7265 		dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
7266 			  dd->prefix, fmt, data, data__sz, ret);
7267 		return;
7268 	}
7269 
7270 	dd->cursor += ret;
7271 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
7272 
7273 	if (!dd->cursor)
7274 		return;
7275 
7276 	/*
7277 	 * If the line buf overflowed or ends in a newline, flush it into the
7278 	 * dump. This is to allow the caller to generate a single line over
7279 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
7280 	 * the line buf, the only case which can lead to an unexpected
7281 	 * truncation is when the caller keeps generating newlines in the middle
7282 	 * instead of the end consecutively. Don't do that.
7283 	 */
7284 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
7285 		ops_dump_flush();
7286 }
7287 
7288 /**
7289  * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU
7290  * @cpu: CPU of interest
7291  *
7292  * Return the maximum relative capacity of @cpu in relation to the most
7293  * performant CPU in the system. The return value is in the range [1,
7294  * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur().
7295  */
7296 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu)
7297 {
7298 	if (kf_cpu_valid(cpu, NULL))
7299 		return arch_scale_cpu_capacity(cpu);
7300 	else
7301 		return SCX_CPUPERF_ONE;
7302 }
7303 
7304 /**
7305  * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU
7306  * @cpu: CPU of interest
7307  *
7308  * Return the current relative performance of @cpu in relation to its maximum.
7309  * The return value is in the range [1, %SCX_CPUPERF_ONE].
7310  *
7311  * The current performance level of a CPU in relation to the maximum performance
7312  * available in the system can be calculated as follows:
7313  *
7314  *   scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE
7315  *
7316  * The result is in the range [1, %SCX_CPUPERF_ONE].
7317  */
7318 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu)
7319 {
7320 	if (kf_cpu_valid(cpu, NULL))
7321 		return arch_scale_freq_capacity(cpu);
7322 	else
7323 		return SCX_CPUPERF_ONE;
7324 }
7325 
7326 /**
7327  * scx_bpf_cpuperf_set - Set the relative performance target of a CPU
7328  * @cpu: CPU of interest
7329  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
7330  *
7331  * Set the target performance level of @cpu to @perf. @perf is in linear
7332  * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the
7333  * schedutil cpufreq governor chooses the target frequency.
7334  *
7335  * The actual performance level chosen, CPU grouping, and the overhead and
7336  * latency of the operations are dependent on the hardware and cpufreq driver in
7337  * use. Consult hardware and cpufreq documentation for more information. The
7338  * current performance level can be monitored using scx_bpf_cpuperf_cur().
7339  */
7340 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf)
7341 {
7342 	if (unlikely(perf > SCX_CPUPERF_ONE)) {
7343 		scx_kf_error("Invalid cpuperf target %u for CPU %d", perf, cpu);
7344 		return;
7345 	}
7346 
7347 	if (kf_cpu_valid(cpu, NULL)) {
7348 		struct rq *rq = cpu_rq(cpu), *locked_rq = scx_locked_rq();
7349 		struct rq_flags rf;
7350 
7351 		/*
7352 		 * When called with an rq lock held, restrict the operation
7353 		 * to the corresponding CPU to prevent ABBA deadlocks.
7354 		 */
7355 		if (locked_rq && rq != locked_rq) {
7356 			scx_kf_error("Invalid target CPU %d", cpu);
7357 			return;
7358 		}
7359 
7360 		/*
7361 		 * If no rq lock is held, allow to operate on any CPU by
7362 		 * acquiring the corresponding rq lock.
7363 		 */
7364 		if (!locked_rq) {
7365 			rq_lock_irqsave(rq, &rf);
7366 			update_rq_clock(rq);
7367 		}
7368 
7369 		rq->scx.cpuperf_target = perf;
7370 		cpufreq_update_util(rq, 0);
7371 
7372 		if (!locked_rq)
7373 			rq_unlock_irqrestore(rq, &rf);
7374 	}
7375 }
7376 
7377 /**
7378  * scx_bpf_nr_node_ids - Return the number of possible node IDs
7379  *
7380  * All valid node IDs in the system are smaller than the returned value.
7381  */
7382 __bpf_kfunc u32 scx_bpf_nr_node_ids(void)
7383 {
7384 	return nr_node_ids;
7385 }
7386 
7387 /**
7388  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
7389  *
7390  * All valid CPU IDs in the system are smaller than the returned value.
7391  */
7392 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
7393 {
7394 	return nr_cpu_ids;
7395 }
7396 
7397 /**
7398  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
7399  */
7400 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
7401 {
7402 	return cpu_possible_mask;
7403 }
7404 
7405 /**
7406  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
7407  */
7408 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
7409 {
7410 	return cpu_online_mask;
7411 }
7412 
7413 /**
7414  * scx_bpf_put_cpumask - Release a possible/online cpumask
7415  * @cpumask: cpumask to release
7416  */
7417 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
7418 {
7419 	/*
7420 	 * Empty function body because we aren't actually acquiring or releasing
7421 	 * a reference to a global cpumask, which is read-only in the caller and
7422 	 * is never released. The acquire / release semantics here are just used
7423 	 * to make the cpumask is a trusted pointer in the caller.
7424 	 */
7425 }
7426 
7427 /**
7428  * scx_bpf_task_running - Is task currently running?
7429  * @p: task of interest
7430  */
7431 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
7432 {
7433 	return task_rq(p)->curr == p;
7434 }
7435 
7436 /**
7437  * scx_bpf_task_cpu - CPU a task is currently associated with
7438  * @p: task of interest
7439  */
7440 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
7441 {
7442 	return task_cpu(p);
7443 }
7444 
7445 /**
7446  * scx_bpf_cpu_rq - Fetch the rq of a CPU
7447  * @cpu: CPU of the rq
7448  */
7449 __bpf_kfunc struct rq *scx_bpf_cpu_rq(s32 cpu)
7450 {
7451 	if (!kf_cpu_valid(cpu, NULL))
7452 		return NULL;
7453 
7454 	return cpu_rq(cpu);
7455 }
7456 
7457 /**
7458  * scx_bpf_task_cgroup - Return the sched cgroup of a task
7459  * @p: task of interest
7460  *
7461  * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with
7462  * from the scheduler's POV. SCX operations should use this function to
7463  * determine @p's current cgroup as, unlike following @p->cgroups,
7464  * @p->sched_task_group is protected by @p's rq lock and thus atomic w.r.t. all
7465  * rq-locked operations. Can be called on the parameter tasks of rq-locked
7466  * operations. The restriction guarantees that @p's rq is locked by the caller.
7467  */
7468 #ifdef CONFIG_CGROUP_SCHED
7469 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p)
7470 {
7471 	struct task_group *tg = p->sched_task_group;
7472 	struct cgroup *cgrp = &cgrp_dfl_root.cgrp;
7473 
7474 	if (!scx_kf_allowed_on_arg_tasks(__SCX_KF_RQ_LOCKED, p))
7475 		goto out;
7476 
7477 	cgrp = tg_cgrp(tg);
7478 
7479 out:
7480 	cgroup_get(cgrp);
7481 	return cgrp;
7482 }
7483 #endif
7484 
7485 /**
7486  * scx_bpf_now - Returns a high-performance monotonically non-decreasing
7487  * clock for the current CPU. The clock returned is in nanoseconds.
7488  *
7489  * It provides the following properties:
7490  *
7491  * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently
7492  *  to account for execution time and track tasks' runtime properties.
7493  *  Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which
7494  *  eventually reads a hardware timestamp counter -- is neither performant nor
7495  *  scalable. scx_bpf_now() aims to provide a high-performance clock by
7496  *  using the rq clock in the scheduler core whenever possible.
7497  *
7498  * 2) High enough resolution for the BPF scheduler use cases: In most BPF
7499  *  scheduler use cases, the required clock resolution is lower than the most
7500  *  accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically
7501  *  uses the rq clock in the scheduler core whenever it is valid. It considers
7502  *  that the rq clock is valid from the time the rq clock is updated
7503  *  (update_rq_clock) until the rq is unlocked (rq_unpin_lock).
7504  *
7505  * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now()
7506  *  guarantees the clock never goes backward when comparing them in the same
7507  *  CPU. On the other hand, when comparing clocks in different CPUs, there
7508  *  is no such guarantee -- the clock can go backward. It provides a
7509  *  monotonically *non-decreasing* clock so that it would provide the same
7510  *  clock values in two different scx_bpf_now() calls in the same CPU
7511  *  during the same period of when the rq clock is valid.
7512  */
7513 __bpf_kfunc u64 scx_bpf_now(void)
7514 {
7515 	struct rq *rq;
7516 	u64 clock;
7517 
7518 	preempt_disable();
7519 
7520 	rq = this_rq();
7521 	if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) {
7522 		/*
7523 		 * If the rq clock is valid, use the cached rq clock.
7524 		 *
7525 		 * Note that scx_bpf_now() is re-entrant between a process
7526 		 * context and an interrupt context (e.g., timer interrupt).
7527 		 * However, we don't need to consider the race between them
7528 		 * because such race is not observable from a caller.
7529 		 */
7530 		clock = READ_ONCE(rq->scx.clock);
7531 	} else {
7532 		/*
7533 		 * Otherwise, return a fresh rq clock.
7534 		 *
7535 		 * The rq clock is updated outside of the rq lock.
7536 		 * In this case, keep the updated rq clock invalid so the next
7537 		 * kfunc call outside the rq lock gets a fresh rq clock.
7538 		 */
7539 		clock = sched_clock_cpu(cpu_of(rq));
7540 	}
7541 
7542 	preempt_enable();
7543 
7544 	return clock;
7545 }
7546 
7547 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events)
7548 {
7549 	struct scx_event_stats *e_cpu;
7550 	int cpu;
7551 
7552 	/* Aggregate per-CPU event counters into @events. */
7553 	memset(events, 0, sizeof(*events));
7554 	for_each_possible_cpu(cpu) {
7555 		e_cpu = per_cpu_ptr(sch->event_stats_cpu, cpu);
7556 		scx_agg_event(events, e_cpu, SCX_EV_SELECT_CPU_FALLBACK);
7557 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
7558 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_KEEP_LAST);
7559 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_EXITING);
7560 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
7561 		scx_agg_event(events, e_cpu, SCX_EV_REFILL_SLICE_DFL);
7562 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DURATION);
7563 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DISPATCH);
7564 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_ACTIVATE);
7565 	}
7566 }
7567 
7568 /*
7569  * scx_bpf_events - Get a system-wide event counter to
7570  * @events: output buffer from a BPF program
7571  * @events__sz: @events len, must end in '__sz'' for the verifier
7572  */
7573 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events,
7574 				size_t events__sz)
7575 {
7576 	struct scx_sched *sch;
7577 	struct scx_event_stats e_sys;
7578 
7579 	rcu_read_lock();
7580 	sch = rcu_dereference(scx_root);
7581 	if (sch)
7582 		scx_read_events(sch, &e_sys);
7583 	else
7584 		memset(&e_sys, 0, sizeof(e_sys));
7585 	rcu_read_unlock();
7586 
7587 	/*
7588 	 * We cannot entirely trust a BPF-provided size since a BPF program
7589 	 * might be compiled against a different vmlinux.h, of which
7590 	 * scx_event_stats would be larger (a newer vmlinux.h) or smaller
7591 	 * (an older vmlinux.h). Hence, we use the smaller size to avoid
7592 	 * memory corruption.
7593 	 */
7594 	events__sz = min(events__sz, sizeof(*events));
7595 	memcpy(events, &e_sys, events__sz);
7596 }
7597 
7598 __bpf_kfunc_end_defs();
7599 
7600 BTF_KFUNCS_START(scx_kfunc_ids_any)
7601 BTF_ID_FLAGS(func, scx_bpf_kick_cpu)
7602 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued)
7603 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq)
7604 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_ITER_NEW | KF_RCU_PROTECTED)
7605 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
7606 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
7607 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_TRUSTED_ARGS)
7608 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_TRUSTED_ARGS)
7609 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_TRUSTED_ARGS)
7610 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap)
7611 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur)
7612 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set)
7613 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
7614 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
7615 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
7616 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
7617 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
7618 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
7619 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
7620 BTF_ID_FLAGS(func, scx_bpf_cpu_rq)
7621 #ifdef CONFIG_CGROUP_SCHED
7622 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_RCU | KF_ACQUIRE)
7623 #endif
7624 BTF_ID_FLAGS(func, scx_bpf_now)
7625 BTF_ID_FLAGS(func, scx_bpf_events, KF_TRUSTED_ARGS)
7626 BTF_KFUNCS_END(scx_kfunc_ids_any)
7627 
7628 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
7629 	.owner			= THIS_MODULE,
7630 	.set			= &scx_kfunc_ids_any,
7631 };
7632 
7633 static int __init scx_init(void)
7634 {
7635 	int ret;
7636 
7637 	/*
7638 	 * kfunc registration can't be done from init_sched_ext_class() as
7639 	 * register_btf_kfunc_id_set() needs most of the system to be up.
7640 	 *
7641 	 * Some kfuncs are context-sensitive and can only be called from
7642 	 * specific SCX ops. They are grouped into BTF sets accordingly.
7643 	 * Unfortunately, BPF currently doesn't have a way of enforcing such
7644 	 * restrictions. Eventually, the verifier should be able to enforce
7645 	 * them. For now, register them the same and make each kfunc explicitly
7646 	 * check using scx_kf_allowed().
7647 	 */
7648 	if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
7649 					     &scx_kfunc_set_enqueue_dispatch)) ||
7650 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
7651 					     &scx_kfunc_set_dispatch)) ||
7652 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
7653 					     &scx_kfunc_set_cpu_release)) ||
7654 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
7655 					     &scx_kfunc_set_unlocked)) ||
7656 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
7657 					     &scx_kfunc_set_unlocked)) ||
7658 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
7659 					     &scx_kfunc_set_any)) ||
7660 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
7661 					     &scx_kfunc_set_any)) ||
7662 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
7663 					     &scx_kfunc_set_any))) {
7664 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
7665 		return ret;
7666 	}
7667 
7668 	ret = scx_idle_init();
7669 	if (ret) {
7670 		pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret);
7671 		return ret;
7672 	}
7673 
7674 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops);
7675 	if (ret) {
7676 		pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret);
7677 		return ret;
7678 	}
7679 
7680 	ret = register_pm_notifier(&scx_pm_notifier);
7681 	if (ret) {
7682 		pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret);
7683 		return ret;
7684 	}
7685 
7686 	scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj);
7687 	if (!scx_kset) {
7688 		pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n");
7689 		return -ENOMEM;
7690 	}
7691 
7692 	ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group);
7693 	if (ret < 0) {
7694 		pr_err("sched_ext: Failed to add global attributes\n");
7695 		return ret;
7696 	}
7697 
7698 	return 0;
7699 }
7700 __initcall(scx_init);
7701