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