xref: /linux/kernel/sched/ext.c (revision 245254f7081dbe1c8da54675d0e4ddbe74cee61b)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
4  * Copyright (c) 2022 Tejun Heo <tj@kernel.org>
5  * Copyright (c) 2022 David Vernet <dvernet@meta.com>
6  */
7 #define SCX_OP_IDX(op)		(offsetof(struct sched_ext_ops, op) / sizeof(void (*)(void)))
8 
9 enum scx_consts {
10 	SCX_DSP_DFL_MAX_BATCH		= 32,
11 	SCX_DSP_MAX_LOOPS		= 32,
12 	SCX_WATCHDOG_MAX_TIMEOUT	= 30 * HZ,
13 
14 	SCX_EXIT_BT_LEN			= 64,
15 	SCX_EXIT_MSG_LEN		= 1024,
16 	SCX_EXIT_DUMP_DFL_LEN		= 32768,
17 };
18 
19 enum scx_exit_kind {
20 	SCX_EXIT_NONE,
21 	SCX_EXIT_DONE,
22 
23 	SCX_EXIT_UNREG = 64,	/* user-space initiated unregistration */
24 	SCX_EXIT_UNREG_BPF,	/* BPF-initiated unregistration */
25 	SCX_EXIT_UNREG_KERN,	/* kernel-initiated unregistration */
26 	SCX_EXIT_SYSRQ,		/* requested by 'S' sysrq */
27 
28 	SCX_EXIT_ERROR = 1024,	/* runtime error, error msg contains details */
29 	SCX_EXIT_ERROR_BPF,	/* ERROR but triggered through scx_bpf_error() */
30 	SCX_EXIT_ERROR_STALL,	/* watchdog detected stalled runnable tasks */
31 };
32 
33 /*
34  * scx_exit_info is passed to ops.exit() to describe why the BPF scheduler is
35  * being disabled.
36  */
37 struct scx_exit_info {
38 	/* %SCX_EXIT_* - broad category of the exit reason */
39 	enum scx_exit_kind	kind;
40 
41 	/* exit code if gracefully exiting */
42 	s64			exit_code;
43 
44 	/* textual representation of the above */
45 	const char		*reason;
46 
47 	/* backtrace if exiting due to an error */
48 	unsigned long		*bt;
49 	u32			bt_len;
50 
51 	/* informational message */
52 	char			*msg;
53 
54 	/* debug dump */
55 	char			*dump;
56 };
57 
58 /* sched_ext_ops.flags */
59 enum scx_ops_flags {
60 	/*
61 	 * Keep built-in idle tracking even if ops.update_idle() is implemented.
62 	 */
63 	SCX_OPS_KEEP_BUILTIN_IDLE = 1LLU << 0,
64 
65 	/*
66 	 * By default, if there are no other task to run on the CPU, ext core
67 	 * keeps running the current task even after its slice expires. If this
68 	 * flag is specified, such tasks are passed to ops.enqueue() with
69 	 * %SCX_ENQ_LAST. See the comment above %SCX_ENQ_LAST for more info.
70 	 */
71 	SCX_OPS_ENQ_LAST	= 1LLU << 1,
72 
73 	/*
74 	 * An exiting task may schedule after PF_EXITING is set. In such cases,
75 	 * bpf_task_from_pid() may not be able to find the task and if the BPF
76 	 * scheduler depends on pid lookup for dispatching, the task will be
77 	 * lost leading to various issues including RCU grace period stalls.
78 	 *
79 	 * To mask this problem, by default, unhashed tasks are automatically
80 	 * dispatched to the local DSQ on enqueue. If the BPF scheduler doesn't
81 	 * depend on pid lookups and wants to handle these tasks directly, the
82 	 * following flag can be used.
83 	 */
84 	SCX_OPS_ENQ_EXITING	= 1LLU << 2,
85 
86 	/*
87 	 * If set, only tasks with policy set to SCHED_EXT are attached to
88 	 * sched_ext. If clear, SCHED_NORMAL tasks are also included.
89 	 */
90 	SCX_OPS_SWITCH_PARTIAL	= 1LLU << 3,
91 
92 	SCX_OPS_ALL_FLAGS	= SCX_OPS_KEEP_BUILTIN_IDLE |
93 				  SCX_OPS_ENQ_LAST |
94 				  SCX_OPS_ENQ_EXITING |
95 				  SCX_OPS_SWITCH_PARTIAL,
96 };
97 
98 /* argument container for ops.init_task() */
99 struct scx_init_task_args {
100 	/*
101 	 * Set if ops.init_task() is being invoked on the fork path, as opposed
102 	 * to the scheduler transition path.
103 	 */
104 	bool			fork;
105 };
106 
107 /* argument container for ops.exit_task() */
108 struct scx_exit_task_args {
109 	/* Whether the task exited before running on sched_ext. */
110 	bool cancelled;
111 };
112 
113 enum scx_cpu_preempt_reason {
114 	/* next task is being scheduled by &sched_class_rt */
115 	SCX_CPU_PREEMPT_RT,
116 	/* next task is being scheduled by &sched_class_dl */
117 	SCX_CPU_PREEMPT_DL,
118 	/* next task is being scheduled by &sched_class_stop */
119 	SCX_CPU_PREEMPT_STOP,
120 	/* unknown reason for SCX being preempted */
121 	SCX_CPU_PREEMPT_UNKNOWN,
122 };
123 
124 /*
125  * Argument container for ops->cpu_acquire(). Currently empty, but may be
126  * expanded in the future.
127  */
128 struct scx_cpu_acquire_args {};
129 
130 /* argument container for ops->cpu_release() */
131 struct scx_cpu_release_args {
132 	/* the reason the CPU was preempted */
133 	enum scx_cpu_preempt_reason reason;
134 
135 	/* the task that's going to be scheduled on the CPU */
136 	struct task_struct	*task;
137 };
138 
139 /*
140  * Informational context provided to dump operations.
141  */
142 struct scx_dump_ctx {
143 	enum scx_exit_kind	kind;
144 	s64			exit_code;
145 	const char		*reason;
146 	u64			at_ns;
147 	u64			at_jiffies;
148 };
149 
150 /**
151  * struct sched_ext_ops - Operation table for BPF scheduler implementation
152  *
153  * Userland can implement an arbitrary scheduling policy by implementing and
154  * loading operations in this table.
155  */
156 struct sched_ext_ops {
157 	/**
158 	 * select_cpu - Pick the target CPU for a task which is being woken up
159 	 * @p: task being woken up
160 	 * @prev_cpu: the cpu @p was on before sleeping
161 	 * @wake_flags: SCX_WAKE_*
162 	 *
163 	 * Decision made here isn't final. @p may be moved to any CPU while it
164 	 * is getting dispatched for execution later. However, as @p is not on
165 	 * the rq at this point, getting the eventual execution CPU right here
166 	 * saves a small bit of overhead down the line.
167 	 *
168 	 * If an idle CPU is returned, the CPU is kicked and will try to
169 	 * dispatch. While an explicit custom mechanism can be added,
170 	 * select_cpu() serves as the default way to wake up idle CPUs.
171 	 *
172 	 * @p may be dispatched directly by calling scx_bpf_dispatch(). If @p
173 	 * is dispatched, the ops.enqueue() callback will be skipped. Finally,
174 	 * if @p is dispatched to SCX_DSQ_LOCAL, it will be dispatched to the
175 	 * local DSQ of whatever CPU is returned by this callback.
176 	 */
177 	s32 (*select_cpu)(struct task_struct *p, s32 prev_cpu, u64 wake_flags);
178 
179 	/**
180 	 * enqueue - Enqueue a task on the BPF scheduler
181 	 * @p: task being enqueued
182 	 * @enq_flags: %SCX_ENQ_*
183 	 *
184 	 * @p is ready to run. Dispatch directly by calling scx_bpf_dispatch()
185 	 * or enqueue on the BPF scheduler. If not directly dispatched, the bpf
186 	 * scheduler owns @p and if it fails to dispatch @p, the task will
187 	 * stall.
188 	 *
189 	 * If @p was dispatched from ops.select_cpu(), this callback is
190 	 * skipped.
191 	 */
192 	void (*enqueue)(struct task_struct *p, u64 enq_flags);
193 
194 	/**
195 	 * dequeue - Remove a task from the BPF scheduler
196 	 * @p: task being dequeued
197 	 * @deq_flags: %SCX_DEQ_*
198 	 *
199 	 * Remove @p from the BPF scheduler. This is usually called to isolate
200 	 * the task while updating its scheduling properties (e.g. priority).
201 	 *
202 	 * The ext core keeps track of whether the BPF side owns a given task or
203 	 * not and can gracefully ignore spurious dispatches from BPF side,
204 	 * which makes it safe to not implement this method. However, depending
205 	 * on the scheduling logic, this can lead to confusing behaviors - e.g.
206 	 * scheduling position not being updated across a priority change.
207 	 */
208 	void (*dequeue)(struct task_struct *p, u64 deq_flags);
209 
210 	/**
211 	 * dispatch - Dispatch tasks from the BPF scheduler and/or consume DSQs
212 	 * @cpu: CPU to dispatch tasks for
213 	 * @prev: previous task being switched out
214 	 *
215 	 * Called when a CPU's local dsq is empty. The operation should dispatch
216 	 * one or more tasks from the BPF scheduler into the DSQs using
217 	 * scx_bpf_dispatch() and/or consume user DSQs into the local DSQ using
218 	 * scx_bpf_consume().
219 	 *
220 	 * The maximum number of times scx_bpf_dispatch() can be called without
221 	 * an intervening scx_bpf_consume() is specified by
222 	 * ops.dispatch_max_batch. See the comments on top of the two functions
223 	 * for more details.
224 	 *
225 	 * When not %NULL, @prev is an SCX task with its slice depleted. If
226 	 * @prev is still runnable as indicated by set %SCX_TASK_QUEUED in
227 	 * @prev->scx.flags, it is not enqueued yet and will be enqueued after
228 	 * ops.dispatch() returns. To keep executing @prev, return without
229 	 * dispatching or consuming any tasks. Also see %SCX_OPS_ENQ_LAST.
230 	 */
231 	void (*dispatch)(s32 cpu, struct task_struct *prev);
232 
233 	/**
234 	 * tick - Periodic tick
235 	 * @p: task running currently
236 	 *
237 	 * This operation is called every 1/HZ seconds on CPUs which are
238 	 * executing an SCX task. Setting @p->scx.slice to 0 will trigger an
239 	 * immediate dispatch cycle on the CPU.
240 	 */
241 	void (*tick)(struct task_struct *p);
242 
243 	/**
244 	 * runnable - A task is becoming runnable on its associated CPU
245 	 * @p: task becoming runnable
246 	 * @enq_flags: %SCX_ENQ_*
247 	 *
248 	 * This and the following three functions can be used to track a task's
249 	 * execution state transitions. A task becomes ->runnable() on a CPU,
250 	 * and then goes through one or more ->running() and ->stopping() pairs
251 	 * as it runs on the CPU, and eventually becomes ->quiescent() when it's
252 	 * done running on the CPU.
253 	 *
254 	 * @p is becoming runnable on the CPU because it's
255 	 *
256 	 * - waking up (%SCX_ENQ_WAKEUP)
257 	 * - being moved from another CPU
258 	 * - being restored after temporarily taken off the queue for an
259 	 *   attribute change.
260 	 *
261 	 * This and ->enqueue() are related but not coupled. This operation
262 	 * notifies @p's state transition and may not be followed by ->enqueue()
263 	 * e.g. when @p is being dispatched to a remote CPU, or when @p is
264 	 * being enqueued on a CPU experiencing a hotplug event. Likewise, a
265 	 * task may be ->enqueue()'d without being preceded by this operation
266 	 * e.g. after exhausting its slice.
267 	 */
268 	void (*runnable)(struct task_struct *p, u64 enq_flags);
269 
270 	/**
271 	 * running - A task is starting to run on its associated CPU
272 	 * @p: task starting to run
273 	 *
274 	 * See ->runnable() for explanation on the task state notifiers.
275 	 */
276 	void (*running)(struct task_struct *p);
277 
278 	/**
279 	 * stopping - A task is stopping execution
280 	 * @p: task stopping to run
281 	 * @runnable: is task @p still runnable?
282 	 *
283 	 * See ->runnable() for explanation on the task state notifiers. If
284 	 * !@runnable, ->quiescent() will be invoked after this operation
285 	 * returns.
286 	 */
287 	void (*stopping)(struct task_struct *p, bool runnable);
288 
289 	/**
290 	 * quiescent - A task is becoming not runnable on its associated CPU
291 	 * @p: task becoming not runnable
292 	 * @deq_flags: %SCX_DEQ_*
293 	 *
294 	 * See ->runnable() for explanation on the task state notifiers.
295 	 *
296 	 * @p is becoming quiescent on the CPU because it's
297 	 *
298 	 * - sleeping (%SCX_DEQ_SLEEP)
299 	 * - being moved to another CPU
300 	 * - being temporarily taken off the queue for an attribute change
301 	 *   (%SCX_DEQ_SAVE)
302 	 *
303 	 * This and ->dequeue() are related but not coupled. This operation
304 	 * notifies @p's state transition and may not be preceded by ->dequeue()
305 	 * e.g. when @p is being dispatched to a remote CPU.
306 	 */
307 	void (*quiescent)(struct task_struct *p, u64 deq_flags);
308 
309 	/**
310 	 * yield - Yield CPU
311 	 * @from: yielding task
312 	 * @to: optional yield target task
313 	 *
314 	 * If @to is NULL, @from is yielding the CPU to other runnable tasks.
315 	 * The BPF scheduler should ensure that other available tasks are
316 	 * dispatched before the yielding task. Return value is ignored in this
317 	 * case.
318 	 *
319 	 * If @to is not-NULL, @from wants to yield the CPU to @to. If the bpf
320 	 * scheduler can implement the request, return %true; otherwise, %false.
321 	 */
322 	bool (*yield)(struct task_struct *from, struct task_struct *to);
323 
324 	/**
325 	 * set_weight - Set task weight
326 	 * @p: task to set weight for
327 	 * @weight: new eight [1..10000]
328 	 *
329 	 * Update @p's weight to @weight.
330 	 */
331 	void (*set_weight)(struct task_struct *p, u32 weight);
332 
333 	/**
334 	 * set_cpumask - Set CPU affinity
335 	 * @p: task to set CPU affinity for
336 	 * @cpumask: cpumask of cpus that @p can run on
337 	 *
338 	 * Update @p's CPU affinity to @cpumask.
339 	 */
340 	void (*set_cpumask)(struct task_struct *p,
341 			    const struct cpumask *cpumask);
342 
343 	/**
344 	 * update_idle - Update the idle state of a CPU
345 	 * @cpu: CPU to udpate the idle state for
346 	 * @idle: whether entering or exiting the idle state
347 	 *
348 	 * This operation is called when @rq's CPU goes or leaves the idle
349 	 * state. By default, implementing this operation disables the built-in
350 	 * idle CPU tracking and the following helpers become unavailable:
351 	 *
352 	 * - scx_bpf_select_cpu_dfl()
353 	 * - scx_bpf_test_and_clear_cpu_idle()
354 	 * - scx_bpf_pick_idle_cpu()
355 	 *
356 	 * The user also must implement ops.select_cpu() as the default
357 	 * implementation relies on scx_bpf_select_cpu_dfl().
358 	 *
359 	 * Specify the %SCX_OPS_KEEP_BUILTIN_IDLE flag to keep the built-in idle
360 	 * tracking.
361 	 */
362 	void (*update_idle)(s32 cpu, bool idle);
363 
364 	/**
365 	 * cpu_acquire - A CPU is becoming available to the BPF scheduler
366 	 * @cpu: The CPU being acquired by the BPF scheduler.
367 	 * @args: Acquire arguments, see the struct definition.
368 	 *
369 	 * A CPU that was previously released from the BPF scheduler is now once
370 	 * again under its control.
371 	 */
372 	void (*cpu_acquire)(s32 cpu, struct scx_cpu_acquire_args *args);
373 
374 	/**
375 	 * cpu_release - A CPU is taken away from the BPF scheduler
376 	 * @cpu: The CPU being released by the BPF scheduler.
377 	 * @args: Release arguments, see the struct definition.
378 	 *
379 	 * The specified CPU is no longer under the control of the BPF
380 	 * scheduler. This could be because it was preempted by a higher
381 	 * priority sched_class, though there may be other reasons as well. The
382 	 * caller should consult @args->reason to determine the cause.
383 	 */
384 	void (*cpu_release)(s32 cpu, struct scx_cpu_release_args *args);
385 
386 	/**
387 	 * init_task - Initialize a task to run in a BPF scheduler
388 	 * @p: task to initialize for BPF scheduling
389 	 * @args: init arguments, see the struct definition
390 	 *
391 	 * Either we're loading a BPF scheduler or a new task is being forked.
392 	 * Initialize @p for BPF scheduling. This operation may block and can
393 	 * be used for allocations, and is called exactly once for a task.
394 	 *
395 	 * Return 0 for success, -errno for failure. An error return while
396 	 * loading will abort loading of the BPF scheduler. During a fork, it
397 	 * will abort that specific fork.
398 	 */
399 	s32 (*init_task)(struct task_struct *p, struct scx_init_task_args *args);
400 
401 	/**
402 	 * exit_task - Exit a previously-running task from the system
403 	 * @p: task to exit
404 	 *
405 	 * @p is exiting or the BPF scheduler is being unloaded. Perform any
406 	 * necessary cleanup for @p.
407 	 */
408 	void (*exit_task)(struct task_struct *p, struct scx_exit_task_args *args);
409 
410 	/**
411 	 * enable - Enable BPF scheduling for a task
412 	 * @p: task to enable BPF scheduling for
413 	 *
414 	 * Enable @p for BPF scheduling. enable() is called on @p any time it
415 	 * enters SCX, and is always paired with a matching disable().
416 	 */
417 	void (*enable)(struct task_struct *p);
418 
419 	/**
420 	 * disable - Disable BPF scheduling for a task
421 	 * @p: task to disable BPF scheduling for
422 	 *
423 	 * @p is exiting, leaving SCX or the BPF scheduler is being unloaded.
424 	 * Disable BPF scheduling for @p. A disable() call is always matched
425 	 * with a prior enable() call.
426 	 */
427 	void (*disable)(struct task_struct *p);
428 
429 	/**
430 	 * dump - Dump BPF scheduler state on error
431 	 * @ctx: debug dump context
432 	 *
433 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump.
434 	 */
435 	void (*dump)(struct scx_dump_ctx *ctx);
436 
437 	/**
438 	 * dump_cpu - Dump BPF scheduler state for a CPU on error
439 	 * @ctx: debug dump context
440 	 * @cpu: CPU to generate debug dump for
441 	 * @idle: @cpu is currently idle without any runnable tasks
442 	 *
443 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
444 	 * @cpu. If @idle is %true and this operation doesn't produce any
445 	 * output, @cpu is skipped for dump.
446 	 */
447 	void (*dump_cpu)(struct scx_dump_ctx *ctx, s32 cpu, bool idle);
448 
449 	/**
450 	 * dump_task - Dump BPF scheduler state for a runnable task on error
451 	 * @ctx: debug dump context
452 	 * @p: runnable task to generate debug dump for
453 	 *
454 	 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for
455 	 * @p.
456 	 */
457 	void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p);
458 
459 	/*
460 	 * All online ops must come before ops.init().
461 	 */
462 
463 	/**
464 	 * init - Initialize the BPF scheduler
465 	 */
466 	s32 (*init)(void);
467 
468 	/**
469 	 * exit - Clean up after the BPF scheduler
470 	 * @info: Exit info
471 	 */
472 	void (*exit)(struct scx_exit_info *info);
473 
474 	/**
475 	 * dispatch_max_batch - Max nr of tasks that dispatch() can dispatch
476 	 */
477 	u32 dispatch_max_batch;
478 
479 	/**
480 	 * flags - %SCX_OPS_* flags
481 	 */
482 	u64 flags;
483 
484 	/**
485 	 * timeout_ms - The maximum amount of time, in milliseconds, that a
486 	 * runnable task should be able to wait before being scheduled. The
487 	 * maximum timeout may not exceed the default timeout of 30 seconds.
488 	 *
489 	 * Defaults to the maximum allowed timeout value of 30 seconds.
490 	 */
491 	u32 timeout_ms;
492 
493 	/**
494 	 * exit_dump_len - scx_exit_info.dump buffer length. If 0, the default
495 	 * value of 32768 is used.
496 	 */
497 	u32 exit_dump_len;
498 
499 	/**
500 	 * name - BPF scheduler's name
501 	 *
502 	 * Must be a non-zero valid BPF object name including only isalnum(),
503 	 * '_' and '.' chars. Shows up in kernel.sched_ext_ops sysctl while the
504 	 * BPF scheduler is enabled.
505 	 */
506 	char name[SCX_OPS_NAME_LEN];
507 };
508 
509 enum scx_opi {
510 	SCX_OPI_BEGIN			= 0,
511 	SCX_OPI_NORMAL_BEGIN		= 0,
512 	SCX_OPI_NORMAL_END		= SCX_OP_IDX(init),
513 	SCX_OPI_END			= SCX_OP_IDX(init),
514 };
515 
516 enum scx_wake_flags {
517 	/* expose select WF_* flags as enums */
518 	SCX_WAKE_FORK		= WF_FORK,
519 	SCX_WAKE_TTWU		= WF_TTWU,
520 	SCX_WAKE_SYNC		= WF_SYNC,
521 };
522 
523 enum scx_enq_flags {
524 	/* expose select ENQUEUE_* flags as enums */
525 	SCX_ENQ_WAKEUP		= ENQUEUE_WAKEUP,
526 	SCX_ENQ_HEAD		= ENQUEUE_HEAD,
527 
528 	/* high 32bits are SCX specific */
529 
530 	/*
531 	 * Set the following to trigger preemption when calling
532 	 * scx_bpf_dispatch() with a local dsq as the target. The slice of the
533 	 * current task is cleared to zero and the CPU is kicked into the
534 	 * scheduling path. Implies %SCX_ENQ_HEAD.
535 	 */
536 	SCX_ENQ_PREEMPT		= 1LLU << 32,
537 
538 	/*
539 	 * The task being enqueued was previously enqueued on the current CPU's
540 	 * %SCX_DSQ_LOCAL, but was removed from it in a call to the
541 	 * bpf_scx_reenqueue_local() kfunc. If bpf_scx_reenqueue_local() was
542 	 * invoked in a ->cpu_release() callback, and the task is again
543 	 * dispatched back to %SCX_LOCAL_DSQ by this current ->enqueue(), the
544 	 * task will not be scheduled on the CPU until at least the next invocation
545 	 * of the ->cpu_acquire() callback.
546 	 */
547 	SCX_ENQ_REENQ		= 1LLU << 40,
548 
549 	/*
550 	 * The task being enqueued is the only task available for the cpu. By
551 	 * default, ext core keeps executing such tasks but when
552 	 * %SCX_OPS_ENQ_LAST is specified, they're ops.enqueue()'d with the
553 	 * %SCX_ENQ_LAST flag set.
554 	 *
555 	 * If the BPF scheduler wants to continue executing the task,
556 	 * ops.enqueue() should dispatch the task to %SCX_DSQ_LOCAL immediately.
557 	 * If the task gets queued on a different dsq or the BPF side, the BPF
558 	 * scheduler is responsible for triggering a follow-up scheduling event.
559 	 * Otherwise, Execution may stall.
560 	 */
561 	SCX_ENQ_LAST		= 1LLU << 41,
562 
563 	/* high 8 bits are internal */
564 	__SCX_ENQ_INTERNAL_MASK	= 0xffLLU << 56,
565 
566 	SCX_ENQ_CLEAR_OPSS	= 1LLU << 56,
567 };
568 
569 enum scx_deq_flags {
570 	/* expose select DEQUEUE_* flags as enums */
571 	SCX_DEQ_SLEEP		= DEQUEUE_SLEEP,
572 };
573 
574 enum scx_pick_idle_cpu_flags {
575 	SCX_PICK_IDLE_CORE	= 1LLU << 0,	/* pick a CPU whose SMT siblings are also idle */
576 };
577 
578 enum scx_kick_flags {
579 	/*
580 	 * Kick the target CPU if idle. Guarantees that the target CPU goes
581 	 * through at least one full scheduling cycle before going idle. If the
582 	 * target CPU can be determined to be currently not idle and going to go
583 	 * through a scheduling cycle before going idle, noop.
584 	 */
585 	SCX_KICK_IDLE		= 1LLU << 0,
586 
587 	/*
588 	 * Preempt the current task and execute the dispatch path. If the
589 	 * current task of the target CPU is an SCX task, its ->scx.slice is
590 	 * cleared to zero before the scheduling path is invoked so that the
591 	 * task expires and the dispatch path is invoked.
592 	 */
593 	SCX_KICK_PREEMPT	= 1LLU << 1,
594 
595 	/*
596 	 * Wait for the CPU to be rescheduled. The scx_bpf_kick_cpu() call will
597 	 * return after the target CPU finishes picking the next task.
598 	 */
599 	SCX_KICK_WAIT		= 1LLU << 2,
600 };
601 
602 enum scx_ops_enable_state {
603 	SCX_OPS_PREPPING,
604 	SCX_OPS_ENABLING,
605 	SCX_OPS_ENABLED,
606 	SCX_OPS_DISABLING,
607 	SCX_OPS_DISABLED,
608 };
609 
610 static const char *scx_ops_enable_state_str[] = {
611 	[SCX_OPS_PREPPING]	= "prepping",
612 	[SCX_OPS_ENABLING]	= "enabling",
613 	[SCX_OPS_ENABLED]	= "enabled",
614 	[SCX_OPS_DISABLING]	= "disabling",
615 	[SCX_OPS_DISABLED]	= "disabled",
616 };
617 
618 /*
619  * sched_ext_entity->ops_state
620  *
621  * Used to track the task ownership between the SCX core and the BPF scheduler.
622  * State transitions look as follows:
623  *
624  * NONE -> QUEUEING -> QUEUED -> DISPATCHING
625  *   ^              |                 |
626  *   |              v                 v
627  *   \-------------------------------/
628  *
629  * QUEUEING and DISPATCHING states can be waited upon. See wait_ops_state() call
630  * sites for explanations on the conditions being waited upon and why they are
631  * safe. Transitions out of them into NONE or QUEUED must store_release and the
632  * waiters should load_acquire.
633  *
634  * Tracking scx_ops_state enables sched_ext core to reliably determine whether
635  * any given task can be dispatched by the BPF scheduler at all times and thus
636  * relaxes the requirements on the BPF scheduler. This allows the BPF scheduler
637  * to try to dispatch any task anytime regardless of its state as the SCX core
638  * can safely reject invalid dispatches.
639  */
640 enum scx_ops_state {
641 	SCX_OPSS_NONE,		/* owned by the SCX core */
642 	SCX_OPSS_QUEUEING,	/* in transit to the BPF scheduler */
643 	SCX_OPSS_QUEUED,	/* owned by the BPF scheduler */
644 	SCX_OPSS_DISPATCHING,	/* in transit back to the SCX core */
645 
646 	/*
647 	 * QSEQ brands each QUEUED instance so that, when dispatch races
648 	 * dequeue/requeue, the dispatcher can tell whether it still has a claim
649 	 * on the task being dispatched.
650 	 *
651 	 * As some 32bit archs can't do 64bit store_release/load_acquire,
652 	 * p->scx.ops_state is atomic_long_t which leaves 30 bits for QSEQ on
653 	 * 32bit machines. The dispatch race window QSEQ protects is very narrow
654 	 * and runs with IRQ disabled. 30 bits should be sufficient.
655 	 */
656 	SCX_OPSS_QSEQ_SHIFT	= 2,
657 };
658 
659 /* Use macros to ensure that the type is unsigned long for the masks */
660 #define SCX_OPSS_STATE_MASK	((1LU << SCX_OPSS_QSEQ_SHIFT) - 1)
661 #define SCX_OPSS_QSEQ_MASK	(~SCX_OPSS_STATE_MASK)
662 
663 /*
664  * During exit, a task may schedule after losing its PIDs. When disabling the
665  * BPF scheduler, we need to be able to iterate tasks in every state to
666  * guarantee system safety. Maintain a dedicated task list which contains every
667  * task between its fork and eventual free.
668  */
669 static DEFINE_SPINLOCK(scx_tasks_lock);
670 static LIST_HEAD(scx_tasks);
671 
672 /* ops enable/disable */
673 static struct kthread_worker *scx_ops_helper;
674 static DEFINE_MUTEX(scx_ops_enable_mutex);
675 DEFINE_STATIC_KEY_FALSE(__scx_ops_enabled);
676 DEFINE_STATIC_PERCPU_RWSEM(scx_fork_rwsem);
677 static atomic_t scx_ops_enable_state_var = ATOMIC_INIT(SCX_OPS_DISABLED);
678 static atomic_t scx_ops_bypass_depth = ATOMIC_INIT(0);
679 static bool scx_switching_all;
680 DEFINE_STATIC_KEY_FALSE(__scx_switched_all);
681 
682 static struct sched_ext_ops scx_ops;
683 static bool scx_warned_zero_slice;
684 
685 static DEFINE_STATIC_KEY_FALSE(scx_ops_enq_last);
686 static DEFINE_STATIC_KEY_FALSE(scx_ops_enq_exiting);
687 DEFINE_STATIC_KEY_FALSE(scx_ops_cpu_preempt);
688 static DEFINE_STATIC_KEY_FALSE(scx_builtin_idle_enabled);
689 
690 struct static_key_false scx_has_op[SCX_OPI_END] =
691 	{ [0 ... SCX_OPI_END-1] = STATIC_KEY_FALSE_INIT };
692 
693 static atomic_t scx_exit_kind = ATOMIC_INIT(SCX_EXIT_DONE);
694 static struct scx_exit_info *scx_exit_info;
695 
696 static atomic_long_t scx_nr_rejected = ATOMIC_LONG_INIT(0);
697 
698 /*
699  * The maximum amount of time in jiffies that a task may be runnable without
700  * being scheduled on a CPU. If this timeout is exceeded, it will trigger
701  * scx_ops_error().
702  */
703 static unsigned long scx_watchdog_timeout;
704 
705 /*
706  * The last time the delayed work was run. This delayed work relies on
707  * ksoftirqd being able to run to service timer interrupts, so it's possible
708  * that this work itself could get wedged. To account for this, we check that
709  * it's not stalled in the timer tick, and trigger an error if it is.
710  */
711 static unsigned long scx_watchdog_timestamp = INITIAL_JIFFIES;
712 
713 static struct delayed_work scx_watchdog_work;
714 
715 /* idle tracking */
716 #ifdef CONFIG_SMP
717 #ifdef CONFIG_CPUMASK_OFFSTACK
718 #define CL_ALIGNED_IF_ONSTACK
719 #else
720 #define CL_ALIGNED_IF_ONSTACK __cacheline_aligned_in_smp
721 #endif
722 
723 static struct {
724 	cpumask_var_t cpu;
725 	cpumask_var_t smt;
726 } idle_masks CL_ALIGNED_IF_ONSTACK;
727 
728 #endif	/* CONFIG_SMP */
729 
730 /* for %SCX_KICK_WAIT */
731 static unsigned long __percpu *scx_kick_cpus_pnt_seqs;
732 
733 /*
734  * Direct dispatch marker.
735  *
736  * Non-NULL values are used for direct dispatch from enqueue path. A valid
737  * pointer points to the task currently being enqueued. An ERR_PTR value is used
738  * to indicate that direct dispatch has already happened.
739  */
740 static DEFINE_PER_CPU(struct task_struct *, direct_dispatch_task);
741 
742 /* dispatch queues */
743 static struct scx_dispatch_q __cacheline_aligned_in_smp scx_dsq_global;
744 
745 static const struct rhashtable_params dsq_hash_params = {
746 	.key_len		= 8,
747 	.key_offset		= offsetof(struct scx_dispatch_q, id),
748 	.head_offset		= offsetof(struct scx_dispatch_q, hash_node),
749 };
750 
751 static struct rhashtable dsq_hash;
752 static LLIST_HEAD(dsqs_to_free);
753 
754 /* dispatch buf */
755 struct scx_dsp_buf_ent {
756 	struct task_struct	*task;
757 	unsigned long		qseq;
758 	u64			dsq_id;
759 	u64			enq_flags;
760 };
761 
762 static u32 scx_dsp_max_batch;
763 
764 struct scx_dsp_ctx {
765 	struct rq		*rq;
766 	struct rq_flags		*rf;
767 	u32			cursor;
768 	u32			nr_tasks;
769 	struct scx_dsp_buf_ent	buf[];
770 };
771 
772 static struct scx_dsp_ctx __percpu *scx_dsp_ctx;
773 
774 /* string formatting from BPF */
775 struct scx_bstr_buf {
776 	u64			data[MAX_BPRINTF_VARARGS];
777 	char			line[SCX_EXIT_MSG_LEN];
778 };
779 
780 static DEFINE_RAW_SPINLOCK(scx_exit_bstr_buf_lock);
781 static struct scx_bstr_buf scx_exit_bstr_buf;
782 
783 /* ops debug dump */
784 struct scx_dump_data {
785 	s32			cpu;
786 	bool			first;
787 	s32			cursor;
788 	struct seq_buf		*s;
789 	const char		*prefix;
790 	struct scx_bstr_buf	buf;
791 };
792 
793 struct scx_dump_data scx_dump_data = {
794 	.cpu			= -1,
795 };
796 
797 /* /sys/kernel/sched_ext interface */
798 static struct kset *scx_kset;
799 static struct kobject *scx_root_kobj;
800 
801 #define CREATE_TRACE_POINTS
802 #include <trace/events/sched_ext.h>
803 
804 static void scx_bpf_kick_cpu(s32 cpu, u64 flags);
805 static __printf(3, 4) void scx_ops_exit_kind(enum scx_exit_kind kind,
806 					     s64 exit_code,
807 					     const char *fmt, ...);
808 
809 #define scx_ops_error_kind(err, fmt, args...)					\
810 	scx_ops_exit_kind((err), 0, fmt, ##args)
811 
812 #define scx_ops_exit(code, fmt, args...)					\
813 	scx_ops_exit_kind(SCX_EXIT_UNREG_KERN, (code), fmt, ##args)
814 
815 #define scx_ops_error(fmt, args...)						\
816 	scx_ops_error_kind(SCX_EXIT_ERROR, fmt, ##args)
817 
818 #define SCX_HAS_OP(op)	static_branch_likely(&scx_has_op[SCX_OP_IDX(op)])
819 
820 static long jiffies_delta_msecs(unsigned long at, unsigned long now)
821 {
822 	if (time_after(at, now))
823 		return jiffies_to_msecs(at - now);
824 	else
825 		return -(long)jiffies_to_msecs(now - at);
826 }
827 
828 /* if the highest set bit is N, return a mask with bits [N+1, 31] set */
829 static u32 higher_bits(u32 flags)
830 {
831 	return ~((1 << fls(flags)) - 1);
832 }
833 
834 /* return the mask with only the highest bit set */
835 static u32 highest_bit(u32 flags)
836 {
837 	int bit = fls(flags);
838 	return ((u64)1 << bit) >> 1;
839 }
840 
841 /*
842  * scx_kf_mask enforcement. Some kfuncs can only be called from specific SCX
843  * ops. When invoking SCX ops, SCX_CALL_OP[_RET]() should be used to indicate
844  * the allowed kfuncs and those kfuncs should use scx_kf_allowed() to check
845  * whether it's running from an allowed context.
846  *
847  * @mask is constant, always inline to cull the mask calculations.
848  */
849 static __always_inline void scx_kf_allow(u32 mask)
850 {
851 	/* nesting is allowed only in increasing scx_kf_mask order */
852 	WARN_ONCE((mask | higher_bits(mask)) & current->scx.kf_mask,
853 		  "invalid nesting current->scx.kf_mask=0x%x mask=0x%x\n",
854 		  current->scx.kf_mask, mask);
855 	current->scx.kf_mask |= mask;
856 	barrier();
857 }
858 
859 static void scx_kf_disallow(u32 mask)
860 {
861 	barrier();
862 	current->scx.kf_mask &= ~mask;
863 }
864 
865 #define SCX_CALL_OP(mask, op, args...)						\
866 do {										\
867 	if (mask) {								\
868 		scx_kf_allow(mask);						\
869 		scx_ops.op(args);						\
870 		scx_kf_disallow(mask);						\
871 	} else {								\
872 		scx_ops.op(args);						\
873 	}									\
874 } while (0)
875 
876 #define SCX_CALL_OP_RET(mask, op, args...)					\
877 ({										\
878 	__typeof__(scx_ops.op(args)) __ret;					\
879 	if (mask) {								\
880 		scx_kf_allow(mask);						\
881 		__ret = scx_ops.op(args);					\
882 		scx_kf_disallow(mask);						\
883 	} else {								\
884 		__ret = scx_ops.op(args);					\
885 	}									\
886 	__ret;									\
887 })
888 
889 /*
890  * Some kfuncs are allowed only on the tasks that are subjects of the
891  * in-progress scx_ops operation for, e.g., locking guarantees. To enforce such
892  * restrictions, the following SCX_CALL_OP_*() variants should be used when
893  * invoking scx_ops operations that take task arguments. These can only be used
894  * for non-nesting operations due to the way the tasks are tracked.
895  *
896  * kfuncs which can only operate on such tasks can in turn use
897  * scx_kf_allowed_on_arg_tasks() to test whether the invocation is allowed on
898  * the specific task.
899  */
900 #define SCX_CALL_OP_TASK(mask, op, task, args...)				\
901 do {										\
902 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
903 	current->scx.kf_tasks[0] = task;					\
904 	SCX_CALL_OP(mask, op, task, ##args);					\
905 	current->scx.kf_tasks[0] = NULL;					\
906 } while (0)
907 
908 #define SCX_CALL_OP_TASK_RET(mask, op, task, args...)				\
909 ({										\
910 	__typeof__(scx_ops.op(task, ##args)) __ret;				\
911 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
912 	current->scx.kf_tasks[0] = task;					\
913 	__ret = SCX_CALL_OP_RET(mask, op, task, ##args);			\
914 	current->scx.kf_tasks[0] = NULL;					\
915 	__ret;									\
916 })
917 
918 #define SCX_CALL_OP_2TASKS_RET(mask, op, task0, task1, args...)			\
919 ({										\
920 	__typeof__(scx_ops.op(task0, task1, ##args)) __ret;			\
921 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
922 	current->scx.kf_tasks[0] = task0;					\
923 	current->scx.kf_tasks[1] = task1;					\
924 	__ret = SCX_CALL_OP_RET(mask, op, task0, task1, ##args);		\
925 	current->scx.kf_tasks[0] = NULL;					\
926 	current->scx.kf_tasks[1] = NULL;					\
927 	__ret;									\
928 })
929 
930 /* @mask is constant, always inline to cull unnecessary branches */
931 static __always_inline bool scx_kf_allowed(u32 mask)
932 {
933 	if (unlikely(!(current->scx.kf_mask & mask))) {
934 		scx_ops_error("kfunc with mask 0x%x called from an operation only allowing 0x%x",
935 			      mask, current->scx.kf_mask);
936 		return false;
937 	}
938 
939 	if (unlikely((mask & SCX_KF_SLEEPABLE) && in_interrupt())) {
940 		scx_ops_error("sleepable kfunc called from non-sleepable context");
941 		return false;
942 	}
943 
944 	/*
945 	 * Enforce nesting boundaries. e.g. A kfunc which can be called from
946 	 * DISPATCH must not be called if we're running DEQUEUE which is nested
947 	 * inside ops.dispatch(). We don't need to check the SCX_KF_SLEEPABLE
948 	 * boundary thanks to the above in_interrupt() check.
949 	 */
950 	if (unlikely(highest_bit(mask) == SCX_KF_CPU_RELEASE &&
951 		     (current->scx.kf_mask & higher_bits(SCX_KF_CPU_RELEASE)))) {
952 		scx_ops_error("cpu_release kfunc called from a nested operation");
953 		return false;
954 	}
955 
956 	if (unlikely(highest_bit(mask) == SCX_KF_DISPATCH &&
957 		     (current->scx.kf_mask & higher_bits(SCX_KF_DISPATCH)))) {
958 		scx_ops_error("dispatch kfunc called from a nested operation");
959 		return false;
960 	}
961 
962 	return true;
963 }
964 
965 /* see SCX_CALL_OP_TASK() */
966 static __always_inline bool scx_kf_allowed_on_arg_tasks(u32 mask,
967 							struct task_struct *p)
968 {
969 	if (!scx_kf_allowed(mask))
970 		return false;
971 
972 	if (unlikely((p != current->scx.kf_tasks[0] &&
973 		      p != current->scx.kf_tasks[1]))) {
974 		scx_ops_error("called on a task not being operated on");
975 		return false;
976 	}
977 
978 	return true;
979 }
980 
981 
982 /*
983  * SCX task iterator.
984  */
985 struct scx_task_iter {
986 	struct sched_ext_entity		cursor;
987 	struct task_struct		*locked;
988 	struct rq			*rq;
989 	struct rq_flags			rf;
990 };
991 
992 /**
993  * scx_task_iter_init - Initialize a task iterator
994  * @iter: iterator to init
995  *
996  * Initialize @iter. Must be called with scx_tasks_lock held. Once initialized,
997  * @iter must eventually be exited with scx_task_iter_exit().
998  *
999  * scx_tasks_lock may be released between this and the first next() call or
1000  * between any two next() calls. If scx_tasks_lock is released between two
1001  * next() calls, the caller is responsible for ensuring that the task being
1002  * iterated remains accessible either through RCU read lock or obtaining a
1003  * reference count.
1004  *
1005  * All tasks which existed when the iteration started are guaranteed to be
1006  * visited as long as they still exist.
1007  */
1008 static void scx_task_iter_init(struct scx_task_iter *iter)
1009 {
1010 	lockdep_assert_held(&scx_tasks_lock);
1011 
1012 	iter->cursor = (struct sched_ext_entity){ .flags = SCX_TASK_CURSOR };
1013 	list_add(&iter->cursor.tasks_node, &scx_tasks);
1014 	iter->locked = NULL;
1015 }
1016 
1017 /**
1018  * scx_task_iter_rq_unlock - Unlock rq locked by a task iterator
1019  * @iter: iterator to unlock rq for
1020  *
1021  * If @iter is in the middle of a locked iteration, it may be locking the rq of
1022  * the task currently being visited. Unlock the rq if so. This function can be
1023  * safely called anytime during an iteration.
1024  *
1025  * Returns %true if the rq @iter was locking is unlocked. %false if @iter was
1026  * not locking an rq.
1027  */
1028 static bool scx_task_iter_rq_unlock(struct scx_task_iter *iter)
1029 {
1030 	if (iter->locked) {
1031 		task_rq_unlock(iter->rq, iter->locked, &iter->rf);
1032 		iter->locked = NULL;
1033 		return true;
1034 	} else {
1035 		return false;
1036 	}
1037 }
1038 
1039 /**
1040  * scx_task_iter_exit - Exit a task iterator
1041  * @iter: iterator to exit
1042  *
1043  * Exit a previously initialized @iter. Must be called with scx_tasks_lock held.
1044  * If the iterator holds a task's rq lock, that rq lock is released. See
1045  * scx_task_iter_init() for details.
1046  */
1047 static void scx_task_iter_exit(struct scx_task_iter *iter)
1048 {
1049 	lockdep_assert_held(&scx_tasks_lock);
1050 
1051 	scx_task_iter_rq_unlock(iter);
1052 	list_del_init(&iter->cursor.tasks_node);
1053 }
1054 
1055 /**
1056  * scx_task_iter_next - Next task
1057  * @iter: iterator to walk
1058  *
1059  * Visit the next task. See scx_task_iter_init() for details.
1060  */
1061 static struct task_struct *scx_task_iter_next(struct scx_task_iter *iter)
1062 {
1063 	struct list_head *cursor = &iter->cursor.tasks_node;
1064 	struct sched_ext_entity *pos;
1065 
1066 	lockdep_assert_held(&scx_tasks_lock);
1067 
1068 	list_for_each_entry(pos, cursor, tasks_node) {
1069 		if (&pos->tasks_node == &scx_tasks)
1070 			return NULL;
1071 		if (!(pos->flags & SCX_TASK_CURSOR)) {
1072 			list_move(cursor, &pos->tasks_node);
1073 			return container_of(pos, struct task_struct, scx);
1074 		}
1075 	}
1076 
1077 	/* can't happen, should always terminate at scx_tasks above */
1078 	BUG();
1079 }
1080 
1081 /**
1082  * scx_task_iter_next_locked - Next non-idle task with its rq locked
1083  * @iter: iterator to walk
1084  * @include_dead: Whether we should include dead tasks in the iteration
1085  *
1086  * Visit the non-idle task with its rq lock held. Allows callers to specify
1087  * whether they would like to filter out dead tasks. See scx_task_iter_init()
1088  * for details.
1089  */
1090 static struct task_struct *
1091 scx_task_iter_next_locked(struct scx_task_iter *iter, bool include_dead)
1092 {
1093 	struct task_struct *p;
1094 retry:
1095 	scx_task_iter_rq_unlock(iter);
1096 
1097 	while ((p = scx_task_iter_next(iter))) {
1098 		/*
1099 		 * is_idle_task() tests %PF_IDLE which may not be set for CPUs
1100 		 * which haven't yet been onlined. Test sched_class directly.
1101 		 */
1102 		if (p->sched_class != &idle_sched_class)
1103 			break;
1104 	}
1105 	if (!p)
1106 		return NULL;
1107 
1108 	iter->rq = task_rq_lock(p, &iter->rf);
1109 	iter->locked = p;
1110 
1111 	/*
1112 	 * If we see %TASK_DEAD, @p already disabled preemption, is about to do
1113 	 * the final __schedule(), won't ever need to be scheduled again and can
1114 	 * thus be safely ignored. If we don't see %TASK_DEAD, @p can't enter
1115 	 * the final __schedle() while we're locking its rq and thus will stay
1116 	 * alive until the rq is unlocked.
1117 	 */
1118 	if (!include_dead && READ_ONCE(p->__state) == TASK_DEAD)
1119 		goto retry;
1120 
1121 	return p;
1122 }
1123 
1124 static enum scx_ops_enable_state scx_ops_enable_state(void)
1125 {
1126 	return atomic_read(&scx_ops_enable_state_var);
1127 }
1128 
1129 static enum scx_ops_enable_state
1130 scx_ops_set_enable_state(enum scx_ops_enable_state to)
1131 {
1132 	return atomic_xchg(&scx_ops_enable_state_var, to);
1133 }
1134 
1135 static bool scx_ops_tryset_enable_state(enum scx_ops_enable_state to,
1136 					enum scx_ops_enable_state from)
1137 {
1138 	int from_v = from;
1139 
1140 	return atomic_try_cmpxchg(&scx_ops_enable_state_var, &from_v, to);
1141 }
1142 
1143 static bool scx_ops_bypassing(void)
1144 {
1145 	return unlikely(atomic_read(&scx_ops_bypass_depth));
1146 }
1147 
1148 /**
1149  * wait_ops_state - Busy-wait the specified ops state to end
1150  * @p: target task
1151  * @opss: state to wait the end of
1152  *
1153  * Busy-wait for @p to transition out of @opss. This can only be used when the
1154  * state part of @opss is %SCX_QUEUEING or %SCX_DISPATCHING. This function also
1155  * has load_acquire semantics to ensure that the caller can see the updates made
1156  * in the enqueueing and dispatching paths.
1157  */
1158 static void wait_ops_state(struct task_struct *p, unsigned long opss)
1159 {
1160 	do {
1161 		cpu_relax();
1162 	} while (atomic_long_read_acquire(&p->scx.ops_state) == opss);
1163 }
1164 
1165 /**
1166  * ops_cpu_valid - Verify a cpu number
1167  * @cpu: cpu number which came from a BPF ops
1168  * @where: extra information reported on error
1169  *
1170  * @cpu is a cpu number which came from the BPF scheduler and can be any value.
1171  * Verify that it is in range and one of the possible cpus. If invalid, trigger
1172  * an ops error.
1173  */
1174 static bool ops_cpu_valid(s32 cpu, const char *where)
1175 {
1176 	if (likely(cpu >= 0 && cpu < nr_cpu_ids && cpu_possible(cpu))) {
1177 		return true;
1178 	} else {
1179 		scx_ops_error("invalid CPU %d%s%s", cpu,
1180 			      where ? " " : "", where ?: "");
1181 		return false;
1182 	}
1183 }
1184 
1185 /**
1186  * ops_sanitize_err - Sanitize a -errno value
1187  * @ops_name: operation to blame on failure
1188  * @err: -errno value to sanitize
1189  *
1190  * Verify @err is a valid -errno. If not, trigger scx_ops_error() and return
1191  * -%EPROTO. This is necessary because returning a rogue -errno up the chain can
1192  * cause misbehaviors. For an example, a large negative return from
1193  * ops.init_task() triggers an oops when passed up the call chain because the
1194  * value fails IS_ERR() test after being encoded with ERR_PTR() and then is
1195  * handled as a pointer.
1196  */
1197 static int ops_sanitize_err(const char *ops_name, s32 err)
1198 {
1199 	if (err < 0 && err >= -MAX_ERRNO)
1200 		return err;
1201 
1202 	scx_ops_error("ops.%s() returned an invalid errno %d", ops_name, err);
1203 	return -EPROTO;
1204 }
1205 
1206 static void update_curr_scx(struct rq *rq)
1207 {
1208 	struct task_struct *curr = rq->curr;
1209 	u64 now = rq_clock_task(rq);
1210 	u64 delta_exec;
1211 
1212 	if (time_before_eq64(now, curr->se.exec_start))
1213 		return;
1214 
1215 	delta_exec = now - curr->se.exec_start;
1216 	curr->se.exec_start = now;
1217 	curr->se.sum_exec_runtime += delta_exec;
1218 	account_group_exec_runtime(curr, delta_exec);
1219 	cgroup_account_cputime(curr, delta_exec);
1220 
1221 	if (curr->scx.slice != SCX_SLICE_INF)
1222 		curr->scx.slice -= min(curr->scx.slice, delta_exec);
1223 }
1224 
1225 static void dsq_mod_nr(struct scx_dispatch_q *dsq, s32 delta)
1226 {
1227 	/* scx_bpf_dsq_nr_queued() reads ->nr without locking, use WRITE_ONCE() */
1228 	WRITE_ONCE(dsq->nr, dsq->nr + delta);
1229 }
1230 
1231 static void dispatch_enqueue(struct scx_dispatch_q *dsq, struct task_struct *p,
1232 			     u64 enq_flags)
1233 {
1234 	bool is_local = dsq->id == SCX_DSQ_LOCAL;
1235 
1236 	WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_node));
1237 
1238 	if (!is_local) {
1239 		raw_spin_lock(&dsq->lock);
1240 		if (unlikely(dsq->id == SCX_DSQ_INVALID)) {
1241 			scx_ops_error("attempting to dispatch to a destroyed dsq");
1242 			/* fall back to the global dsq */
1243 			raw_spin_unlock(&dsq->lock);
1244 			dsq = &scx_dsq_global;
1245 			raw_spin_lock(&dsq->lock);
1246 		}
1247 	}
1248 
1249 	if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT))
1250 		list_add(&p->scx.dsq_node, &dsq->list);
1251 	else
1252 		list_add_tail(&p->scx.dsq_node, &dsq->list);
1253 
1254 	dsq_mod_nr(dsq, 1);
1255 	p->scx.dsq = dsq;
1256 
1257 	/*
1258 	 * scx.ddsp_dsq_id and scx.ddsp_enq_flags are only relevant on the
1259 	 * direct dispatch path, but we clear them here because the direct
1260 	 * dispatch verdict may be overridden on the enqueue path during e.g.
1261 	 * bypass.
1262 	 */
1263 	p->scx.ddsp_dsq_id = SCX_DSQ_INVALID;
1264 	p->scx.ddsp_enq_flags = 0;
1265 
1266 	/*
1267 	 * We're transitioning out of QUEUEING or DISPATCHING. store_release to
1268 	 * match waiters' load_acquire.
1269 	 */
1270 	if (enq_flags & SCX_ENQ_CLEAR_OPSS)
1271 		atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1272 
1273 	if (is_local) {
1274 		struct rq *rq = container_of(dsq, struct rq, scx.local_dsq);
1275 		bool preempt = false;
1276 
1277 		if ((enq_flags & SCX_ENQ_PREEMPT) && p != rq->curr &&
1278 		    rq->curr->sched_class == &ext_sched_class) {
1279 			rq->curr->scx.slice = 0;
1280 			preempt = true;
1281 		}
1282 
1283 		if (preempt || sched_class_above(&ext_sched_class,
1284 						 rq->curr->sched_class))
1285 			resched_curr(rq);
1286 	} else {
1287 		raw_spin_unlock(&dsq->lock);
1288 	}
1289 }
1290 
1291 static void dispatch_dequeue(struct rq *rq, struct task_struct *p)
1292 {
1293 	struct scx_dispatch_q *dsq = p->scx.dsq;
1294 	bool is_local = dsq == &rq->scx.local_dsq;
1295 
1296 	if (!dsq) {
1297 		WARN_ON_ONCE(!list_empty(&p->scx.dsq_node));
1298 		/*
1299 		 * When dispatching directly from the BPF scheduler to a local
1300 		 * DSQ, the task isn't associated with any DSQ but
1301 		 * @p->scx.holding_cpu may be set under the protection of
1302 		 * %SCX_OPSS_DISPATCHING.
1303 		 */
1304 		if (p->scx.holding_cpu >= 0)
1305 			p->scx.holding_cpu = -1;
1306 		return;
1307 	}
1308 
1309 	if (!is_local)
1310 		raw_spin_lock(&dsq->lock);
1311 
1312 	/*
1313 	 * Now that we hold @dsq->lock, @p->holding_cpu and @p->scx.dsq_node
1314 	 * can't change underneath us.
1315 	*/
1316 	if (p->scx.holding_cpu < 0) {
1317 		/* @p must still be on @dsq, dequeue */
1318 		WARN_ON_ONCE(list_empty(&p->scx.dsq_node));
1319 		list_del_init(&p->scx.dsq_node);
1320 		dsq_mod_nr(dsq, -1);
1321 	} else {
1322 		/*
1323 		 * We're racing against dispatch_to_local_dsq() which already
1324 		 * removed @p from @dsq and set @p->scx.holding_cpu. Clear the
1325 		 * holding_cpu which tells dispatch_to_local_dsq() that it lost
1326 		 * the race.
1327 		 */
1328 		WARN_ON_ONCE(!list_empty(&p->scx.dsq_node));
1329 		p->scx.holding_cpu = -1;
1330 	}
1331 	p->scx.dsq = NULL;
1332 
1333 	if (!is_local)
1334 		raw_spin_unlock(&dsq->lock);
1335 }
1336 
1337 static struct scx_dispatch_q *find_user_dsq(u64 dsq_id)
1338 {
1339 	return rhashtable_lookup_fast(&dsq_hash, &dsq_id, dsq_hash_params);
1340 }
1341 
1342 static struct scx_dispatch_q *find_non_local_dsq(u64 dsq_id)
1343 {
1344 	lockdep_assert(rcu_read_lock_any_held());
1345 
1346 	if (dsq_id == SCX_DSQ_GLOBAL)
1347 		return &scx_dsq_global;
1348 	else
1349 		return find_user_dsq(dsq_id);
1350 }
1351 
1352 static struct scx_dispatch_q *find_dsq_for_dispatch(struct rq *rq, u64 dsq_id,
1353 						    struct task_struct *p)
1354 {
1355 	struct scx_dispatch_q *dsq;
1356 
1357 	if (dsq_id == SCX_DSQ_LOCAL)
1358 		return &rq->scx.local_dsq;
1359 
1360 	dsq = find_non_local_dsq(dsq_id);
1361 	if (unlikely(!dsq)) {
1362 		scx_ops_error("non-existent DSQ 0x%llx for %s[%d]",
1363 			      dsq_id, p->comm, p->pid);
1364 		return &scx_dsq_global;
1365 	}
1366 
1367 	return dsq;
1368 }
1369 
1370 static void mark_direct_dispatch(struct task_struct *ddsp_task,
1371 				 struct task_struct *p, u64 dsq_id,
1372 				 u64 enq_flags)
1373 {
1374 	/*
1375 	 * Mark that dispatch already happened from ops.select_cpu() or
1376 	 * ops.enqueue() by spoiling direct_dispatch_task with a non-NULL value
1377 	 * which can never match a valid task pointer.
1378 	 */
1379 	__this_cpu_write(direct_dispatch_task, ERR_PTR(-ESRCH));
1380 
1381 	/* @p must match the task on the enqueue path */
1382 	if (unlikely(p != ddsp_task)) {
1383 		if (IS_ERR(ddsp_task))
1384 			scx_ops_error("%s[%d] already direct-dispatched",
1385 				      p->comm, p->pid);
1386 		else
1387 			scx_ops_error("scheduling for %s[%d] but trying to direct-dispatch %s[%d]",
1388 				      ddsp_task->comm, ddsp_task->pid,
1389 				      p->comm, p->pid);
1390 		return;
1391 	}
1392 
1393 	/*
1394 	 * %SCX_DSQ_LOCAL_ON is not supported during direct dispatch because
1395 	 * dispatching to the local DSQ of a different CPU requires unlocking
1396 	 * the current rq which isn't allowed in the enqueue path. Use
1397 	 * ops.select_cpu() to be on the target CPU and then %SCX_DSQ_LOCAL.
1398 	 */
1399 	if (unlikely((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON)) {
1400 		scx_ops_error("SCX_DSQ_LOCAL_ON can't be used for direct-dispatch");
1401 		return;
1402 	}
1403 
1404 	WARN_ON_ONCE(p->scx.ddsp_dsq_id != SCX_DSQ_INVALID);
1405 	WARN_ON_ONCE(p->scx.ddsp_enq_flags);
1406 
1407 	p->scx.ddsp_dsq_id = dsq_id;
1408 	p->scx.ddsp_enq_flags = enq_flags;
1409 }
1410 
1411 static void direct_dispatch(struct task_struct *p, u64 enq_flags)
1412 {
1413 	struct scx_dispatch_q *dsq;
1414 
1415 	enq_flags |= (p->scx.ddsp_enq_flags | SCX_ENQ_CLEAR_OPSS);
1416 	dsq = find_dsq_for_dispatch(task_rq(p), p->scx.ddsp_dsq_id, p);
1417 	dispatch_enqueue(dsq, p, enq_flags);
1418 }
1419 
1420 static bool scx_rq_online(struct rq *rq)
1421 {
1422 #ifdef CONFIG_SMP
1423 	return likely(rq->online);
1424 #else
1425 	return true;
1426 #endif
1427 }
1428 
1429 static void do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags,
1430 			    int sticky_cpu)
1431 {
1432 	struct task_struct **ddsp_taskp;
1433 	unsigned long qseq;
1434 
1435 	WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_QUEUED));
1436 
1437 	/* rq migration */
1438 	if (sticky_cpu == cpu_of(rq))
1439 		goto local_norefill;
1440 
1441 	if (!scx_rq_online(rq))
1442 		goto local;
1443 
1444 	if (scx_ops_bypassing()) {
1445 		if (enq_flags & SCX_ENQ_LAST)
1446 			goto local;
1447 		else
1448 			goto global;
1449 	}
1450 
1451 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
1452 		goto direct;
1453 
1454 	/* see %SCX_OPS_ENQ_EXITING */
1455 	if (!static_branch_unlikely(&scx_ops_enq_exiting) &&
1456 	    unlikely(p->flags & PF_EXITING))
1457 		goto local;
1458 
1459 	/* see %SCX_OPS_ENQ_LAST */
1460 	if (!static_branch_unlikely(&scx_ops_enq_last) &&
1461 	    (enq_flags & SCX_ENQ_LAST))
1462 		goto local;
1463 
1464 	if (!SCX_HAS_OP(enqueue))
1465 		goto global;
1466 
1467 	/* DSQ bypass didn't trigger, enqueue on the BPF scheduler */
1468 	qseq = rq->scx.ops_qseq++ << SCX_OPSS_QSEQ_SHIFT;
1469 
1470 	WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
1471 	atomic_long_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq);
1472 
1473 	ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
1474 	WARN_ON_ONCE(*ddsp_taskp);
1475 	*ddsp_taskp = p;
1476 
1477 	SCX_CALL_OP_TASK(SCX_KF_ENQUEUE, enqueue, p, enq_flags);
1478 
1479 	*ddsp_taskp = NULL;
1480 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
1481 		goto direct;
1482 
1483 	/*
1484 	 * If not directly dispatched, QUEUEING isn't clear yet and dispatch or
1485 	 * dequeue may be waiting. The store_release matches their load_acquire.
1486 	 */
1487 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_QUEUED | qseq);
1488 	return;
1489 
1490 direct:
1491 	direct_dispatch(p, enq_flags);
1492 	return;
1493 
1494 local:
1495 	p->scx.slice = SCX_SLICE_DFL;
1496 local_norefill:
1497 	dispatch_enqueue(&rq->scx.local_dsq, p, enq_flags);
1498 	return;
1499 
1500 global:
1501 	p->scx.slice = SCX_SLICE_DFL;
1502 	dispatch_enqueue(&scx_dsq_global, p, enq_flags);
1503 }
1504 
1505 static bool task_runnable(const struct task_struct *p)
1506 {
1507 	return !list_empty(&p->scx.runnable_node);
1508 }
1509 
1510 static void set_task_runnable(struct rq *rq, struct task_struct *p)
1511 {
1512 	lockdep_assert_rq_held(rq);
1513 
1514 	if (p->scx.flags & SCX_TASK_RESET_RUNNABLE_AT) {
1515 		p->scx.runnable_at = jiffies;
1516 		p->scx.flags &= ~SCX_TASK_RESET_RUNNABLE_AT;
1517 	}
1518 
1519 	/*
1520 	 * list_add_tail() must be used. scx_ops_bypass() depends on tasks being
1521 	 * appened to the runnable_list.
1522 	 */
1523 	list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list);
1524 }
1525 
1526 static void clr_task_runnable(struct task_struct *p, bool reset_runnable_at)
1527 {
1528 	list_del_init(&p->scx.runnable_node);
1529 	if (reset_runnable_at)
1530 		p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
1531 }
1532 
1533 static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int enq_flags)
1534 {
1535 	int sticky_cpu = p->scx.sticky_cpu;
1536 
1537 	enq_flags |= rq->scx.extra_enq_flags;
1538 
1539 	if (sticky_cpu >= 0)
1540 		p->scx.sticky_cpu = -1;
1541 
1542 	/*
1543 	 * Restoring a running task will be immediately followed by
1544 	 * set_next_task_scx() which expects the task to not be on the BPF
1545 	 * scheduler as tasks can only start running through local DSQs. Force
1546 	 * direct-dispatch into the local DSQ by setting the sticky_cpu.
1547 	 */
1548 	if (unlikely(enq_flags & ENQUEUE_RESTORE) && task_current(rq, p))
1549 		sticky_cpu = cpu_of(rq);
1550 
1551 	if (p->scx.flags & SCX_TASK_QUEUED) {
1552 		WARN_ON_ONCE(!task_runnable(p));
1553 		return;
1554 	}
1555 
1556 	set_task_runnable(rq, p);
1557 	p->scx.flags |= SCX_TASK_QUEUED;
1558 	rq->scx.nr_running++;
1559 	add_nr_running(rq, 1);
1560 
1561 	if (SCX_HAS_OP(runnable))
1562 		SCX_CALL_OP_TASK(SCX_KF_REST, runnable, p, enq_flags);
1563 
1564 	do_enqueue_task(rq, p, enq_flags, sticky_cpu);
1565 }
1566 
1567 static void ops_dequeue(struct task_struct *p, u64 deq_flags)
1568 {
1569 	unsigned long opss;
1570 
1571 	/* dequeue is always temporary, don't reset runnable_at */
1572 	clr_task_runnable(p, false);
1573 
1574 	/* acquire ensures that we see the preceding updates on QUEUED */
1575 	opss = atomic_long_read_acquire(&p->scx.ops_state);
1576 
1577 	switch (opss & SCX_OPSS_STATE_MASK) {
1578 	case SCX_OPSS_NONE:
1579 		break;
1580 	case SCX_OPSS_QUEUEING:
1581 		/*
1582 		 * QUEUEING is started and finished while holding @p's rq lock.
1583 		 * As we're holding the rq lock now, we shouldn't see QUEUEING.
1584 		 */
1585 		BUG();
1586 	case SCX_OPSS_QUEUED:
1587 		if (SCX_HAS_OP(dequeue))
1588 			SCX_CALL_OP_TASK(SCX_KF_REST, dequeue, p, deq_flags);
1589 
1590 		if (atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
1591 					    SCX_OPSS_NONE))
1592 			break;
1593 		fallthrough;
1594 	case SCX_OPSS_DISPATCHING:
1595 		/*
1596 		 * If @p is being dispatched from the BPF scheduler to a DSQ,
1597 		 * wait for the transfer to complete so that @p doesn't get
1598 		 * added to its DSQ after dequeueing is complete.
1599 		 *
1600 		 * As we're waiting on DISPATCHING with the rq locked, the
1601 		 * dispatching side shouldn't try to lock the rq while
1602 		 * DISPATCHING is set. See dispatch_to_local_dsq().
1603 		 *
1604 		 * DISPATCHING shouldn't have qseq set and control can reach
1605 		 * here with NONE @opss from the above QUEUED case block.
1606 		 * Explicitly wait on %SCX_OPSS_DISPATCHING instead of @opss.
1607 		 */
1608 		wait_ops_state(p, SCX_OPSS_DISPATCHING);
1609 		BUG_ON(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
1610 		break;
1611 	}
1612 }
1613 
1614 static void dequeue_task_scx(struct rq *rq, struct task_struct *p, int deq_flags)
1615 {
1616 	if (!(p->scx.flags & SCX_TASK_QUEUED)) {
1617 		WARN_ON_ONCE(task_runnable(p));
1618 		return;
1619 	}
1620 
1621 	ops_dequeue(p, deq_flags);
1622 
1623 	/*
1624 	 * A currently running task which is going off @rq first gets dequeued
1625 	 * and then stops running. As we want running <-> stopping transitions
1626 	 * to be contained within runnable <-> quiescent transitions, trigger
1627 	 * ->stopping() early here instead of in put_prev_task_scx().
1628 	 *
1629 	 * @p may go through multiple stopping <-> running transitions between
1630 	 * here and put_prev_task_scx() if task attribute changes occur while
1631 	 * balance_scx() leaves @rq unlocked. However, they don't contain any
1632 	 * information meaningful to the BPF scheduler and can be suppressed by
1633 	 * skipping the callbacks if the task is !QUEUED.
1634 	 */
1635 	if (SCX_HAS_OP(stopping) && task_current(rq, p)) {
1636 		update_curr_scx(rq);
1637 		SCX_CALL_OP_TASK(SCX_KF_REST, stopping, p, false);
1638 	}
1639 
1640 	if (SCX_HAS_OP(quiescent))
1641 		SCX_CALL_OP_TASK(SCX_KF_REST, quiescent, p, deq_flags);
1642 
1643 	if (deq_flags & SCX_DEQ_SLEEP)
1644 		p->scx.flags |= SCX_TASK_DEQD_FOR_SLEEP;
1645 	else
1646 		p->scx.flags &= ~SCX_TASK_DEQD_FOR_SLEEP;
1647 
1648 	p->scx.flags &= ~SCX_TASK_QUEUED;
1649 	rq->scx.nr_running--;
1650 	sub_nr_running(rq, 1);
1651 
1652 	dispatch_dequeue(rq, p);
1653 }
1654 
1655 static void yield_task_scx(struct rq *rq)
1656 {
1657 	struct task_struct *p = rq->curr;
1658 
1659 	if (SCX_HAS_OP(yield))
1660 		SCX_CALL_OP_2TASKS_RET(SCX_KF_REST, yield, p, NULL);
1661 	else
1662 		p->scx.slice = 0;
1663 }
1664 
1665 static bool yield_to_task_scx(struct rq *rq, struct task_struct *to)
1666 {
1667 	struct task_struct *from = rq->curr;
1668 
1669 	if (SCX_HAS_OP(yield))
1670 		return SCX_CALL_OP_2TASKS_RET(SCX_KF_REST, yield, from, to);
1671 	else
1672 		return false;
1673 }
1674 
1675 #ifdef CONFIG_SMP
1676 /**
1677  * move_task_to_local_dsq - Move a task from a different rq to a local DSQ
1678  * @rq: rq to move the task into, currently locked
1679  * @p: task to move
1680  * @enq_flags: %SCX_ENQ_*
1681  *
1682  * Move @p which is currently on a different rq to @rq's local DSQ. The caller
1683  * must:
1684  *
1685  * 1. Start with exclusive access to @p either through its DSQ lock or
1686  *    %SCX_OPSS_DISPATCHING flag.
1687  *
1688  * 2. Set @p->scx.holding_cpu to raw_smp_processor_id().
1689  *
1690  * 3. Remember task_rq(@p). Release the exclusive access so that we don't
1691  *    deadlock with dequeue.
1692  *
1693  * 4. Lock @rq and the task_rq from #3.
1694  *
1695  * 5. Call this function.
1696  *
1697  * Returns %true if @p was successfully moved. %false after racing dequeue and
1698  * losing.
1699  */
1700 static bool move_task_to_local_dsq(struct rq *rq, struct task_struct *p,
1701 				   u64 enq_flags)
1702 {
1703 	struct rq *task_rq;
1704 
1705 	lockdep_assert_rq_held(rq);
1706 
1707 	/*
1708 	 * If dequeue got to @p while we were trying to lock both rq's, it'd
1709 	 * have cleared @p->scx.holding_cpu to -1. While other cpus may have
1710 	 * updated it to different values afterwards, as this operation can't be
1711 	 * preempted or recurse, @p->scx.holding_cpu can never become
1712 	 * raw_smp_processor_id() again before we're done. Thus, we can tell
1713 	 * whether we lost to dequeue by testing whether @p->scx.holding_cpu is
1714 	 * still raw_smp_processor_id().
1715 	 *
1716 	 * See dispatch_dequeue() for the counterpart.
1717 	 */
1718 	if (unlikely(p->scx.holding_cpu != raw_smp_processor_id()))
1719 		return false;
1720 
1721 	/* @p->rq couldn't have changed if we're still the holding cpu */
1722 	task_rq = task_rq(p);
1723 	lockdep_assert_rq_held(task_rq);
1724 
1725 	WARN_ON_ONCE(!cpumask_test_cpu(cpu_of(rq), p->cpus_ptr));
1726 	deactivate_task(task_rq, p, 0);
1727 	set_task_cpu(p, cpu_of(rq));
1728 	p->scx.sticky_cpu = cpu_of(rq);
1729 
1730 	/*
1731 	 * We want to pass scx-specific enq_flags but activate_task() will
1732 	 * truncate the upper 32 bit. As we own @rq, we can pass them through
1733 	 * @rq->scx.extra_enq_flags instead.
1734 	 */
1735 	WARN_ON_ONCE(rq->scx.extra_enq_flags);
1736 	rq->scx.extra_enq_flags = enq_flags;
1737 	activate_task(rq, p, 0);
1738 	rq->scx.extra_enq_flags = 0;
1739 
1740 	return true;
1741 }
1742 
1743 /**
1744  * dispatch_to_local_dsq_lock - Ensure source and destination rq's are locked
1745  * @rq: current rq which is locked
1746  * @rf: rq_flags to use when unlocking @rq
1747  * @src_rq: rq to move task from
1748  * @dst_rq: rq to move task to
1749  *
1750  * We're holding @rq lock and trying to dispatch a task from @src_rq to
1751  * @dst_rq's local DSQ and thus need to lock both @src_rq and @dst_rq. Whether
1752  * @rq stays locked isn't important as long as the state is restored after
1753  * dispatch_to_local_dsq_unlock().
1754  */
1755 static void dispatch_to_local_dsq_lock(struct rq *rq, struct rq_flags *rf,
1756 				       struct rq *src_rq, struct rq *dst_rq)
1757 {
1758 	rq_unpin_lock(rq, rf);
1759 
1760 	if (src_rq == dst_rq) {
1761 		raw_spin_rq_unlock(rq);
1762 		raw_spin_rq_lock(dst_rq);
1763 	} else if (rq == src_rq) {
1764 		double_lock_balance(rq, dst_rq);
1765 		rq_repin_lock(rq, rf);
1766 	} else if (rq == dst_rq) {
1767 		double_lock_balance(rq, src_rq);
1768 		rq_repin_lock(rq, rf);
1769 	} else {
1770 		raw_spin_rq_unlock(rq);
1771 		double_rq_lock(src_rq, dst_rq);
1772 	}
1773 }
1774 
1775 /**
1776  * dispatch_to_local_dsq_unlock - Undo dispatch_to_local_dsq_lock()
1777  * @rq: current rq which is locked
1778  * @rf: rq_flags to use when unlocking @rq
1779  * @src_rq: rq to move task from
1780  * @dst_rq: rq to move task to
1781  *
1782  * Unlock @src_rq and @dst_rq and ensure that @rq is locked on return.
1783  */
1784 static void dispatch_to_local_dsq_unlock(struct rq *rq, struct rq_flags *rf,
1785 					 struct rq *src_rq, struct rq *dst_rq)
1786 {
1787 	if (src_rq == dst_rq) {
1788 		raw_spin_rq_unlock(dst_rq);
1789 		raw_spin_rq_lock(rq);
1790 		rq_repin_lock(rq, rf);
1791 	} else if (rq == src_rq) {
1792 		double_unlock_balance(rq, dst_rq);
1793 	} else if (rq == dst_rq) {
1794 		double_unlock_balance(rq, src_rq);
1795 	} else {
1796 		double_rq_unlock(src_rq, dst_rq);
1797 		raw_spin_rq_lock(rq);
1798 		rq_repin_lock(rq, rf);
1799 	}
1800 }
1801 #endif	/* CONFIG_SMP */
1802 
1803 static void consume_local_task(struct rq *rq, struct scx_dispatch_q *dsq,
1804 			       struct task_struct *p)
1805 {
1806 	lockdep_assert_held(&dsq->lock);	/* released on return */
1807 
1808 	/* @dsq is locked and @p is on this rq */
1809 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
1810 	list_move_tail(&p->scx.dsq_node, &rq->scx.local_dsq.list);
1811 	dsq_mod_nr(dsq, -1);
1812 	dsq_mod_nr(&rq->scx.local_dsq, 1);
1813 	p->scx.dsq = &rq->scx.local_dsq;
1814 	raw_spin_unlock(&dsq->lock);
1815 }
1816 
1817 #ifdef CONFIG_SMP
1818 /*
1819  * Similar to kernel/sched/core.c::is_cpu_allowed() but we're testing whether @p
1820  * can be pulled to @rq.
1821  */
1822 static bool task_can_run_on_remote_rq(struct task_struct *p, struct rq *rq)
1823 {
1824 	int cpu = cpu_of(rq);
1825 
1826 	if (!cpumask_test_cpu(cpu, p->cpus_ptr))
1827 		return false;
1828 	if (unlikely(is_migration_disabled(p)))
1829 		return false;
1830 	if (!(p->flags & PF_KTHREAD) && unlikely(!task_cpu_possible(cpu, p)))
1831 		return false;
1832 	if (!scx_rq_online(rq))
1833 		return false;
1834 	return true;
1835 }
1836 
1837 static bool consume_remote_task(struct rq *rq, struct rq_flags *rf,
1838 				struct scx_dispatch_q *dsq,
1839 				struct task_struct *p, struct rq *task_rq)
1840 {
1841 	bool moved = false;
1842 
1843 	lockdep_assert_held(&dsq->lock);	/* released on return */
1844 
1845 	/*
1846 	 * @dsq is locked and @p is on a remote rq. @p is currently protected by
1847 	 * @dsq->lock. We want to pull @p to @rq but may deadlock if we grab
1848 	 * @task_rq while holding @dsq and @rq locks. As dequeue can't drop the
1849 	 * rq lock or fail, do a little dancing from our side. See
1850 	 * move_task_to_local_dsq().
1851 	 */
1852 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
1853 	list_del_init(&p->scx.dsq_node);
1854 	dsq_mod_nr(dsq, -1);
1855 	p->scx.holding_cpu = raw_smp_processor_id();
1856 	raw_spin_unlock(&dsq->lock);
1857 
1858 	rq_unpin_lock(rq, rf);
1859 	double_lock_balance(rq, task_rq);
1860 	rq_repin_lock(rq, rf);
1861 
1862 	moved = move_task_to_local_dsq(rq, p, 0);
1863 
1864 	double_unlock_balance(rq, task_rq);
1865 
1866 	return moved;
1867 }
1868 #else	/* CONFIG_SMP */
1869 static bool task_can_run_on_remote_rq(struct task_struct *p, struct rq *rq) { return false; }
1870 static bool consume_remote_task(struct rq *rq, struct rq_flags *rf,
1871 				struct scx_dispatch_q *dsq,
1872 				struct task_struct *p, struct rq *task_rq) { return false; }
1873 #endif	/* CONFIG_SMP */
1874 
1875 static bool consume_dispatch_q(struct rq *rq, struct rq_flags *rf,
1876 			       struct scx_dispatch_q *dsq)
1877 {
1878 	struct task_struct *p;
1879 retry:
1880 	if (list_empty(&dsq->list))
1881 		return false;
1882 
1883 	raw_spin_lock(&dsq->lock);
1884 
1885 	list_for_each_entry(p, &dsq->list, scx.dsq_node) {
1886 		struct rq *task_rq = task_rq(p);
1887 
1888 		if (rq == task_rq) {
1889 			consume_local_task(rq, dsq, p);
1890 			return true;
1891 		}
1892 
1893 		if (task_can_run_on_remote_rq(p, rq)) {
1894 			if (likely(consume_remote_task(rq, rf, dsq, p, task_rq)))
1895 				return true;
1896 			goto retry;
1897 		}
1898 	}
1899 
1900 	raw_spin_unlock(&dsq->lock);
1901 	return false;
1902 }
1903 
1904 enum dispatch_to_local_dsq_ret {
1905 	DTL_DISPATCHED,		/* successfully dispatched */
1906 	DTL_LOST,		/* lost race to dequeue */
1907 	DTL_NOT_LOCAL,		/* destination is not a local DSQ */
1908 	DTL_INVALID,		/* invalid local dsq_id */
1909 };
1910 
1911 /**
1912  * dispatch_to_local_dsq - Dispatch a task to a local dsq
1913  * @rq: current rq which is locked
1914  * @rf: rq_flags to use when unlocking @rq
1915  * @dsq_id: destination dsq ID
1916  * @p: task to dispatch
1917  * @enq_flags: %SCX_ENQ_*
1918  *
1919  * We're holding @rq lock and want to dispatch @p to the local DSQ identified by
1920  * @dsq_id. This function performs all the synchronization dancing needed
1921  * because local DSQs are protected with rq locks.
1922  *
1923  * The caller must have exclusive ownership of @p (e.g. through
1924  * %SCX_OPSS_DISPATCHING).
1925  */
1926 static enum dispatch_to_local_dsq_ret
1927 dispatch_to_local_dsq(struct rq *rq, struct rq_flags *rf, u64 dsq_id,
1928 		      struct task_struct *p, u64 enq_flags)
1929 {
1930 	struct rq *src_rq = task_rq(p);
1931 	struct rq *dst_rq;
1932 
1933 	/*
1934 	 * We're synchronized against dequeue through DISPATCHING. As @p can't
1935 	 * be dequeued, its task_rq and cpus_allowed are stable too.
1936 	 */
1937 	if (dsq_id == SCX_DSQ_LOCAL) {
1938 		dst_rq = rq;
1939 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
1940 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
1941 
1942 		if (!ops_cpu_valid(cpu, "in SCX_DSQ_LOCAL_ON dispatch verdict"))
1943 			return DTL_INVALID;
1944 		dst_rq = cpu_rq(cpu);
1945 	} else {
1946 		return DTL_NOT_LOCAL;
1947 	}
1948 
1949 	/* if dispatching to @rq that @p is already on, no lock dancing needed */
1950 	if (rq == src_rq && rq == dst_rq) {
1951 		dispatch_enqueue(&dst_rq->scx.local_dsq, p,
1952 				 enq_flags | SCX_ENQ_CLEAR_OPSS);
1953 		return DTL_DISPATCHED;
1954 	}
1955 
1956 #ifdef CONFIG_SMP
1957 	if (cpumask_test_cpu(cpu_of(dst_rq), p->cpus_ptr)) {
1958 		struct rq *locked_dst_rq = dst_rq;
1959 		bool dsp;
1960 
1961 		/*
1962 		 * @p is on a possibly remote @src_rq which we need to lock to
1963 		 * move the task. If dequeue is in progress, it'd be locking
1964 		 * @src_rq and waiting on DISPATCHING, so we can't grab @src_rq
1965 		 * lock while holding DISPATCHING.
1966 		 *
1967 		 * As DISPATCHING guarantees that @p is wholly ours, we can
1968 		 * pretend that we're moving from a DSQ and use the same
1969 		 * mechanism - mark the task under transfer with holding_cpu,
1970 		 * release DISPATCHING and then follow the same protocol.
1971 		 */
1972 		p->scx.holding_cpu = raw_smp_processor_id();
1973 
1974 		/* store_release ensures that dequeue sees the above */
1975 		atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1976 
1977 		dispatch_to_local_dsq_lock(rq, rf, src_rq, locked_dst_rq);
1978 
1979 		/*
1980 		 * We don't require the BPF scheduler to avoid dispatching to
1981 		 * offline CPUs mostly for convenience but also because CPUs can
1982 		 * go offline between scx_bpf_dispatch() calls and here. If @p
1983 		 * is destined to an offline CPU, queue it on its current CPU
1984 		 * instead, which should always be safe. As this is an allowed
1985 		 * behavior, don't trigger an ops error.
1986 		 */
1987 		if (!scx_rq_online(dst_rq))
1988 			dst_rq = src_rq;
1989 
1990 		if (src_rq == dst_rq) {
1991 			/*
1992 			 * As @p is staying on the same rq, there's no need to
1993 			 * go through the full deactivate/activate cycle.
1994 			 * Optimize by abbreviating the operations in
1995 			 * move_task_to_local_dsq().
1996 			 */
1997 			dsp = p->scx.holding_cpu == raw_smp_processor_id();
1998 			if (likely(dsp)) {
1999 				p->scx.holding_cpu = -1;
2000 				dispatch_enqueue(&dst_rq->scx.local_dsq, p,
2001 						 enq_flags);
2002 			}
2003 		} else {
2004 			dsp = move_task_to_local_dsq(dst_rq, p, enq_flags);
2005 		}
2006 
2007 		/* if the destination CPU is idle, wake it up */
2008 		if (dsp && sched_class_above(p->sched_class,
2009 					     dst_rq->curr->sched_class))
2010 			resched_curr(dst_rq);
2011 
2012 		dispatch_to_local_dsq_unlock(rq, rf, src_rq, locked_dst_rq);
2013 
2014 		return dsp ? DTL_DISPATCHED : DTL_LOST;
2015 	}
2016 #endif	/* CONFIG_SMP */
2017 
2018 	scx_ops_error("SCX_DSQ_LOCAL[_ON] verdict target cpu %d not allowed for %s[%d]",
2019 		      cpu_of(dst_rq), p->comm, p->pid);
2020 	return DTL_INVALID;
2021 }
2022 
2023 /**
2024  * finish_dispatch - Asynchronously finish dispatching a task
2025  * @rq: current rq which is locked
2026  * @rf: rq_flags to use when unlocking @rq
2027  * @p: task to finish dispatching
2028  * @qseq_at_dispatch: qseq when @p started getting dispatched
2029  * @dsq_id: destination DSQ ID
2030  * @enq_flags: %SCX_ENQ_*
2031  *
2032  * Dispatching to local DSQs may need to wait for queueing to complete or
2033  * require rq lock dancing. As we don't wanna do either while inside
2034  * ops.dispatch() to avoid locking order inversion, we split dispatching into
2035  * two parts. scx_bpf_dispatch() which is called by ops.dispatch() records the
2036  * task and its qseq. Once ops.dispatch() returns, this function is called to
2037  * finish up.
2038  *
2039  * There is no guarantee that @p is still valid for dispatching or even that it
2040  * was valid in the first place. Make sure that the task is still owned by the
2041  * BPF scheduler and claim the ownership before dispatching.
2042  */
2043 static void finish_dispatch(struct rq *rq, struct rq_flags *rf,
2044 			    struct task_struct *p,
2045 			    unsigned long qseq_at_dispatch,
2046 			    u64 dsq_id, u64 enq_flags)
2047 {
2048 	struct scx_dispatch_q *dsq;
2049 	unsigned long opss;
2050 
2051 retry:
2052 	/*
2053 	 * No need for _acquire here. @p is accessed only after a successful
2054 	 * try_cmpxchg to DISPATCHING.
2055 	 */
2056 	opss = atomic_long_read(&p->scx.ops_state);
2057 
2058 	switch (opss & SCX_OPSS_STATE_MASK) {
2059 	case SCX_OPSS_DISPATCHING:
2060 	case SCX_OPSS_NONE:
2061 		/* someone else already got to it */
2062 		return;
2063 	case SCX_OPSS_QUEUED:
2064 		/*
2065 		 * If qseq doesn't match, @p has gone through at least one
2066 		 * dispatch/dequeue and re-enqueue cycle between
2067 		 * scx_bpf_dispatch() and here and we have no claim on it.
2068 		 */
2069 		if ((opss & SCX_OPSS_QSEQ_MASK) != qseq_at_dispatch)
2070 			return;
2071 
2072 		/*
2073 		 * While we know @p is accessible, we don't yet have a claim on
2074 		 * it - the BPF scheduler is allowed to dispatch tasks
2075 		 * spuriously and there can be a racing dequeue attempt. Let's
2076 		 * claim @p by atomically transitioning it from QUEUED to
2077 		 * DISPATCHING.
2078 		 */
2079 		if (likely(atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
2080 						   SCX_OPSS_DISPATCHING)))
2081 			break;
2082 		goto retry;
2083 	case SCX_OPSS_QUEUEING:
2084 		/*
2085 		 * do_enqueue_task() is in the process of transferring the task
2086 		 * to the BPF scheduler while holding @p's rq lock. As we aren't
2087 		 * holding any kernel or BPF resource that the enqueue path may
2088 		 * depend upon, it's safe to wait.
2089 		 */
2090 		wait_ops_state(p, opss);
2091 		goto retry;
2092 	}
2093 
2094 	BUG_ON(!(p->scx.flags & SCX_TASK_QUEUED));
2095 
2096 	switch (dispatch_to_local_dsq(rq, rf, dsq_id, p, enq_flags)) {
2097 	case DTL_DISPATCHED:
2098 		break;
2099 	case DTL_LOST:
2100 		break;
2101 	case DTL_INVALID:
2102 		dsq_id = SCX_DSQ_GLOBAL;
2103 		fallthrough;
2104 	case DTL_NOT_LOCAL:
2105 		dsq = find_dsq_for_dispatch(cpu_rq(raw_smp_processor_id()),
2106 					    dsq_id, p);
2107 		dispatch_enqueue(dsq, p, enq_flags | SCX_ENQ_CLEAR_OPSS);
2108 		break;
2109 	}
2110 }
2111 
2112 static void flush_dispatch_buf(struct rq *rq, struct rq_flags *rf)
2113 {
2114 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
2115 	u32 u;
2116 
2117 	for (u = 0; u < dspc->cursor; u++) {
2118 		struct scx_dsp_buf_ent *ent = &dspc->buf[u];
2119 
2120 		finish_dispatch(rq, rf, ent->task, ent->qseq, ent->dsq_id,
2121 				ent->enq_flags);
2122 	}
2123 
2124 	dspc->nr_tasks += dspc->cursor;
2125 	dspc->cursor = 0;
2126 }
2127 
2128 static int balance_scx(struct rq *rq, struct task_struct *prev,
2129 		       struct rq_flags *rf)
2130 {
2131 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
2132 	bool prev_on_scx = prev->sched_class == &ext_sched_class;
2133 	int nr_loops = SCX_DSP_MAX_LOOPS;
2134 	bool has_tasks = false;
2135 
2136 	lockdep_assert_rq_held(rq);
2137 	rq->scx.flags |= SCX_RQ_BALANCING;
2138 
2139 	if (static_branch_unlikely(&scx_ops_cpu_preempt) &&
2140 	    unlikely(rq->scx.cpu_released)) {
2141 		/*
2142 		 * If the previous sched_class for the current CPU was not SCX,
2143 		 * notify the BPF scheduler that it again has control of the
2144 		 * core. This callback complements ->cpu_release(), which is
2145 		 * emitted in scx_next_task_picked().
2146 		 */
2147 		if (SCX_HAS_OP(cpu_acquire))
2148 			SCX_CALL_OP(0, cpu_acquire, cpu_of(rq), NULL);
2149 		rq->scx.cpu_released = false;
2150 	}
2151 
2152 	if (prev_on_scx) {
2153 		WARN_ON_ONCE(prev->scx.flags & SCX_TASK_BAL_KEEP);
2154 		update_curr_scx(rq);
2155 
2156 		/*
2157 		 * If @prev is runnable & has slice left, it has priority and
2158 		 * fetching more just increases latency for the fetched tasks.
2159 		 * Tell put_prev_task_scx() to put @prev on local_dsq. If the
2160 		 * BPF scheduler wants to handle this explicitly, it should
2161 		 * implement ->cpu_released().
2162 		 *
2163 		 * See scx_ops_disable_workfn() for the explanation on the
2164 		 * bypassing test.
2165 		 */
2166 		if ((prev->scx.flags & SCX_TASK_QUEUED) &&
2167 		    prev->scx.slice && !scx_ops_bypassing()) {
2168 			prev->scx.flags |= SCX_TASK_BAL_KEEP;
2169 			goto has_tasks;
2170 		}
2171 	}
2172 
2173 	/* if there already are tasks to run, nothing to do */
2174 	if (rq->scx.local_dsq.nr)
2175 		goto has_tasks;
2176 
2177 	if (consume_dispatch_q(rq, rf, &scx_dsq_global))
2178 		goto has_tasks;
2179 
2180 	if (!SCX_HAS_OP(dispatch) || scx_ops_bypassing() || !scx_rq_online(rq))
2181 		goto out;
2182 
2183 	dspc->rq = rq;
2184 	dspc->rf = rf;
2185 
2186 	/*
2187 	 * The dispatch loop. Because flush_dispatch_buf() may drop the rq lock,
2188 	 * the local DSQ might still end up empty after a successful
2189 	 * ops.dispatch(). If the local DSQ is empty even after ops.dispatch()
2190 	 * produced some tasks, retry. The BPF scheduler may depend on this
2191 	 * looping behavior to simplify its implementation.
2192 	 */
2193 	do {
2194 		dspc->nr_tasks = 0;
2195 
2196 		SCX_CALL_OP(SCX_KF_DISPATCH, dispatch, cpu_of(rq),
2197 			    prev_on_scx ? prev : NULL);
2198 
2199 		flush_dispatch_buf(rq, rf);
2200 
2201 		if (rq->scx.local_dsq.nr)
2202 			goto has_tasks;
2203 		if (consume_dispatch_q(rq, rf, &scx_dsq_global))
2204 			goto has_tasks;
2205 
2206 		/*
2207 		 * ops.dispatch() can trap us in this loop by repeatedly
2208 		 * dispatching ineligible tasks. Break out once in a while to
2209 		 * allow the watchdog to run. As IRQ can't be enabled in
2210 		 * balance(), we want to complete this scheduling cycle and then
2211 		 * start a new one. IOW, we want to call resched_curr() on the
2212 		 * next, most likely idle, task, not the current one. Use
2213 		 * scx_bpf_kick_cpu() for deferred kicking.
2214 		 */
2215 		if (unlikely(!--nr_loops)) {
2216 			scx_bpf_kick_cpu(cpu_of(rq), 0);
2217 			break;
2218 		}
2219 	} while (dspc->nr_tasks);
2220 
2221 	goto out;
2222 
2223 has_tasks:
2224 	has_tasks = true;
2225 out:
2226 	rq->scx.flags &= ~SCX_RQ_BALANCING;
2227 	return has_tasks;
2228 }
2229 
2230 static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first)
2231 {
2232 	if (p->scx.flags & SCX_TASK_QUEUED) {
2233 		WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
2234 		dispatch_dequeue(rq, p);
2235 	}
2236 
2237 	p->se.exec_start = rq_clock_task(rq);
2238 
2239 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2240 	if (SCX_HAS_OP(running) && (p->scx.flags & SCX_TASK_QUEUED))
2241 		SCX_CALL_OP_TASK(SCX_KF_REST, running, p);
2242 
2243 	clr_task_runnable(p, true);
2244 
2245 	/*
2246 	 * @p is getting newly scheduled or got kicked after someone updated its
2247 	 * slice. Refresh whether tick can be stopped. See scx_can_stop_tick().
2248 	 */
2249 	if ((p->scx.slice == SCX_SLICE_INF) !=
2250 	    (bool)(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) {
2251 		if (p->scx.slice == SCX_SLICE_INF)
2252 			rq->scx.flags |= SCX_RQ_CAN_STOP_TICK;
2253 		else
2254 			rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK;
2255 
2256 		sched_update_tick_dependency(rq);
2257 
2258 		/*
2259 		 * For now, let's refresh the load_avgs just when transitioning
2260 		 * in and out of nohz. In the future, we might want to add a
2261 		 * mechanism which calls the following periodically on
2262 		 * tick-stopped CPUs.
2263 		 */
2264 		update_other_load_avgs(rq);
2265 	}
2266 }
2267 
2268 static void put_prev_task_scx(struct rq *rq, struct task_struct *p)
2269 {
2270 #ifndef CONFIG_SMP
2271 	/*
2272 	 * UP workaround.
2273 	 *
2274 	 * Because SCX may transfer tasks across CPUs during dispatch, dispatch
2275 	 * is performed from its balance operation which isn't called in UP.
2276 	 * Let's work around by calling it from the operations which come right
2277 	 * after.
2278 	 *
2279 	 * 1. If the prev task is on SCX, pick_next_task() calls
2280 	 *    .put_prev_task() right after. As .put_prev_task() is also called
2281 	 *    from other places, we need to distinguish the calls which can be
2282 	 *    done by looking at the previous task's state - if still queued or
2283 	 *    dequeued with %SCX_DEQ_SLEEP, the caller must be pick_next_task().
2284 	 *    This case is handled here.
2285 	 *
2286 	 * 2. If the prev task is not on SCX, the first following call into SCX
2287 	 *    will be .pick_next_task(), which is covered by calling
2288 	 *    balance_scx() from pick_next_task_scx().
2289 	 *
2290 	 * Note that we can't merge the first case into the second as
2291 	 * balance_scx() must be called before the previous SCX task goes
2292 	 * through put_prev_task_scx().
2293 	 *
2294 	 * As UP doesn't transfer tasks around, balance_scx() doesn't need @rf.
2295 	 * Pass in %NULL.
2296 	 */
2297 	if (p->scx.flags & (SCX_TASK_QUEUED | SCX_TASK_DEQD_FOR_SLEEP))
2298 		balance_scx(rq, p, NULL);
2299 #endif
2300 
2301 	update_curr_scx(rq);
2302 
2303 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2304 	if (SCX_HAS_OP(stopping) && (p->scx.flags & SCX_TASK_QUEUED))
2305 		SCX_CALL_OP_TASK(SCX_KF_REST, stopping, p, true);
2306 
2307 	/*
2308 	 * If we're being called from put_prev_task_balance(), balance_scx() may
2309 	 * have decided that @p should keep running.
2310 	 */
2311 	if (p->scx.flags & SCX_TASK_BAL_KEEP) {
2312 		p->scx.flags &= ~SCX_TASK_BAL_KEEP;
2313 		set_task_runnable(rq, p);
2314 		dispatch_enqueue(&rq->scx.local_dsq, p, SCX_ENQ_HEAD);
2315 		return;
2316 	}
2317 
2318 	if (p->scx.flags & SCX_TASK_QUEUED) {
2319 		set_task_runnable(rq, p);
2320 
2321 		/*
2322 		 * If @p has slice left and balance_scx() didn't tag it for
2323 		 * keeping, @p is getting preempted by a higher priority
2324 		 * scheduler class. Leave it at the head of the local DSQ.
2325 		 */
2326 		if (p->scx.slice && !scx_ops_bypassing()) {
2327 			dispatch_enqueue(&rq->scx.local_dsq, p, SCX_ENQ_HEAD);
2328 			return;
2329 		}
2330 
2331 		/*
2332 		 * If we're in the pick_next_task path, balance_scx() should
2333 		 * have already populated the local DSQ if there are any other
2334 		 * available tasks. If empty, tell ops.enqueue() that @p is the
2335 		 * only one available for this cpu. ops.enqueue() should put it
2336 		 * on the local DSQ so that the subsequent pick_next_task_scx()
2337 		 * can find the task unless it wants to trigger a separate
2338 		 * follow-up scheduling event.
2339 		 */
2340 		if (list_empty(&rq->scx.local_dsq.list))
2341 			do_enqueue_task(rq, p, SCX_ENQ_LAST, -1);
2342 		else
2343 			do_enqueue_task(rq, p, 0, -1);
2344 	}
2345 }
2346 
2347 static struct task_struct *first_local_task(struct rq *rq)
2348 {
2349 	return list_first_entry_or_null(&rq->scx.local_dsq.list,
2350 					struct task_struct, scx.dsq_node);
2351 }
2352 
2353 static struct task_struct *pick_next_task_scx(struct rq *rq)
2354 {
2355 	struct task_struct *p;
2356 
2357 #ifndef CONFIG_SMP
2358 	/* UP workaround - see the comment at the head of put_prev_task_scx() */
2359 	if (unlikely(rq->curr->sched_class != &ext_sched_class))
2360 		balance_scx(rq, rq->curr, NULL);
2361 #endif
2362 
2363 	p = first_local_task(rq);
2364 	if (!p)
2365 		return NULL;
2366 
2367 	set_next_task_scx(rq, p, true);
2368 
2369 	if (unlikely(!p->scx.slice)) {
2370 		if (!scx_ops_bypassing() && !scx_warned_zero_slice) {
2371 			printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in pick_next_task_scx()\n",
2372 					p->comm, p->pid);
2373 			scx_warned_zero_slice = true;
2374 		}
2375 		p->scx.slice = SCX_SLICE_DFL;
2376 	}
2377 
2378 	return p;
2379 }
2380 
2381 static enum scx_cpu_preempt_reason
2382 preempt_reason_from_class(const struct sched_class *class)
2383 {
2384 #ifdef CONFIG_SMP
2385 	if (class == &stop_sched_class)
2386 		return SCX_CPU_PREEMPT_STOP;
2387 #endif
2388 	if (class == &dl_sched_class)
2389 		return SCX_CPU_PREEMPT_DL;
2390 	if (class == &rt_sched_class)
2391 		return SCX_CPU_PREEMPT_RT;
2392 	return SCX_CPU_PREEMPT_UNKNOWN;
2393 }
2394 
2395 void scx_next_task_picked(struct rq *rq, struct task_struct *p,
2396 			  const struct sched_class *active)
2397 {
2398 	lockdep_assert_rq_held(rq);
2399 
2400 	if (!scx_enabled())
2401 		return;
2402 #ifdef CONFIG_SMP
2403 	/*
2404 	 * Pairs with the smp_load_acquire() issued by a CPU in
2405 	 * kick_cpus_irq_workfn() who is waiting for this CPU to perform a
2406 	 * resched.
2407 	 */
2408 	smp_store_release(&rq->scx.pnt_seq, rq->scx.pnt_seq + 1);
2409 #endif
2410 	if (!static_branch_unlikely(&scx_ops_cpu_preempt))
2411 		return;
2412 
2413 	/*
2414 	 * The callback is conceptually meant to convey that the CPU is no
2415 	 * longer under the control of SCX. Therefore, don't invoke the
2416 	 * callback if the CPU is is staying on SCX, or going idle (in which
2417 	 * case the SCX scheduler has actively decided not to schedule any
2418 	 * tasks on the CPU).
2419 	 */
2420 	if (likely(active >= &ext_sched_class))
2421 		return;
2422 
2423 	/*
2424 	 * At this point we know that SCX was preempted by a higher priority
2425 	 * sched_class, so invoke the ->cpu_release() callback if we have not
2426 	 * done so already. We only send the callback once between SCX being
2427 	 * preempted, and it regaining control of the CPU.
2428 	 *
2429 	 * ->cpu_release() complements ->cpu_acquire(), which is emitted the
2430 	 *  next time that balance_scx() is invoked.
2431 	 */
2432 	if (!rq->scx.cpu_released) {
2433 		if (SCX_HAS_OP(cpu_release)) {
2434 			struct scx_cpu_release_args args = {
2435 				.reason = preempt_reason_from_class(active),
2436 				.task = p,
2437 			};
2438 
2439 			SCX_CALL_OP(SCX_KF_CPU_RELEASE,
2440 				    cpu_release, cpu_of(rq), &args);
2441 		}
2442 		rq->scx.cpu_released = true;
2443 	}
2444 }
2445 
2446 #ifdef CONFIG_SMP
2447 
2448 static bool test_and_clear_cpu_idle(int cpu)
2449 {
2450 #ifdef CONFIG_SCHED_SMT
2451 	/*
2452 	 * SMT mask should be cleared whether we can claim @cpu or not. The SMT
2453 	 * cluster is not wholly idle either way. This also prevents
2454 	 * scx_pick_idle_cpu() from getting caught in an infinite loop.
2455 	 */
2456 	if (sched_smt_active()) {
2457 		const struct cpumask *smt = cpu_smt_mask(cpu);
2458 
2459 		/*
2460 		 * If offline, @cpu is not its own sibling and
2461 		 * scx_pick_idle_cpu() can get caught in an infinite loop as
2462 		 * @cpu is never cleared from idle_masks.smt. Ensure that @cpu
2463 		 * is eventually cleared.
2464 		 */
2465 		if (cpumask_intersects(smt, idle_masks.smt))
2466 			cpumask_andnot(idle_masks.smt, idle_masks.smt, smt);
2467 		else if (cpumask_test_cpu(cpu, idle_masks.smt))
2468 			__cpumask_clear_cpu(cpu, idle_masks.smt);
2469 	}
2470 #endif
2471 	return cpumask_test_and_clear_cpu(cpu, idle_masks.cpu);
2472 }
2473 
2474 static s32 scx_pick_idle_cpu(const struct cpumask *cpus_allowed, u64 flags)
2475 {
2476 	int cpu;
2477 
2478 retry:
2479 	if (sched_smt_active()) {
2480 		cpu = cpumask_any_and_distribute(idle_masks.smt, cpus_allowed);
2481 		if (cpu < nr_cpu_ids)
2482 			goto found;
2483 
2484 		if (flags & SCX_PICK_IDLE_CORE)
2485 			return -EBUSY;
2486 	}
2487 
2488 	cpu = cpumask_any_and_distribute(idle_masks.cpu, cpus_allowed);
2489 	if (cpu >= nr_cpu_ids)
2490 		return -EBUSY;
2491 
2492 found:
2493 	if (test_and_clear_cpu_idle(cpu))
2494 		return cpu;
2495 	else
2496 		goto retry;
2497 }
2498 
2499 static s32 scx_select_cpu_dfl(struct task_struct *p, s32 prev_cpu,
2500 			      u64 wake_flags, bool *found)
2501 {
2502 	s32 cpu;
2503 
2504 	*found = false;
2505 
2506 	if (!static_branch_likely(&scx_builtin_idle_enabled)) {
2507 		scx_ops_error("built-in idle tracking is disabled");
2508 		return prev_cpu;
2509 	}
2510 
2511 	/*
2512 	 * If WAKE_SYNC, the waker's local DSQ is empty, and the system is
2513 	 * under utilized, wake up @p to the local DSQ of the waker. Checking
2514 	 * only for an empty local DSQ is insufficient as it could give the
2515 	 * wakee an unfair advantage when the system is oversaturated.
2516 	 * Checking only for the presence of idle CPUs is also insufficient as
2517 	 * the local DSQ of the waker could have tasks piled up on it even if
2518 	 * there is an idle core elsewhere on the system.
2519 	 */
2520 	cpu = smp_processor_id();
2521 	if ((wake_flags & SCX_WAKE_SYNC) && p->nr_cpus_allowed > 1 &&
2522 	    !cpumask_empty(idle_masks.cpu) && !(current->flags & PF_EXITING) &&
2523 	    cpu_rq(cpu)->scx.local_dsq.nr == 0) {
2524 		if (cpumask_test_cpu(cpu, p->cpus_ptr))
2525 			goto cpu_found;
2526 	}
2527 
2528 	if (p->nr_cpus_allowed == 1) {
2529 		if (test_and_clear_cpu_idle(prev_cpu)) {
2530 			cpu = prev_cpu;
2531 			goto cpu_found;
2532 		} else {
2533 			return prev_cpu;
2534 		}
2535 	}
2536 
2537 	/*
2538 	 * If CPU has SMT, any wholly idle CPU is likely a better pick than
2539 	 * partially idle @prev_cpu.
2540 	 */
2541 	if (sched_smt_active()) {
2542 		if (cpumask_test_cpu(prev_cpu, idle_masks.smt) &&
2543 		    test_and_clear_cpu_idle(prev_cpu)) {
2544 			cpu = prev_cpu;
2545 			goto cpu_found;
2546 		}
2547 
2548 		cpu = scx_pick_idle_cpu(p->cpus_ptr, SCX_PICK_IDLE_CORE);
2549 		if (cpu >= 0)
2550 			goto cpu_found;
2551 	}
2552 
2553 	if (test_and_clear_cpu_idle(prev_cpu)) {
2554 		cpu = prev_cpu;
2555 		goto cpu_found;
2556 	}
2557 
2558 	cpu = scx_pick_idle_cpu(p->cpus_ptr, 0);
2559 	if (cpu >= 0)
2560 		goto cpu_found;
2561 
2562 	return prev_cpu;
2563 
2564 cpu_found:
2565 	*found = true;
2566 	return cpu;
2567 }
2568 
2569 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags)
2570 {
2571 	/*
2572 	 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it
2573 	 * can be a good migration opportunity with low cache and memory
2574 	 * footprint. Returning a CPU different than @prev_cpu triggers
2575 	 * immediate rq migration. However, for SCX, as the current rq
2576 	 * association doesn't dictate where the task is going to run, this
2577 	 * doesn't fit well. If necessary, we can later add a dedicated method
2578 	 * which can decide to preempt self to force it through the regular
2579 	 * scheduling path.
2580 	 */
2581 	if (unlikely(wake_flags & WF_EXEC))
2582 		return prev_cpu;
2583 
2584 	if (SCX_HAS_OP(select_cpu)) {
2585 		s32 cpu;
2586 		struct task_struct **ddsp_taskp;
2587 
2588 		ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
2589 		WARN_ON_ONCE(*ddsp_taskp);
2590 		*ddsp_taskp = p;
2591 
2592 		cpu = SCX_CALL_OP_TASK_RET(SCX_KF_ENQUEUE | SCX_KF_SELECT_CPU,
2593 					   select_cpu, p, prev_cpu, wake_flags);
2594 		*ddsp_taskp = NULL;
2595 		if (ops_cpu_valid(cpu, "from ops.select_cpu()"))
2596 			return cpu;
2597 		else
2598 			return prev_cpu;
2599 	} else {
2600 		bool found;
2601 		s32 cpu;
2602 
2603 		cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, &found);
2604 		if (found) {
2605 			p->scx.slice = SCX_SLICE_DFL;
2606 			p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL;
2607 		}
2608 		return cpu;
2609 	}
2610 }
2611 
2612 static void set_cpus_allowed_scx(struct task_struct *p,
2613 				 struct affinity_context *ac)
2614 {
2615 	set_cpus_allowed_common(p, ac);
2616 
2617 	/*
2618 	 * The effective cpumask is stored in @p->cpus_ptr which may temporarily
2619 	 * differ from the configured one in @p->cpus_mask. Always tell the bpf
2620 	 * scheduler the effective one.
2621 	 *
2622 	 * Fine-grained memory write control is enforced by BPF making the const
2623 	 * designation pointless. Cast it away when calling the operation.
2624 	 */
2625 	if (SCX_HAS_OP(set_cpumask))
2626 		SCX_CALL_OP_TASK(SCX_KF_REST, set_cpumask, p,
2627 				 (struct cpumask *)p->cpus_ptr);
2628 }
2629 
2630 static void reset_idle_masks(void)
2631 {
2632 	/*
2633 	 * Consider all online cpus idle. Should converge to the actual state
2634 	 * quickly.
2635 	 */
2636 	cpumask_copy(idle_masks.cpu, cpu_online_mask);
2637 	cpumask_copy(idle_masks.smt, cpu_online_mask);
2638 }
2639 
2640 void __scx_update_idle(struct rq *rq, bool idle)
2641 {
2642 	int cpu = cpu_of(rq);
2643 
2644 	if (SCX_HAS_OP(update_idle)) {
2645 		SCX_CALL_OP(SCX_KF_REST, update_idle, cpu_of(rq), idle);
2646 		if (!static_branch_unlikely(&scx_builtin_idle_enabled))
2647 			return;
2648 	}
2649 
2650 	if (idle)
2651 		cpumask_set_cpu(cpu, idle_masks.cpu);
2652 	else
2653 		cpumask_clear_cpu(cpu, idle_masks.cpu);
2654 
2655 #ifdef CONFIG_SCHED_SMT
2656 	if (sched_smt_active()) {
2657 		const struct cpumask *smt = cpu_smt_mask(cpu);
2658 
2659 		if (idle) {
2660 			/*
2661 			 * idle_masks.smt handling is racy but that's fine as
2662 			 * it's only for optimization and self-correcting.
2663 			 */
2664 			for_each_cpu(cpu, smt) {
2665 				if (!cpumask_test_cpu(cpu, idle_masks.cpu))
2666 					return;
2667 			}
2668 			cpumask_or(idle_masks.smt, idle_masks.smt, smt);
2669 		} else {
2670 			cpumask_andnot(idle_masks.smt, idle_masks.smt, smt);
2671 		}
2672 	}
2673 #endif
2674 }
2675 
2676 #else	/* CONFIG_SMP */
2677 
2678 static bool test_and_clear_cpu_idle(int cpu) { return false; }
2679 static s32 scx_pick_idle_cpu(const struct cpumask *cpus_allowed, u64 flags) { return -EBUSY; }
2680 static void reset_idle_masks(void) {}
2681 
2682 #endif	/* CONFIG_SMP */
2683 
2684 static bool check_rq_for_timeouts(struct rq *rq)
2685 {
2686 	struct task_struct *p;
2687 	struct rq_flags rf;
2688 	bool timed_out = false;
2689 
2690 	rq_lock_irqsave(rq, &rf);
2691 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) {
2692 		unsigned long last_runnable = p->scx.runnable_at;
2693 
2694 		if (unlikely(time_after(jiffies,
2695 					last_runnable + scx_watchdog_timeout))) {
2696 			u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable);
2697 
2698 			scx_ops_error_kind(SCX_EXIT_ERROR_STALL,
2699 					   "%s[%d] failed to run for %u.%03us",
2700 					   p->comm, p->pid,
2701 					   dur_ms / 1000, dur_ms % 1000);
2702 			timed_out = true;
2703 			break;
2704 		}
2705 	}
2706 	rq_unlock_irqrestore(rq, &rf);
2707 
2708 	return timed_out;
2709 }
2710 
2711 static void scx_watchdog_workfn(struct work_struct *work)
2712 {
2713 	int cpu;
2714 
2715 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
2716 
2717 	for_each_online_cpu(cpu) {
2718 		if (unlikely(check_rq_for_timeouts(cpu_rq(cpu))))
2719 			break;
2720 
2721 		cond_resched();
2722 	}
2723 	queue_delayed_work(system_unbound_wq, to_delayed_work(work),
2724 			   scx_watchdog_timeout / 2);
2725 }
2726 
2727 void scx_tick(struct rq *rq)
2728 {
2729 	unsigned long last_check;
2730 
2731 	if (!scx_enabled())
2732 		return;
2733 
2734 	last_check = READ_ONCE(scx_watchdog_timestamp);
2735 	if (unlikely(time_after(jiffies,
2736 				last_check + READ_ONCE(scx_watchdog_timeout)))) {
2737 		u32 dur_ms = jiffies_to_msecs(jiffies - last_check);
2738 
2739 		scx_ops_error_kind(SCX_EXIT_ERROR_STALL,
2740 				   "watchdog failed to check in for %u.%03us",
2741 				   dur_ms / 1000, dur_ms % 1000);
2742 	}
2743 
2744 	update_other_load_avgs(rq);
2745 }
2746 
2747 static void task_tick_scx(struct rq *rq, struct task_struct *curr, int queued)
2748 {
2749 	update_curr_scx(rq);
2750 
2751 	/*
2752 	 * While bypassing, always resched as we can't trust the slice
2753 	 * management.
2754 	 */
2755 	if (scx_ops_bypassing())
2756 		curr->scx.slice = 0;
2757 	else if (SCX_HAS_OP(tick))
2758 		SCX_CALL_OP(SCX_KF_REST, tick, curr);
2759 
2760 	if (!curr->scx.slice)
2761 		resched_curr(rq);
2762 }
2763 
2764 static enum scx_task_state scx_get_task_state(const struct task_struct *p)
2765 {
2766 	return (p->scx.flags & SCX_TASK_STATE_MASK) >> SCX_TASK_STATE_SHIFT;
2767 }
2768 
2769 static void scx_set_task_state(struct task_struct *p, enum scx_task_state state)
2770 {
2771 	enum scx_task_state prev_state = scx_get_task_state(p);
2772 	bool warn = false;
2773 
2774 	BUILD_BUG_ON(SCX_TASK_NR_STATES > (1 << SCX_TASK_STATE_BITS));
2775 
2776 	switch (state) {
2777 	case SCX_TASK_NONE:
2778 		break;
2779 	case SCX_TASK_INIT:
2780 		warn = prev_state != SCX_TASK_NONE;
2781 		break;
2782 	case SCX_TASK_READY:
2783 		warn = prev_state == SCX_TASK_NONE;
2784 		break;
2785 	case SCX_TASK_ENABLED:
2786 		warn = prev_state != SCX_TASK_READY;
2787 		break;
2788 	default:
2789 		warn = true;
2790 		return;
2791 	}
2792 
2793 	WARN_ONCE(warn, "sched_ext: Invalid task state transition %d -> %d for %s[%d]",
2794 		  prev_state, state, p->comm, p->pid);
2795 
2796 	p->scx.flags &= ~SCX_TASK_STATE_MASK;
2797 	p->scx.flags |= state << SCX_TASK_STATE_SHIFT;
2798 }
2799 
2800 static int scx_ops_init_task(struct task_struct *p, struct task_group *tg, bool fork)
2801 {
2802 	int ret;
2803 
2804 	p->scx.disallow = false;
2805 
2806 	if (SCX_HAS_OP(init_task)) {
2807 		struct scx_init_task_args args = {
2808 			.fork = fork,
2809 		};
2810 
2811 		ret = SCX_CALL_OP_RET(SCX_KF_SLEEPABLE, init_task, p, &args);
2812 		if (unlikely(ret)) {
2813 			ret = ops_sanitize_err("init_task", ret);
2814 			return ret;
2815 		}
2816 	}
2817 
2818 	scx_set_task_state(p, SCX_TASK_INIT);
2819 
2820 	if (p->scx.disallow) {
2821 		struct rq *rq;
2822 		struct rq_flags rf;
2823 
2824 		rq = task_rq_lock(p, &rf);
2825 
2826 		/*
2827 		 * We're either in fork or load path and @p->policy will be
2828 		 * applied right after. Reverting @p->policy here and rejecting
2829 		 * %SCHED_EXT transitions from scx_check_setscheduler()
2830 		 * guarantees that if ops.init_task() sets @p->disallow, @p can
2831 		 * never be in SCX.
2832 		 */
2833 		if (p->policy == SCHED_EXT) {
2834 			p->policy = SCHED_NORMAL;
2835 			atomic_long_inc(&scx_nr_rejected);
2836 		}
2837 
2838 		task_rq_unlock(rq, p, &rf);
2839 	}
2840 
2841 	p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
2842 	return 0;
2843 }
2844 
2845 static void set_task_scx_weight(struct task_struct *p)
2846 {
2847 	u32 weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO];
2848 
2849 	p->scx.weight = sched_weight_to_cgroup(weight);
2850 }
2851 
2852 static void scx_ops_enable_task(struct task_struct *p)
2853 {
2854 	lockdep_assert_rq_held(task_rq(p));
2855 
2856 	/*
2857 	 * Set the weight before calling ops.enable() so that the scheduler
2858 	 * doesn't see a stale value if they inspect the task struct.
2859 	 */
2860 	set_task_scx_weight(p);
2861 	if (SCX_HAS_OP(enable))
2862 		SCX_CALL_OP_TASK(SCX_KF_REST, enable, p);
2863 	scx_set_task_state(p, SCX_TASK_ENABLED);
2864 
2865 	if (SCX_HAS_OP(set_weight))
2866 		SCX_CALL_OP(SCX_KF_REST, set_weight, p, p->scx.weight);
2867 }
2868 
2869 static void scx_ops_disable_task(struct task_struct *p)
2870 {
2871 	lockdep_assert_rq_held(task_rq(p));
2872 	WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED);
2873 
2874 	if (SCX_HAS_OP(disable))
2875 		SCX_CALL_OP(SCX_KF_REST, disable, p);
2876 	scx_set_task_state(p, SCX_TASK_READY);
2877 }
2878 
2879 static void scx_ops_exit_task(struct task_struct *p)
2880 {
2881 	struct scx_exit_task_args args = {
2882 		.cancelled = false,
2883 	};
2884 
2885 	lockdep_assert_rq_held(task_rq(p));
2886 
2887 	switch (scx_get_task_state(p)) {
2888 	case SCX_TASK_NONE:
2889 		return;
2890 	case SCX_TASK_INIT:
2891 		args.cancelled = true;
2892 		break;
2893 	case SCX_TASK_READY:
2894 		break;
2895 	case SCX_TASK_ENABLED:
2896 		scx_ops_disable_task(p);
2897 		break;
2898 	default:
2899 		WARN_ON_ONCE(true);
2900 		return;
2901 	}
2902 
2903 	if (SCX_HAS_OP(exit_task))
2904 		SCX_CALL_OP(SCX_KF_REST, exit_task, p, &args);
2905 	scx_set_task_state(p, SCX_TASK_NONE);
2906 }
2907 
2908 void init_scx_entity(struct sched_ext_entity *scx)
2909 {
2910 	/*
2911 	 * init_idle() calls this function again after fork sequence is
2912 	 * complete. Don't touch ->tasks_node as it's already linked.
2913 	 */
2914 	memset(scx, 0, offsetof(struct sched_ext_entity, tasks_node));
2915 
2916 	INIT_LIST_HEAD(&scx->dsq_node);
2917 	scx->sticky_cpu = -1;
2918 	scx->holding_cpu = -1;
2919 	INIT_LIST_HEAD(&scx->runnable_node);
2920 	scx->runnable_at = jiffies;
2921 	scx->ddsp_dsq_id = SCX_DSQ_INVALID;
2922 	scx->slice = SCX_SLICE_DFL;
2923 }
2924 
2925 void scx_pre_fork(struct task_struct *p)
2926 {
2927 	/*
2928 	 * BPF scheduler enable/disable paths want to be able to iterate and
2929 	 * update all tasks which can become complex when racing forks. As
2930 	 * enable/disable are very cold paths, let's use a percpu_rwsem to
2931 	 * exclude forks.
2932 	 */
2933 	percpu_down_read(&scx_fork_rwsem);
2934 }
2935 
2936 int scx_fork(struct task_struct *p)
2937 {
2938 	percpu_rwsem_assert_held(&scx_fork_rwsem);
2939 
2940 	if (scx_enabled())
2941 		return scx_ops_init_task(p, task_group(p), true);
2942 	else
2943 		return 0;
2944 }
2945 
2946 void scx_post_fork(struct task_struct *p)
2947 {
2948 	if (scx_enabled()) {
2949 		scx_set_task_state(p, SCX_TASK_READY);
2950 
2951 		/*
2952 		 * Enable the task immediately if it's running on sched_ext.
2953 		 * Otherwise, it'll be enabled in switching_to_scx() if and
2954 		 * when it's ever configured to run with a SCHED_EXT policy.
2955 		 */
2956 		if (p->sched_class == &ext_sched_class) {
2957 			struct rq_flags rf;
2958 			struct rq *rq;
2959 
2960 			rq = task_rq_lock(p, &rf);
2961 			scx_ops_enable_task(p);
2962 			task_rq_unlock(rq, p, &rf);
2963 		}
2964 	}
2965 
2966 	spin_lock_irq(&scx_tasks_lock);
2967 	list_add_tail(&p->scx.tasks_node, &scx_tasks);
2968 	spin_unlock_irq(&scx_tasks_lock);
2969 
2970 	percpu_up_read(&scx_fork_rwsem);
2971 }
2972 
2973 void scx_cancel_fork(struct task_struct *p)
2974 {
2975 	if (scx_enabled()) {
2976 		struct rq *rq;
2977 		struct rq_flags rf;
2978 
2979 		rq = task_rq_lock(p, &rf);
2980 		WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY);
2981 		scx_ops_exit_task(p);
2982 		task_rq_unlock(rq, p, &rf);
2983 	}
2984 
2985 	percpu_up_read(&scx_fork_rwsem);
2986 }
2987 
2988 void sched_ext_free(struct task_struct *p)
2989 {
2990 	unsigned long flags;
2991 
2992 	spin_lock_irqsave(&scx_tasks_lock, flags);
2993 	list_del_init(&p->scx.tasks_node);
2994 	spin_unlock_irqrestore(&scx_tasks_lock, flags);
2995 
2996 	/*
2997 	 * @p is off scx_tasks and wholly ours. scx_ops_enable()'s READY ->
2998 	 * ENABLED transitions can't race us. Disable ops for @p.
2999 	 */
3000 	if (scx_get_task_state(p) != SCX_TASK_NONE) {
3001 		struct rq_flags rf;
3002 		struct rq *rq;
3003 
3004 		rq = task_rq_lock(p, &rf);
3005 		scx_ops_exit_task(p);
3006 		task_rq_unlock(rq, p, &rf);
3007 	}
3008 }
3009 
3010 static void reweight_task_scx(struct rq *rq, struct task_struct *p, int newprio)
3011 {
3012 	lockdep_assert_rq_held(task_rq(p));
3013 
3014 	set_task_scx_weight(p);
3015 	if (SCX_HAS_OP(set_weight))
3016 		SCX_CALL_OP_TASK(SCX_KF_REST, set_weight, p, p->scx.weight);
3017 }
3018 
3019 static void prio_changed_scx(struct rq *rq, struct task_struct *p, int oldprio)
3020 {
3021 }
3022 
3023 static void switching_to_scx(struct rq *rq, struct task_struct *p)
3024 {
3025 	scx_ops_enable_task(p);
3026 
3027 	/*
3028 	 * set_cpus_allowed_scx() is not called while @p is associated with a
3029 	 * different scheduler class. Keep the BPF scheduler up-to-date.
3030 	 */
3031 	if (SCX_HAS_OP(set_cpumask))
3032 		SCX_CALL_OP_TASK(SCX_KF_REST, set_cpumask, p,
3033 				 (struct cpumask *)p->cpus_ptr);
3034 }
3035 
3036 static void switched_from_scx(struct rq *rq, struct task_struct *p)
3037 {
3038 	scx_ops_disable_task(p);
3039 }
3040 
3041 static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p,int wake_flags) {}
3042 static void switched_to_scx(struct rq *rq, struct task_struct *p) {}
3043 
3044 int scx_check_setscheduler(struct task_struct *p, int policy)
3045 {
3046 	lockdep_assert_rq_held(task_rq(p));
3047 
3048 	/* if disallow, reject transitioning into SCX */
3049 	if (scx_enabled() && READ_ONCE(p->scx.disallow) &&
3050 	    p->policy != policy && policy == SCHED_EXT)
3051 		return -EACCES;
3052 
3053 	return 0;
3054 }
3055 
3056 #ifdef CONFIG_NO_HZ_FULL
3057 bool scx_can_stop_tick(struct rq *rq)
3058 {
3059 	struct task_struct *p = rq->curr;
3060 
3061 	if (scx_ops_bypassing())
3062 		return false;
3063 
3064 	if (p->sched_class != &ext_sched_class)
3065 		return true;
3066 
3067 	/*
3068 	 * @rq can dispatch from different DSQs, so we can't tell whether it
3069 	 * needs the tick or not by looking at nr_running. Allow stopping ticks
3070 	 * iff the BPF scheduler indicated so. See set_next_task_scx().
3071 	 */
3072 	return rq->scx.flags & SCX_RQ_CAN_STOP_TICK;
3073 }
3074 #endif
3075 
3076 /*
3077  * Omitted operations:
3078  *
3079  * - wakeup_preempt: NOOP as it isn't useful in the wakeup path because the task
3080  *   isn't tied to the CPU at that point. Preemption is implemented by resetting
3081  *   the victim task's slice to 0 and triggering reschedule on the target CPU.
3082  *
3083  * - migrate_task_rq: Unnecessary as task to cpu mapping is transient.
3084  *
3085  * - task_fork/dead: We need fork/dead notifications for all tasks regardless of
3086  *   their current sched_class. Call them directly from sched core instead.
3087  *
3088  * - task_woken: Unnecessary.
3089  */
3090 DEFINE_SCHED_CLASS(ext) = {
3091 	.enqueue_task		= enqueue_task_scx,
3092 	.dequeue_task		= dequeue_task_scx,
3093 	.yield_task		= yield_task_scx,
3094 	.yield_to_task		= yield_to_task_scx,
3095 
3096 	.wakeup_preempt		= wakeup_preempt_scx,
3097 
3098 	.pick_next_task		= pick_next_task_scx,
3099 
3100 	.put_prev_task		= put_prev_task_scx,
3101 	.set_next_task		= set_next_task_scx,
3102 
3103 #ifdef CONFIG_SMP
3104 	.balance		= balance_scx,
3105 	.select_task_rq		= select_task_rq_scx,
3106 	.set_cpus_allowed	= set_cpus_allowed_scx,
3107 #endif
3108 
3109 	.task_tick		= task_tick_scx,
3110 
3111 	.switching_to		= switching_to_scx,
3112 	.switched_from		= switched_from_scx,
3113 	.switched_to		= switched_to_scx,
3114 	.reweight_task		= reweight_task_scx,
3115 	.prio_changed		= prio_changed_scx,
3116 
3117 	.update_curr		= update_curr_scx,
3118 
3119 #ifdef CONFIG_UCLAMP_TASK
3120 	.uclamp_enabled		= 0,
3121 #endif
3122 };
3123 
3124 static void init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id)
3125 {
3126 	memset(dsq, 0, sizeof(*dsq));
3127 
3128 	raw_spin_lock_init(&dsq->lock);
3129 	INIT_LIST_HEAD(&dsq->list);
3130 	dsq->id = dsq_id;
3131 }
3132 
3133 static struct scx_dispatch_q *create_dsq(u64 dsq_id, int node)
3134 {
3135 	struct scx_dispatch_q *dsq;
3136 	int ret;
3137 
3138 	if (dsq_id & SCX_DSQ_FLAG_BUILTIN)
3139 		return ERR_PTR(-EINVAL);
3140 
3141 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
3142 	if (!dsq)
3143 		return ERR_PTR(-ENOMEM);
3144 
3145 	init_dsq(dsq, dsq_id);
3146 
3147 	ret = rhashtable_insert_fast(&dsq_hash, &dsq->hash_node,
3148 				     dsq_hash_params);
3149 	if (ret) {
3150 		kfree(dsq);
3151 		return ERR_PTR(ret);
3152 	}
3153 	return dsq;
3154 }
3155 
3156 static void free_dsq_irq_workfn(struct irq_work *irq_work)
3157 {
3158 	struct llist_node *to_free = llist_del_all(&dsqs_to_free);
3159 	struct scx_dispatch_q *dsq, *tmp_dsq;
3160 
3161 	llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node)
3162 		kfree_rcu(dsq, rcu);
3163 }
3164 
3165 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn);
3166 
3167 static void destroy_dsq(u64 dsq_id)
3168 {
3169 	struct scx_dispatch_q *dsq;
3170 	unsigned long flags;
3171 
3172 	rcu_read_lock();
3173 
3174 	dsq = find_user_dsq(dsq_id);
3175 	if (!dsq)
3176 		goto out_unlock_rcu;
3177 
3178 	raw_spin_lock_irqsave(&dsq->lock, flags);
3179 
3180 	if (dsq->nr) {
3181 		scx_ops_error("attempting to destroy in-use dsq 0x%016llx (nr=%u)",
3182 			      dsq->id, dsq->nr);
3183 		goto out_unlock_dsq;
3184 	}
3185 
3186 	if (rhashtable_remove_fast(&dsq_hash, &dsq->hash_node, dsq_hash_params))
3187 		goto out_unlock_dsq;
3188 
3189 	/*
3190 	 * Mark dead by invalidating ->id to prevent dispatch_enqueue() from
3191 	 * queueing more tasks. As this function can be called from anywhere,
3192 	 * freeing is bounced through an irq work to avoid nesting RCU
3193 	 * operations inside scheduler locks.
3194 	 */
3195 	dsq->id = SCX_DSQ_INVALID;
3196 	llist_add(&dsq->free_node, &dsqs_to_free);
3197 	irq_work_queue(&free_dsq_irq_work);
3198 
3199 out_unlock_dsq:
3200 	raw_spin_unlock_irqrestore(&dsq->lock, flags);
3201 out_unlock_rcu:
3202 	rcu_read_unlock();
3203 }
3204 
3205 
3206 /********************************************************************************
3207  * Sysfs interface and ops enable/disable.
3208  */
3209 
3210 #define SCX_ATTR(_name)								\
3211 	static struct kobj_attribute scx_attr_##_name = {			\
3212 		.attr = { .name = __stringify(_name), .mode = 0444 },		\
3213 		.show = scx_attr_##_name##_show,				\
3214 	}
3215 
3216 static ssize_t scx_attr_state_show(struct kobject *kobj,
3217 				   struct kobj_attribute *ka, char *buf)
3218 {
3219 	return sysfs_emit(buf, "%s\n",
3220 			  scx_ops_enable_state_str[scx_ops_enable_state()]);
3221 }
3222 SCX_ATTR(state);
3223 
3224 static ssize_t scx_attr_switch_all_show(struct kobject *kobj,
3225 					struct kobj_attribute *ka, char *buf)
3226 {
3227 	return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all));
3228 }
3229 SCX_ATTR(switch_all);
3230 
3231 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj,
3232 					 struct kobj_attribute *ka, char *buf)
3233 {
3234 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected));
3235 }
3236 SCX_ATTR(nr_rejected);
3237 
3238 static struct attribute *scx_global_attrs[] = {
3239 	&scx_attr_state.attr,
3240 	&scx_attr_switch_all.attr,
3241 	&scx_attr_nr_rejected.attr,
3242 	NULL,
3243 };
3244 
3245 static const struct attribute_group scx_global_attr_group = {
3246 	.attrs = scx_global_attrs,
3247 };
3248 
3249 static void scx_kobj_release(struct kobject *kobj)
3250 {
3251 	kfree(kobj);
3252 }
3253 
3254 static ssize_t scx_attr_ops_show(struct kobject *kobj,
3255 				 struct kobj_attribute *ka, char *buf)
3256 {
3257 	return sysfs_emit(buf, "%s\n", scx_ops.name);
3258 }
3259 SCX_ATTR(ops);
3260 
3261 static struct attribute *scx_sched_attrs[] = {
3262 	&scx_attr_ops.attr,
3263 	NULL,
3264 };
3265 ATTRIBUTE_GROUPS(scx_sched);
3266 
3267 static const struct kobj_type scx_ktype = {
3268 	.release = scx_kobj_release,
3269 	.sysfs_ops = &kobj_sysfs_ops,
3270 	.default_groups = scx_sched_groups,
3271 };
3272 
3273 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
3274 {
3275 	return add_uevent_var(env, "SCXOPS=%s", scx_ops.name);
3276 }
3277 
3278 static const struct kset_uevent_ops scx_uevent_ops = {
3279 	.uevent = scx_uevent,
3280 };
3281 
3282 /*
3283  * Used by sched_fork() and __setscheduler_prio() to pick the matching
3284  * sched_class. dl/rt are already handled.
3285  */
3286 bool task_should_scx(struct task_struct *p)
3287 {
3288 	if (!scx_enabled() ||
3289 	    unlikely(scx_ops_enable_state() == SCX_OPS_DISABLING))
3290 		return false;
3291 	if (READ_ONCE(scx_switching_all))
3292 		return true;
3293 	return p->policy == SCHED_EXT;
3294 }
3295 
3296 /**
3297  * scx_ops_bypass - [Un]bypass scx_ops and guarantee forward progress
3298  *
3299  * Bypassing guarantees that all runnable tasks make forward progress without
3300  * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might
3301  * be held by tasks that the BPF scheduler is forgetting to run, which
3302  * unfortunately also excludes toggling the static branches.
3303  *
3304  * Let's work around by overriding a couple ops and modifying behaviors based on
3305  * the DISABLING state and then cycling the queued tasks through dequeue/enqueue
3306  * to force global FIFO scheduling.
3307  *
3308  * a. ops.enqueue() is ignored and tasks are queued in simple global FIFO order.
3309  *
3310  * b. ops.dispatch() is ignored.
3311  *
3312  * c. balance_scx() never sets %SCX_TASK_BAL_KEEP as the slice value can't be
3313  *    trusted. Whenever a tick triggers, the running task is rotated to the tail
3314  *    of the queue.
3315  *
3316  * d. pick_next_task() suppresses zero slice warning.
3317  *
3318  * e. scx_bpf_kick_cpu() is disabled to avoid irq_work malfunction during PM
3319  *    operations.
3320  */
3321 static void scx_ops_bypass(bool bypass)
3322 {
3323 	int depth, cpu;
3324 
3325 	if (bypass) {
3326 		depth = atomic_inc_return(&scx_ops_bypass_depth);
3327 		WARN_ON_ONCE(depth <= 0);
3328 		if (depth != 1)
3329 			return;
3330 	} else {
3331 		depth = atomic_dec_return(&scx_ops_bypass_depth);
3332 		WARN_ON_ONCE(depth < 0);
3333 		if (depth != 0)
3334 			return;
3335 	}
3336 
3337 	/*
3338 	 * We need to guarantee that no tasks are on the BPF scheduler while
3339 	 * bypassing. Either we see enabled or the enable path sees the
3340 	 * increased bypass_depth before moving tasks to SCX.
3341 	 */
3342 	if (!scx_enabled())
3343 		return;
3344 
3345 	/*
3346 	 * No task property is changing. We just need to make sure all currently
3347 	 * queued tasks are re-queued according to the new scx_ops_bypassing()
3348 	 * state. As an optimization, walk each rq's runnable_list instead of
3349 	 * the scx_tasks list.
3350 	 *
3351 	 * This function can't trust the scheduler and thus can't use
3352 	 * cpus_read_lock(). Walk all possible CPUs instead of online.
3353 	 */
3354 	for_each_possible_cpu(cpu) {
3355 		struct rq *rq = cpu_rq(cpu);
3356 		struct rq_flags rf;
3357 		struct task_struct *p, *n;
3358 
3359 		rq_lock_irqsave(rq, &rf);
3360 
3361 		/*
3362 		 * The use of list_for_each_entry_safe_reverse() is required
3363 		 * because each task is going to be removed from and added back
3364 		 * to the runnable_list during iteration. Because they're added
3365 		 * to the tail of the list, safe reverse iteration can still
3366 		 * visit all nodes.
3367 		 */
3368 		list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list,
3369 						 scx.runnable_node) {
3370 			struct sched_enq_and_set_ctx ctx;
3371 
3372 			/* cycling deq/enq is enough, see the function comment */
3373 			sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
3374 			sched_enq_and_set_task(&ctx);
3375 		}
3376 
3377 		rq_unlock_irqrestore(rq, &rf);
3378 
3379 		/* kick to restore ticks */
3380 		resched_cpu(cpu);
3381 	}
3382 }
3383 
3384 static void free_exit_info(struct scx_exit_info *ei)
3385 {
3386 	kfree(ei->dump);
3387 	kfree(ei->msg);
3388 	kfree(ei->bt);
3389 	kfree(ei);
3390 }
3391 
3392 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
3393 {
3394 	struct scx_exit_info *ei;
3395 
3396 	ei = kzalloc(sizeof(*ei), GFP_KERNEL);
3397 	if (!ei)
3398 		return NULL;
3399 
3400 	ei->bt = kcalloc(sizeof(ei->bt[0]), SCX_EXIT_BT_LEN, GFP_KERNEL);
3401 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
3402 	ei->dump = kzalloc(exit_dump_len, GFP_KERNEL);
3403 
3404 	if (!ei->bt || !ei->msg || !ei->dump) {
3405 		free_exit_info(ei);
3406 		return NULL;
3407 	}
3408 
3409 	return ei;
3410 }
3411 
3412 static const char *scx_exit_reason(enum scx_exit_kind kind)
3413 {
3414 	switch (kind) {
3415 	case SCX_EXIT_UNREG:
3416 		return "Scheduler unregistered from user space";
3417 	case SCX_EXIT_UNREG_BPF:
3418 		return "Scheduler unregistered from BPF";
3419 	case SCX_EXIT_UNREG_KERN:
3420 		return "Scheduler unregistered from the main kernel";
3421 	case SCX_EXIT_SYSRQ:
3422 		return "disabled by sysrq-S";
3423 	case SCX_EXIT_ERROR:
3424 		return "runtime error";
3425 	case SCX_EXIT_ERROR_BPF:
3426 		return "scx_bpf_error";
3427 	case SCX_EXIT_ERROR_STALL:
3428 		return "runnable task stall";
3429 	default:
3430 		return "<UNKNOWN>";
3431 	}
3432 }
3433 
3434 static void scx_ops_disable_workfn(struct kthread_work *work)
3435 {
3436 	struct scx_exit_info *ei = scx_exit_info;
3437 	struct scx_task_iter sti;
3438 	struct task_struct *p;
3439 	struct rhashtable_iter rht_iter;
3440 	struct scx_dispatch_q *dsq;
3441 	int i, kind;
3442 
3443 	kind = atomic_read(&scx_exit_kind);
3444 	while (true) {
3445 		/*
3446 		 * NONE indicates that a new scx_ops has been registered since
3447 		 * disable was scheduled - don't kill the new ops. DONE
3448 		 * indicates that the ops has already been disabled.
3449 		 */
3450 		if (kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE)
3451 			return;
3452 		if (atomic_try_cmpxchg(&scx_exit_kind, &kind, SCX_EXIT_DONE))
3453 			break;
3454 	}
3455 	ei->kind = kind;
3456 	ei->reason = scx_exit_reason(ei->kind);
3457 
3458 	/* guarantee forward progress by bypassing scx_ops */
3459 	scx_ops_bypass(true);
3460 
3461 	switch (scx_ops_set_enable_state(SCX_OPS_DISABLING)) {
3462 	case SCX_OPS_DISABLING:
3463 		WARN_ONCE(true, "sched_ext: duplicate disabling instance?");
3464 		break;
3465 	case SCX_OPS_DISABLED:
3466 		pr_warn("sched_ext: ops error detected without ops (%s)\n",
3467 			scx_exit_info->msg);
3468 		WARN_ON_ONCE(scx_ops_set_enable_state(SCX_OPS_DISABLED) !=
3469 			     SCX_OPS_DISABLING);
3470 		goto done;
3471 	default:
3472 		break;
3473 	}
3474 
3475 	/*
3476 	 * Here, every runnable task is guaranteed to make forward progress and
3477 	 * we can safely use blocking synchronization constructs. Actually
3478 	 * disable ops.
3479 	 */
3480 	mutex_lock(&scx_ops_enable_mutex);
3481 
3482 	static_branch_disable(&__scx_switched_all);
3483 	WRITE_ONCE(scx_switching_all, false);
3484 
3485 	/*
3486 	 * Avoid racing against fork. See scx_ops_enable() for explanation on
3487 	 * the locking order.
3488 	 */
3489 	percpu_down_write(&scx_fork_rwsem);
3490 	cpus_read_lock();
3491 
3492 	spin_lock_irq(&scx_tasks_lock);
3493 	scx_task_iter_init(&sti);
3494 	/*
3495 	 * Invoke scx_ops_exit_task() on all non-idle tasks, including
3496 	 * TASK_DEAD tasks. Because dead tasks may have a nonzero refcount,
3497 	 * we may not have invoked sched_ext_free() on them by the time a
3498 	 * scheduler is disabled. We must therefore exit the task here, or we'd
3499 	 * fail to invoke ops.exit_task(), as the scheduler will have been
3500 	 * unloaded by the time the task is subsequently exited on the
3501 	 * sched_ext_free() path.
3502 	 */
3503 	while ((p = scx_task_iter_next_locked(&sti, true))) {
3504 		const struct sched_class *old_class = p->sched_class;
3505 		struct sched_enq_and_set_ctx ctx;
3506 
3507 		if (READ_ONCE(p->__state) != TASK_DEAD) {
3508 			sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE,
3509 					       &ctx);
3510 
3511 			p->scx.slice = min_t(u64, p->scx.slice, SCX_SLICE_DFL);
3512 			__setscheduler_prio(p, p->prio);
3513 			check_class_changing(task_rq(p), p, old_class);
3514 
3515 			sched_enq_and_set_task(&ctx);
3516 
3517 			check_class_changed(task_rq(p), p, old_class, p->prio);
3518 		}
3519 		scx_ops_exit_task(p);
3520 	}
3521 	scx_task_iter_exit(&sti);
3522 	spin_unlock_irq(&scx_tasks_lock);
3523 
3524 	/* no task is on scx, turn off all the switches and flush in-progress calls */
3525 	static_branch_disable_cpuslocked(&__scx_ops_enabled);
3526 	for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++)
3527 		static_branch_disable_cpuslocked(&scx_has_op[i]);
3528 	static_branch_disable_cpuslocked(&scx_ops_enq_last);
3529 	static_branch_disable_cpuslocked(&scx_ops_enq_exiting);
3530 	static_branch_disable_cpuslocked(&scx_ops_cpu_preempt);
3531 	static_branch_disable_cpuslocked(&scx_builtin_idle_enabled);
3532 	synchronize_rcu();
3533 
3534 	cpus_read_unlock();
3535 	percpu_up_write(&scx_fork_rwsem);
3536 
3537 	if (ei->kind >= SCX_EXIT_ERROR) {
3538 		printk(KERN_ERR "sched_ext: BPF scheduler \"%s\" errored, disabling\n", scx_ops.name);
3539 
3540 		if (ei->msg[0] == '\0')
3541 			printk(KERN_ERR "sched_ext: %s\n", ei->reason);
3542 		else
3543 			printk(KERN_ERR "sched_ext: %s (%s)\n", ei->reason, ei->msg);
3544 
3545 		stack_trace_print(ei->bt, ei->bt_len, 2);
3546 	}
3547 
3548 	if (scx_ops.exit)
3549 		SCX_CALL_OP(SCX_KF_UNLOCKED, exit, ei);
3550 
3551 	cancel_delayed_work_sync(&scx_watchdog_work);
3552 
3553 	/*
3554 	 * Delete the kobject from the hierarchy eagerly in addition to just
3555 	 * dropping a reference. Otherwise, if the object is deleted
3556 	 * asynchronously, sysfs could observe an object of the same name still
3557 	 * in the hierarchy when another scheduler is loaded.
3558 	 */
3559 	kobject_del(scx_root_kobj);
3560 	kobject_put(scx_root_kobj);
3561 	scx_root_kobj = NULL;
3562 
3563 	memset(&scx_ops, 0, sizeof(scx_ops));
3564 
3565 	rhashtable_walk_enter(&dsq_hash, &rht_iter);
3566 	do {
3567 		rhashtable_walk_start(&rht_iter);
3568 
3569 		while ((dsq = rhashtable_walk_next(&rht_iter)) && !IS_ERR(dsq))
3570 			destroy_dsq(dsq->id);
3571 
3572 		rhashtable_walk_stop(&rht_iter);
3573 	} while (dsq == ERR_PTR(-EAGAIN));
3574 	rhashtable_walk_exit(&rht_iter);
3575 
3576 	free_percpu(scx_dsp_ctx);
3577 	scx_dsp_ctx = NULL;
3578 	scx_dsp_max_batch = 0;
3579 
3580 	free_exit_info(scx_exit_info);
3581 	scx_exit_info = NULL;
3582 
3583 	mutex_unlock(&scx_ops_enable_mutex);
3584 
3585 	WARN_ON_ONCE(scx_ops_set_enable_state(SCX_OPS_DISABLED) !=
3586 		     SCX_OPS_DISABLING);
3587 done:
3588 	scx_ops_bypass(false);
3589 }
3590 
3591 static DEFINE_KTHREAD_WORK(scx_ops_disable_work, scx_ops_disable_workfn);
3592 
3593 static void schedule_scx_ops_disable_work(void)
3594 {
3595 	struct kthread_worker *helper = READ_ONCE(scx_ops_helper);
3596 
3597 	/*
3598 	 * We may be called spuriously before the first bpf_sched_ext_reg(). If
3599 	 * scx_ops_helper isn't set up yet, there's nothing to do.
3600 	 */
3601 	if (helper)
3602 		kthread_queue_work(helper, &scx_ops_disable_work);
3603 }
3604 
3605 static void scx_ops_disable(enum scx_exit_kind kind)
3606 {
3607 	int none = SCX_EXIT_NONE;
3608 
3609 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
3610 		kind = SCX_EXIT_ERROR;
3611 
3612 	atomic_try_cmpxchg(&scx_exit_kind, &none, kind);
3613 
3614 	schedule_scx_ops_disable_work();
3615 }
3616 
3617 static void dump_newline(struct seq_buf *s)
3618 {
3619 	trace_sched_ext_dump("");
3620 
3621 	/* @s may be zero sized and seq_buf triggers WARN if so */
3622 	if (s->size)
3623 		seq_buf_putc(s, '\n');
3624 }
3625 
3626 static __printf(2, 3) void dump_line(struct seq_buf *s, const char *fmt, ...)
3627 {
3628 	va_list args;
3629 
3630 #ifdef CONFIG_TRACEPOINTS
3631 	if (trace_sched_ext_dump_enabled()) {
3632 		/* protected by scx_dump_state()::dump_lock */
3633 		static char line_buf[SCX_EXIT_MSG_LEN];
3634 
3635 		va_start(args, fmt);
3636 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
3637 		va_end(args);
3638 
3639 		trace_sched_ext_dump(line_buf);
3640 	}
3641 #endif
3642 	/* @s may be zero sized and seq_buf triggers WARN if so */
3643 	if (s->size) {
3644 		va_start(args, fmt);
3645 		seq_buf_vprintf(s, fmt, args);
3646 		va_end(args);
3647 
3648 		seq_buf_putc(s, '\n');
3649 	}
3650 }
3651 
3652 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
3653 			     const unsigned long *bt, unsigned int len)
3654 {
3655 	unsigned int i;
3656 
3657 	for (i = 0; i < len; i++)
3658 		dump_line(s, "%s%pS", prefix, (void *)bt[i]);
3659 }
3660 
3661 static void ops_dump_init(struct seq_buf *s, const char *prefix)
3662 {
3663 	struct scx_dump_data *dd = &scx_dump_data;
3664 
3665 	lockdep_assert_irqs_disabled();
3666 
3667 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
3668 	dd->first = true;
3669 	dd->cursor = 0;
3670 	dd->s = s;
3671 	dd->prefix = prefix;
3672 }
3673 
3674 static void ops_dump_flush(void)
3675 {
3676 	struct scx_dump_data *dd = &scx_dump_data;
3677 	char *line = dd->buf.line;
3678 
3679 	if (!dd->cursor)
3680 		return;
3681 
3682 	/*
3683 	 * There's something to flush and this is the first line. Insert a blank
3684 	 * line to distinguish ops dump.
3685 	 */
3686 	if (dd->first) {
3687 		dump_newline(dd->s);
3688 		dd->first = false;
3689 	}
3690 
3691 	/*
3692 	 * There may be multiple lines in $line. Scan and emit each line
3693 	 * separately.
3694 	 */
3695 	while (true) {
3696 		char *end = line;
3697 		char c;
3698 
3699 		while (*end != '\n' && *end != '\0')
3700 			end++;
3701 
3702 		/*
3703 		 * If $line overflowed, it may not have newline at the end.
3704 		 * Always emit with a newline.
3705 		 */
3706 		c = *end;
3707 		*end = '\0';
3708 		dump_line(dd->s, "%s%s", dd->prefix, line);
3709 		if (c == '\0')
3710 			break;
3711 
3712 		/* move to the next line */
3713 		end++;
3714 		if (*end == '\0')
3715 			break;
3716 		line = end;
3717 	}
3718 
3719 	dd->cursor = 0;
3720 }
3721 
3722 static void ops_dump_exit(void)
3723 {
3724 	ops_dump_flush();
3725 	scx_dump_data.cpu = -1;
3726 }
3727 
3728 static void scx_dump_task(struct seq_buf *s, struct scx_dump_ctx *dctx,
3729 			  struct task_struct *p, char marker)
3730 {
3731 	static unsigned long bt[SCX_EXIT_BT_LEN];
3732 	char dsq_id_buf[19] = "(n/a)";
3733 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
3734 	unsigned int bt_len;
3735 
3736 	if (p->scx.dsq)
3737 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
3738 			  (unsigned long long)p->scx.dsq->id);
3739 
3740 	dump_newline(s);
3741 	dump_line(s, " %c%c %s[%d] %+ldms",
3742 		  marker, task_state_to_char(p), p->comm, p->pid,
3743 		  jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
3744 	dump_line(s, "      scx_state/flags=%u/0x%x ops_state/qseq=%lu/%lu",
3745 		  scx_get_task_state(p), p->scx.flags & ~SCX_TASK_STATE_MASK,
3746 		  ops_state & SCX_OPSS_STATE_MASK,
3747 		  ops_state >> SCX_OPSS_QSEQ_SHIFT);
3748 	dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
3749 		  p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
3750 	dump_line(s, "      cpus=%*pb", cpumask_pr_args(p->cpus_ptr));
3751 
3752 	if (SCX_HAS_OP(dump_task)) {
3753 		ops_dump_init(s, "    ");
3754 		SCX_CALL_OP(SCX_KF_REST, dump_task, dctx, p);
3755 		ops_dump_exit();
3756 	}
3757 
3758 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
3759 	if (bt_len) {
3760 		dump_newline(s);
3761 		dump_stack_trace(s, "    ", bt, bt_len);
3762 	}
3763 }
3764 
3765 static void scx_dump_state(struct scx_exit_info *ei, size_t dump_len)
3766 {
3767 	static DEFINE_SPINLOCK(dump_lock);
3768 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
3769 	struct scx_dump_ctx dctx = {
3770 		.kind = ei->kind,
3771 		.exit_code = ei->exit_code,
3772 		.reason = ei->reason,
3773 		.at_ns = ktime_get_ns(),
3774 		.at_jiffies = jiffies,
3775 	};
3776 	struct seq_buf s;
3777 	unsigned long flags;
3778 	char *buf;
3779 	int cpu;
3780 
3781 	spin_lock_irqsave(&dump_lock, flags);
3782 
3783 	seq_buf_init(&s, ei->dump, dump_len);
3784 
3785 	if (ei->kind == SCX_EXIT_NONE) {
3786 		dump_line(&s, "Debug dump triggered by %s", ei->reason);
3787 	} else {
3788 		dump_line(&s, "%s[%d] triggered exit kind %d:",
3789 			  current->comm, current->pid, ei->kind);
3790 		dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
3791 		dump_newline(&s);
3792 		dump_line(&s, "Backtrace:");
3793 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
3794 	}
3795 
3796 	if (SCX_HAS_OP(dump)) {
3797 		ops_dump_init(&s, "");
3798 		SCX_CALL_OP(SCX_KF_UNLOCKED, dump, &dctx);
3799 		ops_dump_exit();
3800 	}
3801 
3802 	dump_newline(&s);
3803 	dump_line(&s, "CPU states");
3804 	dump_line(&s, "----------");
3805 
3806 	for_each_possible_cpu(cpu) {
3807 		struct rq *rq = cpu_rq(cpu);
3808 		struct rq_flags rf;
3809 		struct task_struct *p;
3810 		struct seq_buf ns;
3811 		size_t avail, used;
3812 		bool idle;
3813 
3814 		rq_lock(rq, &rf);
3815 
3816 		idle = list_empty(&rq->scx.runnable_list) &&
3817 			rq->curr->sched_class == &idle_sched_class;
3818 
3819 		if (idle && !SCX_HAS_OP(dump_cpu))
3820 			goto next;
3821 
3822 		/*
3823 		 * We don't yet know whether ops.dump_cpu() will produce output
3824 		 * and we may want to skip the default CPU dump if it doesn't.
3825 		 * Use a nested seq_buf to generate the standard dump so that we
3826 		 * can decide whether to commit later.
3827 		 */
3828 		avail = seq_buf_get_buf(&s, &buf);
3829 		seq_buf_init(&ns, buf, avail);
3830 
3831 		dump_newline(&ns);
3832 		dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu pnt_seq=%lu",
3833 			  cpu, rq->scx.nr_running, rq->scx.flags,
3834 			  rq->scx.cpu_released, rq->scx.ops_qseq,
3835 			  rq->scx.pnt_seq);
3836 		dump_line(&ns, "          curr=%s[%d] class=%ps",
3837 			  rq->curr->comm, rq->curr->pid,
3838 			  rq->curr->sched_class);
3839 		if (!cpumask_empty(rq->scx.cpus_to_kick))
3840 			dump_line(&ns, "  cpus_to_kick   : %*pb",
3841 				  cpumask_pr_args(rq->scx.cpus_to_kick));
3842 		if (!cpumask_empty(rq->scx.cpus_to_kick_if_idle))
3843 			dump_line(&ns, "  idle_to_kick   : %*pb",
3844 				  cpumask_pr_args(rq->scx.cpus_to_kick_if_idle));
3845 		if (!cpumask_empty(rq->scx.cpus_to_preempt))
3846 			dump_line(&ns, "  cpus_to_preempt: %*pb",
3847 				  cpumask_pr_args(rq->scx.cpus_to_preempt));
3848 		if (!cpumask_empty(rq->scx.cpus_to_wait))
3849 			dump_line(&ns, "  cpus_to_wait   : %*pb",
3850 				  cpumask_pr_args(rq->scx.cpus_to_wait));
3851 
3852 		used = seq_buf_used(&ns);
3853 		if (SCX_HAS_OP(dump_cpu)) {
3854 			ops_dump_init(&ns, "  ");
3855 			SCX_CALL_OP(SCX_KF_REST, dump_cpu, &dctx, cpu, idle);
3856 			ops_dump_exit();
3857 		}
3858 
3859 		/*
3860 		 * If idle && nothing generated by ops.dump_cpu(), there's
3861 		 * nothing interesting. Skip.
3862 		 */
3863 		if (idle && used == seq_buf_used(&ns))
3864 			goto next;
3865 
3866 		/*
3867 		 * $s may already have overflowed when $ns was created. If so,
3868 		 * calling commit on it will trigger BUG.
3869 		 */
3870 		if (avail) {
3871 			seq_buf_commit(&s, seq_buf_used(&ns));
3872 			if (seq_buf_has_overflowed(&ns))
3873 				seq_buf_set_overflow(&s);
3874 		}
3875 
3876 		if (rq->curr->sched_class == &ext_sched_class)
3877 			scx_dump_task(&s, &dctx, rq->curr, '*');
3878 
3879 		list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
3880 			scx_dump_task(&s, &dctx, p, ' ');
3881 	next:
3882 		rq_unlock(rq, &rf);
3883 	}
3884 
3885 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
3886 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
3887 		       trunc_marker, sizeof(trunc_marker));
3888 
3889 	spin_unlock_irqrestore(&dump_lock, flags);
3890 }
3891 
3892 static void scx_ops_error_irq_workfn(struct irq_work *irq_work)
3893 {
3894 	struct scx_exit_info *ei = scx_exit_info;
3895 
3896 	if (ei->kind >= SCX_EXIT_ERROR)
3897 		scx_dump_state(ei, scx_ops.exit_dump_len);
3898 
3899 	schedule_scx_ops_disable_work();
3900 }
3901 
3902 static DEFINE_IRQ_WORK(scx_ops_error_irq_work, scx_ops_error_irq_workfn);
3903 
3904 static __printf(3, 4) void scx_ops_exit_kind(enum scx_exit_kind kind,
3905 					     s64 exit_code,
3906 					     const char *fmt, ...)
3907 {
3908 	struct scx_exit_info *ei = scx_exit_info;
3909 	int none = SCX_EXIT_NONE;
3910 	va_list args;
3911 
3912 	if (!atomic_try_cmpxchg(&scx_exit_kind, &none, kind))
3913 		return;
3914 
3915 	ei->exit_code = exit_code;
3916 
3917 	if (kind >= SCX_EXIT_ERROR)
3918 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
3919 
3920 	va_start(args, fmt);
3921 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
3922 	va_end(args);
3923 
3924 	/*
3925 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
3926 	 * in scx_ops_disable_workfn().
3927 	 */
3928 	ei->kind = kind;
3929 	ei->reason = scx_exit_reason(ei->kind);
3930 
3931 	irq_work_queue(&scx_ops_error_irq_work);
3932 }
3933 
3934 static struct kthread_worker *scx_create_rt_helper(const char *name)
3935 {
3936 	struct kthread_worker *helper;
3937 
3938 	helper = kthread_create_worker(0, name);
3939 	if (helper)
3940 		sched_set_fifo(helper->task);
3941 	return helper;
3942 }
3943 
3944 static int validate_ops(const struct sched_ext_ops *ops)
3945 {
3946 	/*
3947 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
3948 	 * ops.enqueue() callback isn't implemented.
3949 	 */
3950 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
3951 		scx_ops_error("SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
3952 		return -EINVAL;
3953 	}
3954 
3955 	return 0;
3956 }
3957 
3958 static int scx_ops_enable(struct sched_ext_ops *ops, struct bpf_link *link)
3959 {
3960 	struct scx_task_iter sti;
3961 	struct task_struct *p;
3962 	unsigned long timeout;
3963 	int i, ret;
3964 
3965 	mutex_lock(&scx_ops_enable_mutex);
3966 
3967 	if (!scx_ops_helper) {
3968 		WRITE_ONCE(scx_ops_helper,
3969 			   scx_create_rt_helper("sched_ext_ops_helper"));
3970 		if (!scx_ops_helper) {
3971 			ret = -ENOMEM;
3972 			goto err_unlock;
3973 		}
3974 	}
3975 
3976 	if (scx_ops_enable_state() != SCX_OPS_DISABLED) {
3977 		ret = -EBUSY;
3978 		goto err_unlock;
3979 	}
3980 
3981 	scx_root_kobj = kzalloc(sizeof(*scx_root_kobj), GFP_KERNEL);
3982 	if (!scx_root_kobj) {
3983 		ret = -ENOMEM;
3984 		goto err_unlock;
3985 	}
3986 
3987 	scx_root_kobj->kset = scx_kset;
3988 	ret = kobject_init_and_add(scx_root_kobj, &scx_ktype, NULL, "root");
3989 	if (ret < 0)
3990 		goto err;
3991 
3992 	scx_exit_info = alloc_exit_info(ops->exit_dump_len);
3993 	if (!scx_exit_info) {
3994 		ret = -ENOMEM;
3995 		goto err_del;
3996 	}
3997 
3998 	/*
3999 	 * Set scx_ops, transition to PREPPING and clear exit info to arm the
4000 	 * disable path. Failure triggers full disabling from here on.
4001 	 */
4002 	scx_ops = *ops;
4003 
4004 	WARN_ON_ONCE(scx_ops_set_enable_state(SCX_OPS_PREPPING) !=
4005 		     SCX_OPS_DISABLED);
4006 
4007 	atomic_set(&scx_exit_kind, SCX_EXIT_NONE);
4008 	scx_warned_zero_slice = false;
4009 
4010 	atomic_long_set(&scx_nr_rejected, 0);
4011 
4012 	/*
4013 	 * Keep CPUs stable during enable so that the BPF scheduler can track
4014 	 * online CPUs by watching ->on/offline_cpu() after ->init().
4015 	 */
4016 	cpus_read_lock();
4017 
4018 	if (scx_ops.init) {
4019 		ret = SCX_CALL_OP_RET(SCX_KF_SLEEPABLE, init);
4020 		if (ret) {
4021 			ret = ops_sanitize_err("init", ret);
4022 			goto err_disable_unlock_cpus;
4023 		}
4024 	}
4025 
4026 	cpus_read_unlock();
4027 
4028 	ret = validate_ops(ops);
4029 	if (ret)
4030 		goto err_disable;
4031 
4032 	WARN_ON_ONCE(scx_dsp_ctx);
4033 	scx_dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
4034 	scx_dsp_ctx = __alloc_percpu(struct_size_t(struct scx_dsp_ctx, buf,
4035 						   scx_dsp_max_batch),
4036 				     __alignof__(struct scx_dsp_ctx));
4037 	if (!scx_dsp_ctx) {
4038 		ret = -ENOMEM;
4039 		goto err_disable;
4040 	}
4041 
4042 	if (ops->timeout_ms)
4043 		timeout = msecs_to_jiffies(ops->timeout_ms);
4044 	else
4045 		timeout = SCX_WATCHDOG_MAX_TIMEOUT;
4046 
4047 	WRITE_ONCE(scx_watchdog_timeout, timeout);
4048 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
4049 	queue_delayed_work(system_unbound_wq, &scx_watchdog_work,
4050 			   scx_watchdog_timeout / 2);
4051 
4052 	/*
4053 	 * Lock out forks before opening the floodgate so that they don't wander
4054 	 * into the operations prematurely.
4055 	 *
4056 	 * We don't need to keep the CPUs stable but grab cpus_read_lock() to
4057 	 * ease future locking changes for cgroup suport.
4058 	 *
4059 	 * Note that cpu_hotplug_lock must nest inside scx_fork_rwsem due to the
4060 	 * following dependency chain:
4061 	 *
4062 	 *   scx_fork_rwsem --> pernet_ops_rwsem --> cpu_hotplug_lock
4063 	 */
4064 	percpu_down_write(&scx_fork_rwsem);
4065 	cpus_read_lock();
4066 
4067 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
4068 		if (((void (**)(void))ops)[i])
4069 			static_branch_enable_cpuslocked(&scx_has_op[i]);
4070 
4071 	if (ops->flags & SCX_OPS_ENQ_LAST)
4072 		static_branch_enable_cpuslocked(&scx_ops_enq_last);
4073 
4074 	if (ops->flags & SCX_OPS_ENQ_EXITING)
4075 		static_branch_enable_cpuslocked(&scx_ops_enq_exiting);
4076 	if (scx_ops.cpu_acquire || scx_ops.cpu_release)
4077 		static_branch_enable_cpuslocked(&scx_ops_cpu_preempt);
4078 
4079 	if (!ops->update_idle || (ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE)) {
4080 		reset_idle_masks();
4081 		static_branch_enable_cpuslocked(&scx_builtin_idle_enabled);
4082 	} else {
4083 		static_branch_disable_cpuslocked(&scx_builtin_idle_enabled);
4084 	}
4085 
4086 	static_branch_enable_cpuslocked(&__scx_ops_enabled);
4087 
4088 	/*
4089 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
4090 	 * preventing new tasks from being added. No need to exclude tasks
4091 	 * leaving as sched_ext_free() can handle both prepped and enabled
4092 	 * tasks. Prep all tasks first and then enable them with preemption
4093 	 * disabled.
4094 	 */
4095 	spin_lock_irq(&scx_tasks_lock);
4096 
4097 	scx_task_iter_init(&sti);
4098 	while ((p = scx_task_iter_next_locked(&sti, false))) {
4099 		get_task_struct(p);
4100 		scx_task_iter_rq_unlock(&sti);
4101 		spin_unlock_irq(&scx_tasks_lock);
4102 
4103 		ret = scx_ops_init_task(p, task_group(p), false);
4104 		if (ret) {
4105 			put_task_struct(p);
4106 			spin_lock_irq(&scx_tasks_lock);
4107 			scx_task_iter_exit(&sti);
4108 			spin_unlock_irq(&scx_tasks_lock);
4109 			pr_err("sched_ext: ops.init_task() failed (%d) for %s[%d] while loading\n",
4110 			       ret, p->comm, p->pid);
4111 			goto err_disable_unlock_all;
4112 		}
4113 
4114 		put_task_struct(p);
4115 		spin_lock_irq(&scx_tasks_lock);
4116 	}
4117 	scx_task_iter_exit(&sti);
4118 
4119 	/*
4120 	 * All tasks are prepped but are still ops-disabled. Ensure that
4121 	 * %current can't be scheduled out and switch everyone.
4122 	 * preempt_disable() is necessary because we can't guarantee that
4123 	 * %current won't be starved if scheduled out while switching.
4124 	 */
4125 	preempt_disable();
4126 
4127 	/*
4128 	 * From here on, the disable path must assume that tasks have ops
4129 	 * enabled and need to be recovered.
4130 	 *
4131 	 * Transition to ENABLING fails iff the BPF scheduler has already
4132 	 * triggered scx_bpf_error(). Returning an error code here would lose
4133 	 * the recorded error information. Exit indicating success so that the
4134 	 * error is notified through ops.exit() with all the details.
4135 	 */
4136 	if (!scx_ops_tryset_enable_state(SCX_OPS_ENABLING, SCX_OPS_PREPPING)) {
4137 		preempt_enable();
4138 		spin_unlock_irq(&scx_tasks_lock);
4139 		WARN_ON_ONCE(atomic_read(&scx_exit_kind) == SCX_EXIT_NONE);
4140 		ret = 0;
4141 		goto err_disable_unlock_all;
4142 	}
4143 
4144 	/*
4145 	 * We're fully committed and can't fail. The PREPPED -> ENABLED
4146 	 * transitions here are synchronized against sched_ext_free() through
4147 	 * scx_tasks_lock.
4148 	 */
4149 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
4150 
4151 	scx_task_iter_init(&sti);
4152 	while ((p = scx_task_iter_next_locked(&sti, false))) {
4153 		const struct sched_class *old_class = p->sched_class;
4154 		struct sched_enq_and_set_ctx ctx;
4155 
4156 		sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
4157 
4158 		scx_set_task_state(p, SCX_TASK_READY);
4159 		__setscheduler_prio(p, p->prio);
4160 		check_class_changing(task_rq(p), p, old_class);
4161 
4162 		sched_enq_and_set_task(&ctx);
4163 
4164 		check_class_changed(task_rq(p), p, old_class, p->prio);
4165 	}
4166 	scx_task_iter_exit(&sti);
4167 
4168 	spin_unlock_irq(&scx_tasks_lock);
4169 	preempt_enable();
4170 	cpus_read_unlock();
4171 	percpu_up_write(&scx_fork_rwsem);
4172 
4173 	/* see above ENABLING transition for the explanation on exiting with 0 */
4174 	if (!scx_ops_tryset_enable_state(SCX_OPS_ENABLED, SCX_OPS_ENABLING)) {
4175 		WARN_ON_ONCE(atomic_read(&scx_exit_kind) == SCX_EXIT_NONE);
4176 		ret = 0;
4177 		goto err_disable;
4178 	}
4179 
4180 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
4181 		static_branch_enable(&__scx_switched_all);
4182 
4183 	kobject_uevent(scx_root_kobj, KOBJ_ADD);
4184 	mutex_unlock(&scx_ops_enable_mutex);
4185 
4186 	return 0;
4187 
4188 err_del:
4189 	kobject_del(scx_root_kobj);
4190 err:
4191 	kobject_put(scx_root_kobj);
4192 	scx_root_kobj = NULL;
4193 	if (scx_exit_info) {
4194 		free_exit_info(scx_exit_info);
4195 		scx_exit_info = NULL;
4196 	}
4197 err_unlock:
4198 	mutex_unlock(&scx_ops_enable_mutex);
4199 	return ret;
4200 
4201 err_disable_unlock_all:
4202 	percpu_up_write(&scx_fork_rwsem);
4203 err_disable_unlock_cpus:
4204 	cpus_read_unlock();
4205 err_disable:
4206 	mutex_unlock(&scx_ops_enable_mutex);
4207 	/* must be fully disabled before returning */
4208 	scx_ops_disable(SCX_EXIT_ERROR);
4209 	kthread_flush_work(&scx_ops_disable_work);
4210 	return ret;
4211 }
4212 
4213 
4214 /********************************************************************************
4215  * bpf_struct_ops plumbing.
4216  */
4217 #include <linux/bpf_verifier.h>
4218 #include <linux/bpf.h>
4219 #include <linux/btf.h>
4220 
4221 extern struct btf *btf_vmlinux;
4222 static const struct btf_type *task_struct_type;
4223 static u32 task_struct_type_id;
4224 
4225 static bool set_arg_maybe_null(const char *op, int arg_n, int off, int size,
4226 			       enum bpf_access_type type,
4227 			       const struct bpf_prog *prog,
4228 			       struct bpf_insn_access_aux *info)
4229 {
4230 	struct btf *btf = bpf_get_btf_vmlinux();
4231 	const struct bpf_struct_ops_desc *st_ops_desc;
4232 	const struct btf_member *member;
4233 	const struct btf_type *t;
4234 	u32 btf_id, member_idx;
4235 	const char *mname;
4236 
4237 	/* struct_ops op args are all sequential, 64-bit numbers */
4238 	if (off != arg_n * sizeof(__u64))
4239 		return false;
4240 
4241 	/* btf_id should be the type id of struct sched_ext_ops */
4242 	btf_id = prog->aux->attach_btf_id;
4243 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
4244 	if (!st_ops_desc)
4245 		return false;
4246 
4247 	/* BTF type of struct sched_ext_ops */
4248 	t = st_ops_desc->type;
4249 
4250 	member_idx = prog->expected_attach_type;
4251 	if (member_idx >= btf_type_vlen(t))
4252 		return false;
4253 
4254 	/*
4255 	 * Get the member name of this struct_ops program, which corresponds to
4256 	 * a field in struct sched_ext_ops. For example, the member name of the
4257 	 * dispatch struct_ops program (callback) is "dispatch".
4258 	 */
4259 	member = &btf_type_member(t)[member_idx];
4260 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
4261 
4262 	if (!strcmp(mname, op)) {
4263 		/*
4264 		 * The value is a pointer to a type (struct task_struct) given
4265 		 * by a BTF ID (PTR_TO_BTF_ID). It is trusted (PTR_TRUSTED),
4266 		 * however, can be a NULL (PTR_MAYBE_NULL). The BPF program
4267 		 * should check the pointer to make sure it is not NULL before
4268 		 * using it, or the verifier will reject the program.
4269 		 *
4270 		 * Longer term, this is something that should be addressed by
4271 		 * BTF, and be fully contained within the verifier.
4272 		 */
4273 		info->reg_type = PTR_MAYBE_NULL | PTR_TO_BTF_ID | PTR_TRUSTED;
4274 		info->btf = btf_vmlinux;
4275 		info->btf_id = task_struct_type_id;
4276 
4277 		return true;
4278 	}
4279 
4280 	return false;
4281 }
4282 
4283 static bool bpf_scx_is_valid_access(int off, int size,
4284 				    enum bpf_access_type type,
4285 				    const struct bpf_prog *prog,
4286 				    struct bpf_insn_access_aux *info)
4287 {
4288 	if (type != BPF_READ)
4289 		return false;
4290 	if (set_arg_maybe_null("dispatch", 1, off, size, type, prog, info) ||
4291 	    set_arg_maybe_null("yield", 1, off, size, type, prog, info))
4292 		return true;
4293 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
4294 		return false;
4295 	if (off % size != 0)
4296 		return false;
4297 
4298 	return btf_ctx_access(off, size, type, prog, info);
4299 }
4300 
4301 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
4302 				     const struct bpf_reg_state *reg, int off,
4303 				     int size)
4304 {
4305 	const struct btf_type *t;
4306 
4307 	t = btf_type_by_id(reg->btf, reg->btf_id);
4308 	if (t == task_struct_type) {
4309 		if (off >= offsetof(struct task_struct, scx.slice) &&
4310 		    off + size <= offsetofend(struct task_struct, scx.slice))
4311 			return SCALAR_VALUE;
4312 		if (off >= offsetof(struct task_struct, scx.disallow) &&
4313 		    off + size <= offsetofend(struct task_struct, scx.disallow))
4314 			return SCALAR_VALUE;
4315 	}
4316 
4317 	return -EACCES;
4318 }
4319 
4320 static const struct bpf_func_proto *
4321 bpf_scx_get_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
4322 {
4323 	switch (func_id) {
4324 	case BPF_FUNC_task_storage_get:
4325 		return &bpf_task_storage_get_proto;
4326 	case BPF_FUNC_task_storage_delete:
4327 		return &bpf_task_storage_delete_proto;
4328 	default:
4329 		return bpf_base_func_proto(func_id, prog);
4330 	}
4331 }
4332 
4333 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
4334 	.get_func_proto = bpf_scx_get_func_proto,
4335 	.is_valid_access = bpf_scx_is_valid_access,
4336 	.btf_struct_access = bpf_scx_btf_struct_access,
4337 };
4338 
4339 static int bpf_scx_init_member(const struct btf_type *t,
4340 			       const struct btf_member *member,
4341 			       void *kdata, const void *udata)
4342 {
4343 	const struct sched_ext_ops *uops = udata;
4344 	struct sched_ext_ops *ops = kdata;
4345 	u32 moff = __btf_member_bit_offset(t, member) / 8;
4346 	int ret;
4347 
4348 	switch (moff) {
4349 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
4350 		if (*(u32 *)(udata + moff) > INT_MAX)
4351 			return -E2BIG;
4352 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
4353 		return 1;
4354 	case offsetof(struct sched_ext_ops, flags):
4355 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
4356 			return -EINVAL;
4357 		ops->flags = *(u64 *)(udata + moff);
4358 		return 1;
4359 	case offsetof(struct sched_ext_ops, name):
4360 		ret = bpf_obj_name_cpy(ops->name, uops->name,
4361 				       sizeof(ops->name));
4362 		if (ret < 0)
4363 			return ret;
4364 		if (ret == 0)
4365 			return -EINVAL;
4366 		return 1;
4367 	case offsetof(struct sched_ext_ops, timeout_ms):
4368 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
4369 		    SCX_WATCHDOG_MAX_TIMEOUT)
4370 			return -E2BIG;
4371 		ops->timeout_ms = *(u32 *)(udata + moff);
4372 		return 1;
4373 	case offsetof(struct sched_ext_ops, exit_dump_len):
4374 		ops->exit_dump_len =
4375 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
4376 		return 1;
4377 	}
4378 
4379 	return 0;
4380 }
4381 
4382 static int bpf_scx_check_member(const struct btf_type *t,
4383 				const struct btf_member *member,
4384 				const struct bpf_prog *prog)
4385 {
4386 	u32 moff = __btf_member_bit_offset(t, member) / 8;
4387 
4388 	switch (moff) {
4389 	case offsetof(struct sched_ext_ops, init_task):
4390 	case offsetof(struct sched_ext_ops, init):
4391 	case offsetof(struct sched_ext_ops, exit):
4392 		break;
4393 	default:
4394 		if (prog->sleepable)
4395 			return -EINVAL;
4396 	}
4397 
4398 	return 0;
4399 }
4400 
4401 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
4402 {
4403 	return scx_ops_enable(kdata, link);
4404 }
4405 
4406 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
4407 {
4408 	scx_ops_disable(SCX_EXIT_UNREG);
4409 	kthread_flush_work(&scx_ops_disable_work);
4410 }
4411 
4412 static int bpf_scx_init(struct btf *btf)
4413 {
4414 	u32 type_id;
4415 
4416 	type_id = btf_find_by_name_kind(btf, "task_struct", BTF_KIND_STRUCT);
4417 	if (type_id < 0)
4418 		return -EINVAL;
4419 	task_struct_type = btf_type_by_id(btf, type_id);
4420 	task_struct_type_id = type_id;
4421 
4422 	return 0;
4423 }
4424 
4425 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
4426 {
4427 	/*
4428 	 * sched_ext does not support updating the actively-loaded BPF
4429 	 * scheduler, as registering a BPF scheduler can always fail if the
4430 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
4431 	 * etc. Similarly, we can always race with unregistration happening
4432 	 * elsewhere, such as with sysrq.
4433 	 */
4434 	return -EOPNOTSUPP;
4435 }
4436 
4437 static int bpf_scx_validate(void *kdata)
4438 {
4439 	return 0;
4440 }
4441 
4442 static s32 select_cpu_stub(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
4443 static void enqueue_stub(struct task_struct *p, u64 enq_flags) {}
4444 static void dequeue_stub(struct task_struct *p, u64 enq_flags) {}
4445 static void dispatch_stub(s32 prev_cpu, struct task_struct *p) {}
4446 static void runnable_stub(struct task_struct *p, u64 enq_flags) {}
4447 static void running_stub(struct task_struct *p) {}
4448 static void stopping_stub(struct task_struct *p, bool runnable) {}
4449 static void quiescent_stub(struct task_struct *p, u64 deq_flags) {}
4450 static bool yield_stub(struct task_struct *from, struct task_struct *to) { return false; }
4451 static void set_weight_stub(struct task_struct *p, u32 weight) {}
4452 static void set_cpumask_stub(struct task_struct *p, const struct cpumask *mask) {}
4453 static void update_idle_stub(s32 cpu, bool idle) {}
4454 static void cpu_acquire_stub(s32 cpu, struct scx_cpu_acquire_args *args) {}
4455 static void cpu_release_stub(s32 cpu, struct scx_cpu_release_args *args) {}
4456 static s32 init_task_stub(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
4457 static void exit_task_stub(struct task_struct *p, struct scx_exit_task_args *args) {}
4458 static void enable_stub(struct task_struct *p) {}
4459 static void disable_stub(struct task_struct *p) {}
4460 static s32 init_stub(void) { return -EINVAL; }
4461 static void exit_stub(struct scx_exit_info *info) {}
4462 
4463 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
4464 	.select_cpu = select_cpu_stub,
4465 	.enqueue = enqueue_stub,
4466 	.dequeue = dequeue_stub,
4467 	.dispatch = dispatch_stub,
4468 	.runnable = runnable_stub,
4469 	.running = running_stub,
4470 	.stopping = stopping_stub,
4471 	.quiescent = quiescent_stub,
4472 	.yield = yield_stub,
4473 	.set_weight = set_weight_stub,
4474 	.set_cpumask = set_cpumask_stub,
4475 	.update_idle = update_idle_stub,
4476 	.cpu_acquire = cpu_acquire_stub,
4477 	.cpu_release = cpu_release_stub,
4478 	.init_task = init_task_stub,
4479 	.exit_task = exit_task_stub,
4480 	.enable = enable_stub,
4481 	.disable = disable_stub,
4482 	.init = init_stub,
4483 	.exit = exit_stub,
4484 };
4485 
4486 static struct bpf_struct_ops bpf_sched_ext_ops = {
4487 	.verifier_ops = &bpf_scx_verifier_ops,
4488 	.reg = bpf_scx_reg,
4489 	.unreg = bpf_scx_unreg,
4490 	.check_member = bpf_scx_check_member,
4491 	.init_member = bpf_scx_init_member,
4492 	.init = bpf_scx_init,
4493 	.update = bpf_scx_update,
4494 	.validate = bpf_scx_validate,
4495 	.name = "sched_ext_ops",
4496 	.owner = THIS_MODULE,
4497 	.cfi_stubs = &__bpf_ops_sched_ext_ops
4498 };
4499 
4500 
4501 /********************************************************************************
4502  * System integration and init.
4503  */
4504 
4505 static void sysrq_handle_sched_ext_reset(u8 key)
4506 {
4507 	if (scx_ops_helper)
4508 		scx_ops_disable(SCX_EXIT_SYSRQ);
4509 	else
4510 		pr_info("sched_ext: BPF scheduler not yet used\n");
4511 }
4512 
4513 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
4514 	.handler	= sysrq_handle_sched_ext_reset,
4515 	.help_msg	= "reset-sched-ext(S)",
4516 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
4517 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
4518 };
4519 
4520 static void sysrq_handle_sched_ext_dump(u8 key)
4521 {
4522 	struct scx_exit_info ei = { .kind = SCX_EXIT_NONE, .reason = "SysRq-D" };
4523 
4524 	if (scx_enabled())
4525 		scx_dump_state(&ei, 0);
4526 }
4527 
4528 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
4529 	.handler	= sysrq_handle_sched_ext_dump,
4530 	.help_msg	= "dump-sched-ext(D)",
4531 	.action_msg	= "Trigger sched_ext debug dump",
4532 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
4533 };
4534 
4535 static bool can_skip_idle_kick(struct rq *rq)
4536 {
4537 	lockdep_assert_rq_held(rq);
4538 
4539 	/*
4540 	 * We can skip idle kicking if @rq is going to go through at least one
4541 	 * full SCX scheduling cycle before going idle. Just checking whether
4542 	 * curr is not idle is insufficient because we could be racing
4543 	 * balance_one() trying to pull the next task from a remote rq, which
4544 	 * may fail, and @rq may become idle afterwards.
4545 	 *
4546 	 * The race window is small and we don't and can't guarantee that @rq is
4547 	 * only kicked while idle anyway. Skip only when sure.
4548 	 */
4549 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_BALANCING);
4550 }
4551 
4552 static bool kick_one_cpu(s32 cpu, struct rq *this_rq, unsigned long *pseqs)
4553 {
4554 	struct rq *rq = cpu_rq(cpu);
4555 	struct scx_rq *this_scx = &this_rq->scx;
4556 	bool should_wait = false;
4557 	unsigned long flags;
4558 
4559 	raw_spin_rq_lock_irqsave(rq, flags);
4560 
4561 	/*
4562 	 * During CPU hotplug, a CPU may depend on kicking itself to make
4563 	 * forward progress. Allow kicking self regardless of online state.
4564 	 */
4565 	if (cpu_online(cpu) || cpu == cpu_of(this_rq)) {
4566 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_preempt)) {
4567 			if (rq->curr->sched_class == &ext_sched_class)
4568 				rq->curr->scx.slice = 0;
4569 			cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
4570 		}
4571 
4572 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_wait)) {
4573 			pseqs[cpu] = rq->scx.pnt_seq;
4574 			should_wait = true;
4575 		}
4576 
4577 		resched_curr(rq);
4578 	} else {
4579 		cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
4580 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
4581 	}
4582 
4583 	raw_spin_rq_unlock_irqrestore(rq, flags);
4584 
4585 	return should_wait;
4586 }
4587 
4588 static void kick_one_cpu_if_idle(s32 cpu, struct rq *this_rq)
4589 {
4590 	struct rq *rq = cpu_rq(cpu);
4591 	unsigned long flags;
4592 
4593 	raw_spin_rq_lock_irqsave(rq, flags);
4594 
4595 	if (!can_skip_idle_kick(rq) &&
4596 	    (cpu_online(cpu) || cpu == cpu_of(this_rq)))
4597 		resched_curr(rq);
4598 
4599 	raw_spin_rq_unlock_irqrestore(rq, flags);
4600 }
4601 
4602 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
4603 {
4604 	struct rq *this_rq = this_rq();
4605 	struct scx_rq *this_scx = &this_rq->scx;
4606 	unsigned long *pseqs = this_cpu_ptr(scx_kick_cpus_pnt_seqs);
4607 	bool should_wait = false;
4608 	s32 cpu;
4609 
4610 	for_each_cpu(cpu, this_scx->cpus_to_kick) {
4611 		should_wait |= kick_one_cpu(cpu, this_rq, pseqs);
4612 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick);
4613 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
4614 	}
4615 
4616 	for_each_cpu(cpu, this_scx->cpus_to_kick_if_idle) {
4617 		kick_one_cpu_if_idle(cpu, this_rq);
4618 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
4619 	}
4620 
4621 	if (!should_wait)
4622 		return;
4623 
4624 	for_each_cpu(cpu, this_scx->cpus_to_wait) {
4625 		unsigned long *wait_pnt_seq = &cpu_rq(cpu)->scx.pnt_seq;
4626 
4627 		if (cpu != cpu_of(this_rq)) {
4628 			/*
4629 			 * Pairs with smp_store_release() issued by this CPU in
4630 			 * scx_next_task_picked() on the resched path.
4631 			 *
4632 			 * We busy-wait here to guarantee that no other task can
4633 			 * be scheduled on our core before the target CPU has
4634 			 * entered the resched path.
4635 			 */
4636 			while (smp_load_acquire(wait_pnt_seq) == pseqs[cpu])
4637 				cpu_relax();
4638 		}
4639 
4640 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
4641 	}
4642 }
4643 
4644 /**
4645  * print_scx_info - print out sched_ext scheduler state
4646  * @log_lvl: the log level to use when printing
4647  * @p: target task
4648  *
4649  * If a sched_ext scheduler is enabled, print the name and state of the
4650  * scheduler. If @p is on sched_ext, print further information about the task.
4651  *
4652  * This function can be safely called on any task as long as the task_struct
4653  * itself is accessible. While safe, this function isn't synchronized and may
4654  * print out mixups or garbages of limited length.
4655  */
4656 void print_scx_info(const char *log_lvl, struct task_struct *p)
4657 {
4658 	enum scx_ops_enable_state state = scx_ops_enable_state();
4659 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
4660 	char runnable_at_buf[22] = "?";
4661 	struct sched_class *class;
4662 	unsigned long runnable_at;
4663 
4664 	if (state == SCX_OPS_DISABLED)
4665 		return;
4666 
4667 	/*
4668 	 * Carefully check if the task was running on sched_ext, and then
4669 	 * carefully copy the time it's been runnable, and its state.
4670 	 */
4671 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
4672 	    class != &ext_sched_class) {
4673 		printk("%sSched_ext: %s (%s%s)", log_lvl, scx_ops.name,
4674 		       scx_ops_enable_state_str[state], all);
4675 		return;
4676 	}
4677 
4678 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
4679 				      sizeof(runnable_at)))
4680 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
4681 			  jiffies_delta_msecs(runnable_at, jiffies));
4682 
4683 	/* print everything onto one line to conserve console space */
4684 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
4685 	       log_lvl, scx_ops.name, scx_ops_enable_state_str[state], all,
4686 	       runnable_at_buf);
4687 }
4688 
4689 void __init init_sched_ext_class(void)
4690 {
4691 	s32 cpu, v;
4692 
4693 	/*
4694 	 * The following is to prevent the compiler from optimizing out the enum
4695 	 * definitions so that BPF scheduler implementations can use them
4696 	 * through the generated vmlinux.h.
4697 	 */
4698 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT);
4699 
4700 	BUG_ON(rhashtable_init(&dsq_hash, &dsq_hash_params));
4701 	init_dsq(&scx_dsq_global, SCX_DSQ_GLOBAL);
4702 #ifdef CONFIG_SMP
4703 	BUG_ON(!alloc_cpumask_var(&idle_masks.cpu, GFP_KERNEL));
4704 	BUG_ON(!alloc_cpumask_var(&idle_masks.smt, GFP_KERNEL));
4705 #endif
4706 	scx_kick_cpus_pnt_seqs =
4707 		__alloc_percpu(sizeof(scx_kick_cpus_pnt_seqs[0]) * nr_cpu_ids,
4708 			       __alignof__(scx_kick_cpus_pnt_seqs[0]));
4709 	BUG_ON(!scx_kick_cpus_pnt_seqs);
4710 
4711 	for_each_possible_cpu(cpu) {
4712 		struct rq *rq = cpu_rq(cpu);
4713 
4714 		init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL);
4715 		INIT_LIST_HEAD(&rq->scx.runnable_list);
4716 
4717 		BUG_ON(!zalloc_cpumask_var(&rq->scx.cpus_to_kick, GFP_KERNEL));
4718 		BUG_ON(!zalloc_cpumask_var(&rq->scx.cpus_to_kick_if_idle, GFP_KERNEL));
4719 		BUG_ON(!zalloc_cpumask_var(&rq->scx.cpus_to_preempt, GFP_KERNEL));
4720 		BUG_ON(!zalloc_cpumask_var(&rq->scx.cpus_to_wait, GFP_KERNEL));
4721 		init_irq_work(&rq->scx.kick_cpus_irq_work, kick_cpus_irq_workfn);
4722 	}
4723 
4724 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
4725 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
4726 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
4727 }
4728 
4729 
4730 /********************************************************************************
4731  * Helpers that can be called from the BPF scheduler.
4732  */
4733 #include <linux/btf_ids.h>
4734 
4735 __bpf_kfunc_start_defs();
4736 
4737 /**
4738  * scx_bpf_create_dsq - Create a custom DSQ
4739  * @dsq_id: DSQ to create
4740  * @node: NUMA node to allocate from
4741  *
4742  * Create a custom DSQ identified by @dsq_id. Can be called from ops.init() and
4743  * ops.init_task().
4744  */
4745 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node)
4746 {
4747 	if (!scx_kf_allowed(SCX_KF_SLEEPABLE))
4748 		return -EINVAL;
4749 
4750 	if (unlikely(node >= (int)nr_node_ids ||
4751 		     (node < 0 && node != NUMA_NO_NODE)))
4752 		return -EINVAL;
4753 	return PTR_ERR_OR_ZERO(create_dsq(dsq_id, node));
4754 }
4755 
4756 __bpf_kfunc_end_defs();
4757 
4758 BTF_KFUNCS_START(scx_kfunc_ids_sleepable)
4759 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_SLEEPABLE)
4760 BTF_KFUNCS_END(scx_kfunc_ids_sleepable)
4761 
4762 static const struct btf_kfunc_id_set scx_kfunc_set_sleepable = {
4763 	.owner			= THIS_MODULE,
4764 	.set			= &scx_kfunc_ids_sleepable,
4765 };
4766 
4767 __bpf_kfunc_start_defs();
4768 
4769 /**
4770  * scx_bpf_select_cpu_dfl - The default implementation of ops.select_cpu()
4771  * @p: task_struct to select a CPU for
4772  * @prev_cpu: CPU @p was on previously
4773  * @wake_flags: %SCX_WAKE_* flags
4774  * @is_idle: out parameter indicating whether the returned CPU is idle
4775  *
4776  * Can only be called from ops.select_cpu() if the built-in CPU selection is
4777  * enabled - ops.update_idle() is missing or %SCX_OPS_KEEP_BUILTIN_IDLE is set.
4778  * @p, @prev_cpu and @wake_flags match ops.select_cpu().
4779  *
4780  * Returns the picked CPU with *@is_idle indicating whether the picked CPU is
4781  * currently idle and thus a good candidate for direct dispatching.
4782  */
4783 __bpf_kfunc s32 scx_bpf_select_cpu_dfl(struct task_struct *p, s32 prev_cpu,
4784 				       u64 wake_flags, bool *is_idle)
4785 {
4786 	if (!scx_kf_allowed(SCX_KF_SELECT_CPU)) {
4787 		*is_idle = false;
4788 		return prev_cpu;
4789 	}
4790 #ifdef CONFIG_SMP
4791 	return scx_select_cpu_dfl(p, prev_cpu, wake_flags, is_idle);
4792 #else
4793 	*is_idle = false;
4794 	return prev_cpu;
4795 #endif
4796 }
4797 
4798 __bpf_kfunc_end_defs();
4799 
4800 BTF_KFUNCS_START(scx_kfunc_ids_select_cpu)
4801 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_RCU)
4802 BTF_KFUNCS_END(scx_kfunc_ids_select_cpu)
4803 
4804 static const struct btf_kfunc_id_set scx_kfunc_set_select_cpu = {
4805 	.owner			= THIS_MODULE,
4806 	.set			= &scx_kfunc_ids_select_cpu,
4807 };
4808 
4809 static bool scx_dispatch_preamble(struct task_struct *p, u64 enq_flags)
4810 {
4811 	if (!scx_kf_allowed(SCX_KF_ENQUEUE | SCX_KF_DISPATCH))
4812 		return false;
4813 
4814 	lockdep_assert_irqs_disabled();
4815 
4816 	if (unlikely(!p)) {
4817 		scx_ops_error("called with NULL task");
4818 		return false;
4819 	}
4820 
4821 	if (unlikely(enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
4822 		scx_ops_error("invalid enq_flags 0x%llx", enq_flags);
4823 		return false;
4824 	}
4825 
4826 	return true;
4827 }
4828 
4829 static void scx_dispatch_commit(struct task_struct *p, u64 dsq_id, u64 enq_flags)
4830 {
4831 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
4832 	struct task_struct *ddsp_task;
4833 
4834 	ddsp_task = __this_cpu_read(direct_dispatch_task);
4835 	if (ddsp_task) {
4836 		mark_direct_dispatch(ddsp_task, p, dsq_id, enq_flags);
4837 		return;
4838 	}
4839 
4840 	if (unlikely(dspc->cursor >= scx_dsp_max_batch)) {
4841 		scx_ops_error("dispatch buffer overflow");
4842 		return;
4843 	}
4844 
4845 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
4846 		.task = p,
4847 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
4848 		.dsq_id = dsq_id,
4849 		.enq_flags = enq_flags,
4850 	};
4851 }
4852 
4853 __bpf_kfunc_start_defs();
4854 
4855 /**
4856  * scx_bpf_dispatch - Dispatch a task into the FIFO queue of a DSQ
4857  * @p: task_struct to dispatch
4858  * @dsq_id: DSQ to dispatch to
4859  * @slice: duration @p can run for in nsecs
4860  * @enq_flags: SCX_ENQ_*
4861  *
4862  * Dispatch @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe
4863  * to call this function spuriously. Can be called from ops.enqueue(),
4864  * ops.select_cpu(), and ops.dispatch().
4865  *
4866  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
4867  * and @p must match the task being enqueued. Also, %SCX_DSQ_LOCAL_ON can't be
4868  * used to target the local DSQ of a CPU other than the enqueueing one. Use
4869  * ops.select_cpu() to be on the target CPU in the first place.
4870  *
4871  * When called from ops.select_cpu(), @enq_flags and @dsp_id are stored, and @p
4872  * will be directly dispatched to the corresponding dispatch queue after
4873  * ops.select_cpu() returns. If @p is dispatched to SCX_DSQ_LOCAL, it will be
4874  * dispatched to the local DSQ of the CPU returned by ops.select_cpu().
4875  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
4876  * task is dispatched.
4877  *
4878  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
4879  * and this function can be called upto ops.dispatch_max_batch times to dispatch
4880  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
4881  * remaining slots. scx_bpf_consume() flushes the batch and resets the counter.
4882  *
4883  * This function doesn't have any locking restrictions and may be called under
4884  * BPF locks (in the future when BPF introduces more flexible locking).
4885  *
4886  * @p is allowed to run for @slice. The scheduling path is triggered on slice
4887  * exhaustion. If zero, the current residual slice is maintained. If
4888  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
4889  * scx_bpf_kick_cpu() to trigger scheduling.
4890  */
4891 __bpf_kfunc void scx_bpf_dispatch(struct task_struct *p, u64 dsq_id, u64 slice,
4892 				  u64 enq_flags)
4893 {
4894 	if (!scx_dispatch_preamble(p, enq_flags))
4895 		return;
4896 
4897 	if (slice)
4898 		p->scx.slice = slice;
4899 	else
4900 		p->scx.slice = p->scx.slice ?: 1;
4901 
4902 	scx_dispatch_commit(p, dsq_id, enq_flags);
4903 }
4904 
4905 __bpf_kfunc_end_defs();
4906 
4907 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
4908 BTF_ID_FLAGS(func, scx_bpf_dispatch, KF_RCU)
4909 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
4910 
4911 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
4912 	.owner			= THIS_MODULE,
4913 	.set			= &scx_kfunc_ids_enqueue_dispatch,
4914 };
4915 
4916 __bpf_kfunc_start_defs();
4917 
4918 /**
4919  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
4920  *
4921  * Can only be called from ops.dispatch().
4922  */
4923 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(void)
4924 {
4925 	if (!scx_kf_allowed(SCX_KF_DISPATCH))
4926 		return 0;
4927 
4928 	return scx_dsp_max_batch - __this_cpu_read(scx_dsp_ctx->cursor);
4929 }
4930 
4931 /**
4932  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
4933  *
4934  * Cancel the latest dispatch. Can be called multiple times to cancel further
4935  * dispatches. Can only be called from ops.dispatch().
4936  */
4937 __bpf_kfunc void scx_bpf_dispatch_cancel(void)
4938 {
4939 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
4940 
4941 	if (!scx_kf_allowed(SCX_KF_DISPATCH))
4942 		return;
4943 
4944 	if (dspc->cursor > 0)
4945 		dspc->cursor--;
4946 	else
4947 		scx_ops_error("dispatch buffer underflow");
4948 }
4949 
4950 /**
4951  * scx_bpf_consume - Transfer a task from a DSQ to the current CPU's local DSQ
4952  * @dsq_id: DSQ to consume
4953  *
4954  * Consume a task from the non-local DSQ identified by @dsq_id and transfer it
4955  * to the current CPU's local DSQ for execution. Can only be called from
4956  * ops.dispatch().
4957  *
4958  * This function flushes the in-flight dispatches from scx_bpf_dispatch() before
4959  * trying to consume the specified DSQ. It may also grab rq locks and thus can't
4960  * be called under any BPF locks.
4961  *
4962  * Returns %true if a task has been consumed, %false if there isn't any task to
4963  * consume.
4964  */
4965 __bpf_kfunc bool scx_bpf_consume(u64 dsq_id)
4966 {
4967 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
4968 	struct scx_dispatch_q *dsq;
4969 
4970 	if (!scx_kf_allowed(SCX_KF_DISPATCH))
4971 		return false;
4972 
4973 	flush_dispatch_buf(dspc->rq, dspc->rf);
4974 
4975 	dsq = find_non_local_dsq(dsq_id);
4976 	if (unlikely(!dsq)) {
4977 		scx_ops_error("invalid DSQ ID 0x%016llx", dsq_id);
4978 		return false;
4979 	}
4980 
4981 	if (consume_dispatch_q(dspc->rq, dspc->rf, dsq)) {
4982 		/*
4983 		 * A successfully consumed task can be dequeued before it starts
4984 		 * running while the CPU is trying to migrate other dispatched
4985 		 * tasks. Bump nr_tasks to tell balance_scx() to retry on empty
4986 		 * local DSQ.
4987 		 */
4988 		dspc->nr_tasks++;
4989 		return true;
4990 	} else {
4991 		return false;
4992 	}
4993 }
4994 
4995 __bpf_kfunc_end_defs();
4996 
4997 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
4998 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots)
4999 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel)
5000 BTF_ID_FLAGS(func, scx_bpf_consume)
5001 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
5002 
5003 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
5004 	.owner			= THIS_MODULE,
5005 	.set			= &scx_kfunc_ids_dispatch,
5006 };
5007 
5008 __bpf_kfunc_start_defs();
5009 
5010 /**
5011  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
5012  *
5013  * Iterate over all of the tasks currently enqueued on the local DSQ of the
5014  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
5015  * processed tasks. Can only be called from ops.cpu_release().
5016  */
5017 __bpf_kfunc u32 scx_bpf_reenqueue_local(void)
5018 {
5019 	u32 nr_enqueued, i;
5020 	struct rq *rq;
5021 
5022 	if (!scx_kf_allowed(SCX_KF_CPU_RELEASE))
5023 		return 0;
5024 
5025 	rq = cpu_rq(smp_processor_id());
5026 	lockdep_assert_rq_held(rq);
5027 
5028 	/*
5029 	 * Get the number of tasks on the local DSQ before iterating over it to
5030 	 * pull off tasks. The enqueue callback below can signal that it wants
5031 	 * the task to stay on the local DSQ, and we want to prevent the BPF
5032 	 * scheduler from causing us to loop indefinitely.
5033 	 */
5034 	nr_enqueued = rq->scx.local_dsq.nr;
5035 	for (i = 0; i < nr_enqueued; i++) {
5036 		struct task_struct *p;
5037 
5038 		p = first_local_task(rq);
5039 		WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) !=
5040 			     SCX_OPSS_NONE);
5041 		WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_QUEUED));
5042 		WARN_ON_ONCE(p->scx.holding_cpu != -1);
5043 		dispatch_dequeue(rq, p);
5044 		do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
5045 	}
5046 
5047 	return nr_enqueued;
5048 }
5049 
5050 __bpf_kfunc_end_defs();
5051 
5052 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
5053 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local)
5054 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
5055 
5056 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
5057 	.owner			= THIS_MODULE,
5058 	.set			= &scx_kfunc_ids_cpu_release,
5059 };
5060 
5061 __bpf_kfunc_start_defs();
5062 
5063 /**
5064  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
5065  * @cpu: cpu to kick
5066  * @flags: %SCX_KICK_* flags
5067  *
5068  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
5069  * trigger rescheduling on a busy CPU. This can be called from any online
5070  * scx_ops operation and the actual kicking is performed asynchronously through
5071  * an irq work.
5072  */
5073 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags)
5074 {
5075 	struct rq *this_rq;
5076 	unsigned long irq_flags;
5077 
5078 	if (!ops_cpu_valid(cpu, NULL))
5079 		return;
5080 
5081 	/*
5082 	 * While bypassing for PM ops, IRQ handling may not be online which can
5083 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
5084 	 * IRQ status update. Suppress kicking.
5085 	 */
5086 	if (scx_ops_bypassing())
5087 		return;
5088 
5089 	local_irq_save(irq_flags);
5090 
5091 	this_rq = this_rq();
5092 
5093 	/*
5094 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
5095 	 * rq locks. We can probably be smarter and avoid bouncing if called
5096 	 * from ops which don't hold a rq lock.
5097 	 */
5098 	if (flags & SCX_KICK_IDLE) {
5099 		struct rq *target_rq = cpu_rq(cpu);
5100 
5101 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT)))
5102 			scx_ops_error("PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
5103 
5104 		if (raw_spin_rq_trylock(target_rq)) {
5105 			if (can_skip_idle_kick(target_rq)) {
5106 				raw_spin_rq_unlock(target_rq);
5107 				goto out;
5108 			}
5109 			raw_spin_rq_unlock(target_rq);
5110 		}
5111 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick_if_idle);
5112 	} else {
5113 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick);
5114 
5115 		if (flags & SCX_KICK_PREEMPT)
5116 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_preempt);
5117 		if (flags & SCX_KICK_WAIT)
5118 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_wait);
5119 	}
5120 
5121 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
5122 out:
5123 	local_irq_restore(irq_flags);
5124 }
5125 
5126 /**
5127  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
5128  * @dsq_id: id of the DSQ
5129  *
5130  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
5131  * -%ENOENT is returned.
5132  */
5133 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id)
5134 {
5135 	struct scx_dispatch_q *dsq;
5136 	s32 ret;
5137 
5138 	preempt_disable();
5139 
5140 	if (dsq_id == SCX_DSQ_LOCAL) {
5141 		ret = READ_ONCE(this_rq()->scx.local_dsq.nr);
5142 		goto out;
5143 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
5144 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
5145 
5146 		if (ops_cpu_valid(cpu, NULL)) {
5147 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
5148 			goto out;
5149 		}
5150 	} else {
5151 		dsq = find_non_local_dsq(dsq_id);
5152 		if (dsq) {
5153 			ret = READ_ONCE(dsq->nr);
5154 			goto out;
5155 		}
5156 	}
5157 	ret = -ENOENT;
5158 out:
5159 	preempt_enable();
5160 	return ret;
5161 }
5162 
5163 /**
5164  * scx_bpf_destroy_dsq - Destroy a custom DSQ
5165  * @dsq_id: DSQ to destroy
5166  *
5167  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
5168  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
5169  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
5170  * which doesn't exist. Can be called from any online scx_ops operations.
5171  */
5172 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id)
5173 {
5174 	destroy_dsq(dsq_id);
5175 }
5176 
5177 __bpf_kfunc_end_defs();
5178 
5179 static s32 __bstr_format(u64 *data_buf, char *line_buf, size_t line_size,
5180 			 char *fmt, unsigned long long *data, u32 data__sz)
5181 {
5182 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
5183 	s32 ret;
5184 
5185 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
5186 	    (data__sz && !data)) {
5187 		scx_ops_error("invalid data=%p and data__sz=%u",
5188 			      (void *)data, data__sz);
5189 		return -EINVAL;
5190 	}
5191 
5192 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
5193 	if (ret < 0) {
5194 		scx_ops_error("failed to read data fields (%d)", ret);
5195 		return ret;
5196 	}
5197 
5198 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
5199 				  &bprintf_data);
5200 	if (ret < 0) {
5201 		scx_ops_error("format preparation failed (%d)", ret);
5202 		return ret;
5203 	}
5204 
5205 	ret = bstr_printf(line_buf, line_size, fmt,
5206 			  bprintf_data.bin_args);
5207 	bpf_bprintf_cleanup(&bprintf_data);
5208 	if (ret < 0) {
5209 		scx_ops_error("(\"%s\", %p, %u) failed to format",
5210 			      fmt, data, data__sz);
5211 		return ret;
5212 	}
5213 
5214 	return ret;
5215 }
5216 
5217 static s32 bstr_format(struct scx_bstr_buf *buf,
5218 		       char *fmt, unsigned long long *data, u32 data__sz)
5219 {
5220 	return __bstr_format(buf->data, buf->line, sizeof(buf->line),
5221 			     fmt, data, data__sz);
5222 }
5223 
5224 __bpf_kfunc_start_defs();
5225 
5226 /**
5227  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
5228  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
5229  * @fmt: error message format string
5230  * @data: format string parameters packaged using ___bpf_fill() macro
5231  * @data__sz: @data len, must end in '__sz' for the verifier
5232  *
5233  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
5234  * disabling.
5235  */
5236 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
5237 				   unsigned long long *data, u32 data__sz)
5238 {
5239 	unsigned long flags;
5240 
5241 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
5242 	if (bstr_format(&scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
5243 		scx_ops_exit_kind(SCX_EXIT_UNREG_BPF, exit_code, "%s",
5244 				  scx_exit_bstr_buf.line);
5245 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
5246 }
5247 
5248 /**
5249  * scx_bpf_error_bstr - Indicate fatal error
5250  * @fmt: error message format string
5251  * @data: format string parameters packaged using ___bpf_fill() macro
5252  * @data__sz: @data len, must end in '__sz' for the verifier
5253  *
5254  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
5255  * disabling.
5256  */
5257 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
5258 				    u32 data__sz)
5259 {
5260 	unsigned long flags;
5261 
5262 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
5263 	if (bstr_format(&scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
5264 		scx_ops_exit_kind(SCX_EXIT_ERROR_BPF, 0, "%s",
5265 				  scx_exit_bstr_buf.line);
5266 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
5267 }
5268 
5269 /**
5270  * scx_bpf_dump - Generate extra debug dump specific to the BPF scheduler
5271  * @fmt: format string
5272  * @data: format string parameters packaged using ___bpf_fill() macro
5273  * @data__sz: @data len, must end in '__sz' for the verifier
5274  *
5275  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
5276  * dump_task() to generate extra debug dump specific to the BPF scheduler.
5277  *
5278  * The extra dump may be multiple lines. A single line may be split over
5279  * multiple calls. The last line is automatically terminated.
5280  */
5281 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
5282 				   u32 data__sz)
5283 {
5284 	struct scx_dump_data *dd = &scx_dump_data;
5285 	struct scx_bstr_buf *buf = &dd->buf;
5286 	s32 ret;
5287 
5288 	if (raw_smp_processor_id() != dd->cpu) {
5289 		scx_ops_error("scx_bpf_dump() must only be called from ops.dump() and friends");
5290 		return;
5291 	}
5292 
5293 	/* append the formatted string to the line buf */
5294 	ret = __bstr_format(buf->data, buf->line + dd->cursor,
5295 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
5296 	if (ret < 0) {
5297 		dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
5298 			  dd->prefix, fmt, data, data__sz, ret);
5299 		return;
5300 	}
5301 
5302 	dd->cursor += ret;
5303 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
5304 
5305 	if (!dd->cursor)
5306 		return;
5307 
5308 	/*
5309 	 * If the line buf overflowed or ends in a newline, flush it into the
5310 	 * dump. This is to allow the caller to generate a single line over
5311 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
5312 	 * the line buf, the only case which can lead to an unexpected
5313 	 * truncation is when the caller keeps generating newlines in the middle
5314 	 * instead of the end consecutively. Don't do that.
5315 	 */
5316 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
5317 		ops_dump_flush();
5318 }
5319 
5320 /**
5321  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
5322  *
5323  * All valid CPU IDs in the system are smaller than the returned value.
5324  */
5325 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
5326 {
5327 	return nr_cpu_ids;
5328 }
5329 
5330 /**
5331  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
5332  */
5333 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
5334 {
5335 	return cpu_possible_mask;
5336 }
5337 
5338 /**
5339  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
5340  */
5341 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
5342 {
5343 	return cpu_online_mask;
5344 }
5345 
5346 /**
5347  * scx_bpf_put_cpumask - Release a possible/online cpumask
5348  * @cpumask: cpumask to release
5349  */
5350 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
5351 {
5352 	/*
5353 	 * Empty function body because we aren't actually acquiring or releasing
5354 	 * a reference to a global cpumask, which is read-only in the caller and
5355 	 * is never released. The acquire / release semantics here are just used
5356 	 * to make the cpumask is a trusted pointer in the caller.
5357 	 */
5358 }
5359 
5360 /**
5361  * scx_bpf_get_idle_cpumask - Get a referenced kptr to the idle-tracking
5362  * per-CPU cpumask.
5363  *
5364  * Returns NULL if idle tracking is not enabled, or running on a UP kernel.
5365  */
5366 __bpf_kfunc const struct cpumask *scx_bpf_get_idle_cpumask(void)
5367 {
5368 	if (!static_branch_likely(&scx_builtin_idle_enabled)) {
5369 		scx_ops_error("built-in idle tracking is disabled");
5370 		return cpu_none_mask;
5371 	}
5372 
5373 #ifdef CONFIG_SMP
5374 	return idle_masks.cpu;
5375 #else
5376 	return cpu_none_mask;
5377 #endif
5378 }
5379 
5380 /**
5381  * scx_bpf_get_idle_smtmask - Get a referenced kptr to the idle-tracking,
5382  * per-physical-core cpumask. Can be used to determine if an entire physical
5383  * core is free.
5384  *
5385  * Returns NULL if idle tracking is not enabled, or running on a UP kernel.
5386  */
5387 __bpf_kfunc const struct cpumask *scx_bpf_get_idle_smtmask(void)
5388 {
5389 	if (!static_branch_likely(&scx_builtin_idle_enabled)) {
5390 		scx_ops_error("built-in idle tracking is disabled");
5391 		return cpu_none_mask;
5392 	}
5393 
5394 #ifdef CONFIG_SMP
5395 	if (sched_smt_active())
5396 		return idle_masks.smt;
5397 	else
5398 		return idle_masks.cpu;
5399 #else
5400 	return cpu_none_mask;
5401 #endif
5402 }
5403 
5404 /**
5405  * scx_bpf_put_idle_cpumask - Release a previously acquired referenced kptr to
5406  * either the percpu, or SMT idle-tracking cpumask.
5407  */
5408 __bpf_kfunc void scx_bpf_put_idle_cpumask(const struct cpumask *idle_mask)
5409 {
5410 	/*
5411 	 * Empty function body because we aren't actually acquiring or releasing
5412 	 * a reference to a global idle cpumask, which is read-only in the
5413 	 * caller and is never released. The acquire / release semantics here
5414 	 * are just used to make the cpumask a trusted pointer in the caller.
5415 	 */
5416 }
5417 
5418 /**
5419  * scx_bpf_test_and_clear_cpu_idle - Test and clear @cpu's idle state
5420  * @cpu: cpu to test and clear idle for
5421  *
5422  * Returns %true if @cpu was idle and its idle state was successfully cleared.
5423  * %false otherwise.
5424  *
5425  * Unavailable if ops.update_idle() is implemented and
5426  * %SCX_OPS_KEEP_BUILTIN_IDLE is not set.
5427  */
5428 __bpf_kfunc bool scx_bpf_test_and_clear_cpu_idle(s32 cpu)
5429 {
5430 	if (!static_branch_likely(&scx_builtin_idle_enabled)) {
5431 		scx_ops_error("built-in idle tracking is disabled");
5432 		return false;
5433 	}
5434 
5435 	if (ops_cpu_valid(cpu, NULL))
5436 		return test_and_clear_cpu_idle(cpu);
5437 	else
5438 		return false;
5439 }
5440 
5441 /**
5442  * scx_bpf_pick_idle_cpu - Pick and claim an idle cpu
5443  * @cpus_allowed: Allowed cpumask
5444  * @flags: %SCX_PICK_IDLE_CPU_* flags
5445  *
5446  * Pick and claim an idle cpu in @cpus_allowed. Returns the picked idle cpu
5447  * number on success. -%EBUSY if no matching cpu was found.
5448  *
5449  * Idle CPU tracking may race against CPU scheduling state transitions. For
5450  * example, this function may return -%EBUSY as CPUs are transitioning into the
5451  * idle state. If the caller then assumes that there will be dispatch events on
5452  * the CPUs as they were all busy, the scheduler may end up stalling with CPUs
5453  * idling while there are pending tasks. Use scx_bpf_pick_any_cpu() and
5454  * scx_bpf_kick_cpu() to guarantee that there will be at least one dispatch
5455  * event in the near future.
5456  *
5457  * Unavailable if ops.update_idle() is implemented and
5458  * %SCX_OPS_KEEP_BUILTIN_IDLE is not set.
5459  */
5460 __bpf_kfunc s32 scx_bpf_pick_idle_cpu(const struct cpumask *cpus_allowed,
5461 				      u64 flags)
5462 {
5463 	if (!static_branch_likely(&scx_builtin_idle_enabled)) {
5464 		scx_ops_error("built-in idle tracking is disabled");
5465 		return -EBUSY;
5466 	}
5467 
5468 	return scx_pick_idle_cpu(cpus_allowed, flags);
5469 }
5470 
5471 /**
5472  * scx_bpf_pick_any_cpu - Pick and claim an idle cpu if available or pick any CPU
5473  * @cpus_allowed: Allowed cpumask
5474  * @flags: %SCX_PICK_IDLE_CPU_* flags
5475  *
5476  * Pick and claim an idle cpu in @cpus_allowed. If none is available, pick any
5477  * CPU in @cpus_allowed. Guaranteed to succeed and returns the picked idle cpu
5478  * number if @cpus_allowed is not empty. -%EBUSY is returned if @cpus_allowed is
5479  * empty.
5480  *
5481  * If ops.update_idle() is implemented and %SCX_OPS_KEEP_BUILTIN_IDLE is not
5482  * set, this function can't tell which CPUs are idle and will always pick any
5483  * CPU.
5484  */
5485 __bpf_kfunc s32 scx_bpf_pick_any_cpu(const struct cpumask *cpus_allowed,
5486 				     u64 flags)
5487 {
5488 	s32 cpu;
5489 
5490 	if (static_branch_likely(&scx_builtin_idle_enabled)) {
5491 		cpu = scx_pick_idle_cpu(cpus_allowed, flags);
5492 		if (cpu >= 0)
5493 			return cpu;
5494 	}
5495 
5496 	cpu = cpumask_any_distribute(cpus_allowed);
5497 	if (cpu < nr_cpu_ids)
5498 		return cpu;
5499 	else
5500 		return -EBUSY;
5501 }
5502 
5503 /**
5504  * scx_bpf_task_running - Is task currently running?
5505  * @p: task of interest
5506  */
5507 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
5508 {
5509 	return task_rq(p)->curr == p;
5510 }
5511 
5512 /**
5513  * scx_bpf_task_cpu - CPU a task is currently associated with
5514  * @p: task of interest
5515  */
5516 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
5517 {
5518 	return task_cpu(p);
5519 }
5520 
5521 __bpf_kfunc_end_defs();
5522 
5523 BTF_KFUNCS_START(scx_kfunc_ids_any)
5524 BTF_ID_FLAGS(func, scx_bpf_kick_cpu)
5525 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued)
5526 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq)
5527 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_TRUSTED_ARGS)
5528 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_TRUSTED_ARGS)
5529 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_TRUSTED_ARGS)
5530 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
5531 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
5532 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
5533 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
5534 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask, KF_ACQUIRE)
5535 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask, KF_ACQUIRE)
5536 BTF_ID_FLAGS(func, scx_bpf_put_idle_cpumask, KF_RELEASE)
5537 BTF_ID_FLAGS(func, scx_bpf_test_and_clear_cpu_idle)
5538 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu, KF_RCU)
5539 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu, KF_RCU)
5540 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
5541 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
5542 BTF_KFUNCS_END(scx_kfunc_ids_any)
5543 
5544 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
5545 	.owner			= THIS_MODULE,
5546 	.set			= &scx_kfunc_ids_any,
5547 };
5548 
5549 static int __init scx_init(void)
5550 {
5551 	int ret;
5552 
5553 	/*
5554 	 * kfunc registration can't be done from init_sched_ext_class() as
5555 	 * register_btf_kfunc_id_set() needs most of the system to be up.
5556 	 *
5557 	 * Some kfuncs are context-sensitive and can only be called from
5558 	 * specific SCX ops. They are grouped into BTF sets accordingly.
5559 	 * Unfortunately, BPF currently doesn't have a way of enforcing such
5560 	 * restrictions. Eventually, the verifier should be able to enforce
5561 	 * them. For now, register them the same and make each kfunc explicitly
5562 	 * check using scx_kf_allowed().
5563 	 */
5564 	if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
5565 					     &scx_kfunc_set_sleepable)) ||
5566 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
5567 					     &scx_kfunc_set_select_cpu)) ||
5568 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
5569 					     &scx_kfunc_set_enqueue_dispatch)) ||
5570 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
5571 					     &scx_kfunc_set_dispatch)) ||
5572 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
5573 					     &scx_kfunc_set_cpu_release)) ||
5574 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
5575 					     &scx_kfunc_set_any)) ||
5576 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
5577 					     &scx_kfunc_set_any)) ||
5578 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
5579 					     &scx_kfunc_set_any))) {
5580 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
5581 		return ret;
5582 	}
5583 
5584 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops);
5585 	if (ret) {
5586 		pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret);
5587 		return ret;
5588 	}
5589 
5590 	scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj);
5591 	if (!scx_kset) {
5592 		pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n");
5593 		return -ENOMEM;
5594 	}
5595 
5596 	ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group);
5597 	if (ret < 0) {
5598 		pr_err("sched_ext: Failed to add global attributes\n");
5599 		return ret;
5600 	}
5601 
5602 	return 0;
5603 }
5604 __initcall(scx_init);
5605