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