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