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