xref: /linux/kernel/sched/ext/ext.c (revision 11260c335ec6071af5543aef73000b28f041c124)
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 #include <linux/bitmap.h>
10 #include <linux/btf_ids.h>
11 #include <linux/rhashtable.h>
12 #include <linux/sched/clock.h>
13 #include <linux/sched/isolation.h>
14 #include <linux/suspend.h>
15 #include <linux/sysrq.h>
16 
17 #include "../pelt.h"
18 #include "internal.h"
19 #include "cid.h"
20 #include "arena.h"
21 #include "idle.h"
22 #include "sub.h"
23 #include "inlines.h"
24 
25 DEFINE_RAW_SPINLOCK(scx_sched_lock);
26 
27 /*
28  * NOTE: sched_ext is in the process of growing multiple scheduler support and
29  * scx_root usage is in a transitional state. Naked dereferences are safe if the
30  * caller is one of the tasks attached to SCX and explicit RCU dereference is
31  * necessary otherwise. Naked scx_root dereferences trigger sparse warnings but
32  * are used as temporary markers to indicate that the dereferences need to be
33  * updated to point to the associated scheduler instances rather than scx_root.
34  */
35 struct scx_sched __rcu *scx_root;
36 
37 /*
38  * All scheds, writers must hold both scx_enable_mutex and scx_sched_lock.
39  * Readers can hold either or rcu_read_lock().
40  */
41 LIST_HEAD(scx_sched_all);
42 
43 #ifdef CONFIG_EXT_SUB_SCHED
44 const struct rhashtable_params scx_sched_hash_params = {
45 	.key_len		= sizeof_field(struct scx_sched, ops.sub_cgroup_id),
46 	.key_offset		= offsetof(struct scx_sched, ops.sub_cgroup_id),
47 	.head_offset		= offsetof(struct scx_sched, hash_node),
48 	.insecure_elasticity	= true,	/* inserted under scx_sched_lock */
49 };
50 
51 struct rhashtable scx_sched_hash;
52 #endif
53 
54 /* see SCX_OPS_TID_TO_TASK */
55 static const struct rhashtable_params scx_tid_hash_params = {
56 	.key_len		= sizeof_field(struct sched_ext_entity, tid),
57 	.key_offset		= offsetof(struct sched_ext_entity, tid),
58 	.head_offset		= offsetof(struct sched_ext_entity, tid_hash_node),
59 	.insecure_elasticity	= true,	/* inserted/removed under scx_tasks_lock */
60 };
61 static struct rhashtable scx_tid_hash;
62 
63 /*
64  * During exit, a task may schedule after losing its PIDs. When disabling the
65  * BPF scheduler, we need to be able to iterate tasks in every state to
66  * guarantee system safety. Maintain a dedicated task list which contains every
67  * task between its fork and eventual free.
68  */
69 static DEFINE_RAW_SPINLOCK(scx_tasks_lock);
70 static LIST_HEAD(scx_tasks);
71 
72 /* ops enable/disable */
73 DEFINE_MUTEX(scx_enable_mutex);
74 DEFINE_STATIC_KEY_FALSE(__scx_enabled);
75 DEFINE_PERCPU_RWSEM(scx_fork_rwsem);
76 static atomic_t scx_enable_state_var = ATOMIC_INIT(SCX_DISABLED);
77 static DEFINE_RAW_SPINLOCK(scx_bypass_lock);
78 static bool scx_init_task_enabled;
79 static bool scx_switching_all;
80 DEFINE_STATIC_KEY_FALSE(__scx_switched_all);
81 static DEFINE_STATIC_KEY_FALSE(__scx_tid_to_task_enabled);
82 
83 /*
84  * Gates cgroup ops delivery. Set at the end of the cgroup init phase of root
85  * enable and cleared before root disable starts tearing down tasks, both under
86  * scx_cgroup_lock(). Holding cgroup_lock() and seeing %true guarantees no race
87  * against root tearing down tasks.
88  */
89 bool scx_cgroup_enabled;
90 
91 /*
92  * True once SCX_OPS_TID_TO_TASK has been negotiated with the root scheduler
93  * and the tid->task table is live. Wraps the static key so callers don't
94  * take the address, and hints "likely enabled" for the common case where
95  * the feature is in use.
96  */
scx_tid_to_task_enabled(void)97 static inline bool scx_tid_to_task_enabled(void)
98 {
99 	return static_branch_likely(&__scx_tid_to_task_enabled);
100 }
101 
102 static atomic_long_t scx_nr_rejected = ATOMIC_LONG_INIT(0);
103 static atomic_long_t scx_hotplug_seq = ATOMIC_LONG_INIT(0);
104 
105 /* Global cursor for the per-CPU tid allocator. Starts at 1; tid 0 is reserved. */
106 static atomic64_t scx_tid_cursor = ATOMIC64_INIT(1);
107 
108 /* is @dsq synchronized by the containing rq lock instead of dsq->lock? */
dsq_is_rq_owned(struct scx_dispatch_q * dsq)109 static bool dsq_is_rq_owned(struct scx_dispatch_q *dsq)
110 {
111 	switch (dsq->id) {
112 	case SCX_DSQ_LOCAL:
113 	case SCX_DSQ_REJECT:
114 	case SCX_DSQ_RESCUE:
115 		return true;
116 	default:
117 		return false;
118 	}
119 }
120 
121 /* Cursor for unique scx_sched instance ids. id 0 is reserved. */
122 static atomic64_t scx_sched_id_cursor = ATOMIC64_INIT(0);
123 
124 #ifdef CONFIG_EXT_SUB_SCHED
125 /*
126  * The sub sched being enabled. Used by scx_disable_and_exit_task() to exit
127  * tasks for the sub-sched being enabled. Use a global variable instead of a
128  * per-task field as all enables are serialized.
129  */
130 struct scx_sched *scx_enabling_sub_sched;
131 #else
132 #define scx_enabling_sub_sched	(struct scx_sched *)NULL
133 #endif	/* CONFIG_EXT_SUB_SCHED */
134 
135 /*
136  * A monotonically increasing sequence number that is incremented every time a
137  * scheduler is enabled. This can be used to check if any custom sched_ext
138  * scheduler has ever been used in the system.
139  */
140 static atomic_long_t scx_enable_seq = ATOMIC_LONG_INIT(0);
141 
142 /*
143  * Watchdog interval. All scx_sched's share a single watchdog timer and the
144  * interval is half of the shortest sch->watchdog_timeout.
145  */
146 static unsigned long scx_watchdog_interval;
147 
148 /*
149  * The last time the delayed work was run. This delayed work relies on
150  * ksoftirqd being able to run to service timer interrupts, so it's possible
151  * that this work itself could get wedged. To account for this, we check that
152  * it's not stalled in the timer tick, and trigger an error if it is.
153  */
154 static unsigned long scx_watchdog_timestamp = INITIAL_JIFFIES;
155 
156 static struct delayed_work scx_watchdog_work;
157 
158 /*
159  * For %SCX_KICK_WAIT: Each CPU has a pointer to an array of kick_sync sequence
160  * numbers. The arrays are allocated with kvzalloc() as size can exceed percpu
161  * allocator limits on large machines. O(nr_cpu_ids^2) allocation, allocated
162  * lazily when enabling and freed when disabling to avoid waste when sched_ext
163  * isn't active.
164  */
165 struct scx_kick_syncs {
166 	struct rcu_head		rcu;
167 	unsigned long		syncs[];
168 };
169 
170 static DEFINE_PER_CPU(struct scx_kick_syncs __rcu *, scx_kick_syncs);
171 
172 /*
173  * Per-CPU buffered allocator state for p->scx.tid. Each CPU pulls a chunk of
174  * SCX_TID_CHUNK ids from scx_tid_cursor and hands them out locally without
175  * further synchronization. See scx_alloc_tid().
176  */
177 struct scx_tid_alloc {
178 	u64	next;
179 	u64	end;
180 };
181 static DEFINE_PER_CPU(struct scx_tid_alloc, scx_tid_alloc);
182 
183 /*
184  * Direct dispatch marker.
185  *
186  * Non-NULL values are used for direct dispatch from enqueue path. A valid
187  * pointer points to the task currently being enqueued. An ERR_PTR value is used
188  * to indicate that direct dispatch has already happened.
189  */
190 static DEFINE_PER_CPU(struct task_struct *, direct_dispatch_task);
191 
192 static const struct rhashtable_params dsq_hash_params = {
193 	.key_len		= sizeof_field(struct scx_dispatch_q, id),
194 	.key_offset		= offsetof(struct scx_dispatch_q, id),
195 	.head_offset		= offsetof(struct scx_dispatch_q, hash_node),
196 };
197 
198 static LLIST_HEAD(dsqs_to_free);
199 
200 /* ops debug dump */
201 static DEFINE_RAW_SPINLOCK(scx_dump_lock);
202 
203 struct scx_dump_data {
204 	s32			cpu;
205 	bool			first;
206 	s32			cursor;
207 	struct seq_buf		*s;
208 	const char		*prefix;
209 	struct scx_bstr_buf	buf;
210 };
211 
212 static struct scx_dump_data scx_dump_data = {
213 	.cpu			= -1,
214 };
215 
216 /* /sys/kernel/sched_ext interface */
217 static struct kset *scx_kset;
218 
219 /*
220  * Parameters that can be adjusted through /sys/module/sched_ext/parameters.
221  * There usually is no reason to modify these as normal scheduler operation
222  * shouldn't be affected by them. The knobs are primarily for debugging.
223  */
224 static unsigned int scx_slice_bypass_us = SCX_SLICE_BYPASS / NSEC_PER_USEC;
225 static unsigned int scx_bypass_lb_intv_us = SCX_BYPASS_LB_DFL_INTV_US;
226 
set_slice_us(const char * val,const struct kernel_param * kp)227 static int set_slice_us(const char *val, const struct kernel_param *kp)
228 {
229 	return param_set_uint_minmax(val, kp, 100, 100 * USEC_PER_MSEC);
230 }
231 
232 static const struct kernel_param_ops slice_us_param_ops = {
233 	.set = set_slice_us,
234 	.get = param_get_uint,
235 };
236 
set_bypass_lb_intv_us(const char * val,const struct kernel_param * kp)237 static int set_bypass_lb_intv_us(const char *val, const struct kernel_param *kp)
238 {
239 	return param_set_uint_minmax(val, kp, 0, 10 * USEC_PER_SEC);
240 }
241 
242 static const struct kernel_param_ops bypass_lb_intv_us_param_ops = {
243 	.set = set_bypass_lb_intv_us,
244 	.get = param_get_uint,
245 };
246 
247 #undef MODULE_PARAM_PREFIX
248 #define MODULE_PARAM_PREFIX	"sched_ext."
249 
250 module_param_cb(slice_bypass_us, &slice_us_param_ops, &scx_slice_bypass_us, 0600);
251 MODULE_PARM_DESC(slice_bypass_us, "bypass slice in microseconds, applied on [un]load (100us to 100ms)");
252 module_param_cb(bypass_lb_intv_us, &bypass_lb_intv_us_param_ops, &scx_bypass_lb_intv_us, 0600);
253 MODULE_PARM_DESC(bypass_lb_intv_us, "bypass load balance interval in microseconds (0 (disable) to 10s)");
254 
255 #undef MODULE_PARAM_PREFIX
256 
257 #define CREATE_TRACE_POINTS
258 #include <trace/events/sched_ext.h>
259 
260 static void run_deferred(struct rq *rq);
261 static bool task_dead_and_done(struct task_struct *p);
262 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind);
263 
__scx_exit(struct scx_sched * sch,enum scx_exit_kind kind,s64 exit_code,s32 exit_cpu,const char * fmt,...)264 __printf(5, 6) bool __scx_exit(struct scx_sched *sch,
265 			       enum scx_exit_kind kind, s64 exit_code,
266 			       s32 exit_cpu, const char *fmt, ...)
267 {
268 	va_list args;
269 	bool ret;
270 
271 	va_start(args, fmt);
272 	ret = scx_vexit(sch, kind, exit_code, exit_cpu, fmt, args);
273 	va_end(args);
274 
275 	return ret;
276 }
277 
jiffies_delta_msecs(unsigned long at,unsigned long now)278 static long jiffies_delta_msecs(unsigned long at, unsigned long now)
279 {
280 	if (time_after(at, now))
281 		return jiffies_to_msecs(at - now);
282 	else
283 		return -(long)jiffies_to_msecs(now - at);
284 }
285 
u32_before(u32 a,u32 b)286 static bool u32_before(u32 a, u32 b)
287 {
288 	return (s32)(a - b) < 0;
289 }
290 
291 /**
292  * scx_is_descendant - Test whether sched is a descendant
293  * @sch: sched to test
294  * @ancestor: ancestor sched to test against
295  *
296  * Test whether @sch is a descendant of @ancestor.
297  */
scx_is_descendant(struct scx_sched * sch,struct scx_sched * ancestor)298 bool scx_is_descendant(struct scx_sched *sch, struct scx_sched *ancestor)
299 {
300 	if (sch->level < ancestor->level)
301 		return false;
302 	return sch->ancestors[ancestor->level] == ancestor;
303 }
304 
find_global_dsq(struct scx_sched * sch,s32 cpu)305 static struct scx_dispatch_q *find_global_dsq(struct scx_sched *sch, s32 cpu)
306 {
307 	return &sch->pnode[cpu_to_node(cpu)]->global_dsq;
308 }
309 
find_user_dsq(struct scx_sched * sch,u64 dsq_id)310 static struct scx_dispatch_q *find_user_dsq(struct scx_sched *sch, u64 dsq_id)
311 {
312 	return rhashtable_lookup(&sch->dsq_hash, &dsq_id, dsq_hash_params);
313 }
314 
scx_setscheduler_class(struct task_struct * p)315 static const struct sched_class *scx_setscheduler_class(struct task_struct *p)
316 {
317 	if (p->sched_class == &stop_sched_class)
318 		return &stop_sched_class;
319 
320 	return __setscheduler_class(p->policy, p->prio);
321 }
322 
bypass_enq_target_dsq(struct scx_sched * sch,s32 cpu)323 static struct scx_dispatch_q *bypass_enq_target_dsq(struct scx_sched *sch, s32 cpu)
324 {
325 #ifdef CONFIG_EXT_SUB_SCHED
326 	/*
327 	 * If @sch is a sub-sched which is bypassing, its tasks should go into
328 	 * the bypass DSQs of the nearest ancestor which is not bypassing. The
329 	 * not-bypassing ancestor is responsible for scheduling all tasks from
330 	 * bypassing sub-trees. If all ancestors including root are bypassing,
331 	 * all tasks should go to the root's bypass DSQs.
332 	 *
333 	 * Whenever a sched starts bypassing, all runnable tasks in its subtree
334 	 * are re-enqueued after scx_bypassing() is turned on, guaranteeing that
335 	 * all tasks are transferred to the right DSQs.
336 	 */
337 	while (scx_parent(sch) && scx_bypassing(sch, cpu))
338 		sch = scx_parent(sch);
339 #endif	/* CONFIG_EXT_SUB_SCHED */
340 
341 	return scx_bypass_dsq(sch, cpu);
342 }
343 
344 /**
345  * rq_is_open - Is the rq available for immediate execution of an SCX task?
346  * @rq: rq to test
347  * @enq_flags: optional %SCX_ENQ_* of the task being enqueued
348  *
349  * Returns %true if @rq is currently open for executing an SCX task. After a
350  * %false return, @rq is guaranteed to invoke SCX dispatch path at least once
351  * before going to idle and not inserting a task into @rq's local DSQ after a
352  * %false return doesn't cause @rq to stall.
353  */
rq_is_open(struct rq * rq,u64 enq_flags)354 static bool rq_is_open(struct rq *rq, u64 enq_flags)
355 {
356 	lockdep_assert_rq_held(rq);
357 
358 	/*
359 	 * A higher-priority class task is either running or in the process of
360 	 * waking up on @rq.
361 	 */
362 	if (sched_class_above(rq->next_class, &ext_sched_class))
363 		return false;
364 
365 	/*
366 	 * @rq is either in transition to or in idle and there is no
367 	 * higher-priority class task waking up on it.
368 	 */
369 	if (sched_class_above(&ext_sched_class, rq->next_class))
370 		return true;
371 
372 	/*
373 	 * @rq is either picking, in transition to, or running an SCX task.
374 	 */
375 
376 	/*
377 	 * If we're in the dispatch path holding rq lock, $curr may or may not
378 	 * be ready depending on whether the on-going dispatch decides to extend
379 	 * $curr's slice. We say yes here and resolve it at the end of dispatch.
380 	 * See dispatch_one().
381 	 */
382 	if (rq->scx.flags & SCX_RQ_IN_DISPATCH)
383 		return true;
384 
385 	/*
386 	 * %SCX_ENQ_PREEMPT clears $curr's slice if on SCX and kicks dispatch,
387 	 * so allow it to avoid spuriously triggering reenq on a combined
388 	 * PREEMPT|IMMED insertion.
389 	 */
390 	if (enq_flags & SCX_ENQ_PREEMPT) {
391 		struct task_struct *curr = rq->curr;
392 
393 		/*
394 		 * A protected slice refuses the preemption and the cpu stays
395 		 * occupied. See rq_owned_post_enq().
396 		 */
397 		return curr->sched_class != &ext_sched_class ||
398 			likely(!(curr->scx.flags & SCX_TASK_PROTECTED));
399 	}
400 
401 	/*
402 	 * @rq is either in transition to or running an SCX task and can't go
403 	 * idle without another SCX dispatch cycle.
404 	 */
405 	return false;
406 }
407 
408 /*
409  * Track the rq currently locked.
410  *
411  * This allows kfuncs to safely operate on rq from any scx ops callback,
412  * knowing which rq is already locked.
413  */
414 DEFINE_PER_CPU(struct rq *, scx_locked_rq_state);
415 
416 /*
417  * Under core scheduling, a pick that releases the rq lock invalidates the
418  * core-wide selection it is part of. Count the releases so that the core-sched
419  * pick can tell whether one happened across dispatch.
420  */
scx_rq_lock_drop(struct rq * rq)421 static void scx_rq_lock_drop(struct rq *rq)
422 {
423 	lockdep_assert_rq_held(rq);
424 #ifdef CONFIG_SCHED_CORE
425 	if (sched_core_enabled(rq))
426 		rq->scx.lock_drop_seq++;
427 #endif
428 }
429 
switch_rq_lock(struct rq * from,struct rq * to)430 static void switch_rq_lock(struct rq *from, struct rq *to)
431 {
432 	bool tracked = scx_locked_rq() == from;
433 
434 	if (tracked)
435 		update_locked_rq(NULL);
436 	scx_rq_lock_drop(from);
437 	raw_spin_rq_unlock(from);
438 	raw_spin_rq_lock(to);
439 	if (tracked)
440 		update_locked_rq(to);
441 }
442 
443 /*
444  * Flipped on enable per sch->is_cid_type. Declared in internal.h so
445  * subsystem inlines can read it.
446  */
447 DEFINE_STATIC_KEY_FALSE(__scx_is_cid_type);
448 
449 /**
450  * scx_call_op_set_cpumask - invoke ops.set_cpumask / ops_cid.set_cmask for @task
451  * @sch: scx_sched being invoked
452  * @rq: rq to update as the currently-locked rq, or NULL
453  * @task: task whose affinity is changing
454  * @cpumask: new cpumask
455  *
456  * For cid-form schedulers, translate @cpumask to a cmask via the per-cpu
457  * scratch in cid.c and dispatch through the ops_cid union view. Caller
458  * must hold @rq's rq lock so this_cpu_ptr is stable across the call.
459  */
scx_call_op_set_cpumask(struct scx_sched * sch,struct rq * rq,struct task_struct * task,const struct cpumask * cpumask)460 static inline void scx_call_op_set_cpumask(struct scx_sched *sch, struct rq *rq,
461 					   struct task_struct *task,
462 					   const struct cpumask *cpumask)
463 {
464 	if (scx_is_cid_type()) {
465 		struct scx_cmask *kern_va = *this_cpu_ptr(sch->set_cmask_scratch);
466 		struct scx_cmask_ref ref;
467 
468 		/*
469 		 * Build the per-cpu arena cmask from kernel geometry via @ref,
470 		 * never reading its BPF-writable header. set_cmask()'s __arena
471 		 * argument takes the kernel address and the struct_ops
472 		 * trampoline rebases it into BPF's arena pointer form. The rq
473 		 * lock makes this cpu the sole kernel writer.
474 		 */
475 		scx_cmask_ref_init_kern(sch, kern_va, 0, num_possible_cpus(), &ref);
476 		scx_cmask_ref_from_cpumask(&ref, cpumask);
477 		SCX_CALL_CID_OP_TASK(sch, set_cmask, rq, task, kern_va);
478 	} else {
479 		SCX_CALL_OP_TASK(sch, set_cpumask, rq, task, cpumask);
480 	}
481 }
482 
483 enum scx_dsq_iter_flags {
484 	/* iterate in the reverse dispatch order */
485 	SCX_DSQ_ITER_REV		= 1U << 16,
486 
487 	__SCX_DSQ_ITER_HAS_SLICE	= 1U << 30,
488 	__SCX_DSQ_ITER_HAS_VTIME	= 1U << 31,
489 
490 	__SCX_DSQ_ITER_USER_FLAGS	= SCX_DSQ_ITER_REV,
491 	__SCX_DSQ_ITER_ALL_FLAGS	= __SCX_DSQ_ITER_USER_FLAGS |
492 					  __SCX_DSQ_ITER_HAS_SLICE |
493 					  __SCX_DSQ_ITER_HAS_VTIME,
494 };
495 
496 /**
497  * nldsq_next_task - Iterate to the next task in a non-local DSQ
498  * @dsq: non-local dsq being iterated
499  * @cur: current position, %NULL to start iteration
500  * @rev: walk backwards
501  *
502  * Returns %NULL when iteration is finished.
503  */
nldsq_next_task(struct scx_dispatch_q * dsq,struct task_struct * cur,bool rev)504 static struct task_struct *nldsq_next_task(struct scx_dispatch_q *dsq,
505 					   struct task_struct *cur, bool rev)
506 {
507 	struct list_head *list_node;
508 	struct scx_dsq_list_node *dsq_lnode;
509 
510 	lockdep_assert_held(&dsq->lock);
511 
512 	if (cur)
513 		list_node = &cur->scx.dsq_list.node;
514 	else
515 		list_node = &dsq->list;
516 
517 	/* find the next task, need to skip BPF iteration cursors */
518 	do {
519 		if (rev)
520 			list_node = list_node->prev;
521 		else
522 			list_node = list_node->next;
523 
524 		if (list_node == &dsq->list)
525 			return NULL;
526 
527 		dsq_lnode = container_of(list_node, struct scx_dsq_list_node,
528 					 node);
529 	} while (dsq_lnode->flags & SCX_DSQ_LNODE_ITER_CURSOR);
530 
531 	return container_of(dsq_lnode, struct task_struct, scx.dsq_list);
532 }
533 
534 #define nldsq_for_each_task(p, dsq)						\
535 	for ((p) = nldsq_next_task((dsq), NULL, false); (p);			\
536 	     (p) = nldsq_next_task((dsq), (p), false))
537 
538 /**
539  * nldsq_cursor_next_task - Iterate to the next task given a cursor in a non-local DSQ
540  * @cursor: scx_dsq_list_node initialized with INIT_DSQ_LIST_CURSOR()
541  * @dsq: non-local dsq being iterated
542  *
543  * Find the next task in a cursor based iteration. The caller must have
544  * initialized @cursor using INIT_DSQ_LIST_CURSOR() and can release the DSQ lock
545  * between the iteration steps.
546  *
547  * Only tasks which were queued before @cursor was initialized are visible. This
548  * bounds the iteration and guarantees that vtime never jumps in the other
549  * direction while iterating.
550  */
nldsq_cursor_next_task(struct scx_dsq_list_node * cursor,struct scx_dispatch_q * dsq)551 static struct task_struct *nldsq_cursor_next_task(struct scx_dsq_list_node *cursor,
552 						  struct scx_dispatch_q *dsq)
553 {
554 	bool rev = cursor->flags & SCX_DSQ_ITER_REV;
555 	struct task_struct *p;
556 
557 	lockdep_assert_held(&dsq->lock);
558 	BUG_ON(!(cursor->flags & SCX_DSQ_LNODE_ITER_CURSOR));
559 
560 	if (list_empty(&cursor->node))
561 		p = NULL;
562 	else
563 		p = container_of(cursor, struct task_struct, scx.dsq_list);
564 
565 	/* skip cursors and tasks that were queued after @cursor init */
566 	do {
567 		p = nldsq_next_task(dsq, p, rev);
568 	} while (p && unlikely(u32_before(cursor->priv, p->scx.dsq_seq)));
569 
570 	if (p) {
571 		if (rev)
572 			list_move_tail(&cursor->node, &p->scx.dsq_list.node);
573 		else
574 			list_move(&cursor->node, &p->scx.dsq_list.node);
575 	} else {
576 		list_del_init(&cursor->node);
577 	}
578 
579 	return p;
580 }
581 
582 /**
583  * nldsq_cursor_lost_task - Test whether someone else took the task since iteration
584  * @cursor: scx_dsq_list_node initialized with INIT_DSQ_LIST_CURSOR()
585  * @rq: rq @p was on
586  * @dsq: dsq @p was on
587  * @p: target task
588  *
589  * @p is a task returned by nldsq_cursor_next_task(). The locks may have been
590  * dropped and re-acquired inbetween. Verify that no one else took or is in the
591  * process of taking @p from @dsq.
592  *
593  * On %false return, the caller can assume full ownership of @p.
594  */
nldsq_cursor_lost_task(struct scx_dsq_list_node * cursor,struct rq * rq,struct scx_dispatch_q * dsq,struct task_struct * p)595 static bool nldsq_cursor_lost_task(struct scx_dsq_list_node *cursor,
596 				   struct rq *rq, struct scx_dispatch_q *dsq,
597 				   struct task_struct *p)
598 {
599 	lockdep_assert_rq_held(rq);
600 	lockdep_assert_held(&dsq->lock);
601 
602 	/*
603 	 * @p could have already left $src_dsq, got re-enqueud, or be in the
604 	 * process of being consumed by someone else.
605 	 */
606 	if (unlikely(p->scx.dsq != dsq ||
607 		     u32_before(cursor->priv, p->scx.dsq_seq) ||
608 		     p->scx.holding_cpu >= 0))
609 		return true;
610 
611 	/* if @p has stayed on @dsq, its rq couldn't have changed */
612 	if (WARN_ON_ONCE(rq != task_rq(p)))
613 		return true;
614 
615 	return false;
616 }
617 
618 /*
619  * BPF DSQ iterator. Tasks in a non-local DSQ can be iterated in [reverse]
620  * dispatch order. BPF-visible iterator is opaque and larger to allow future
621  * changes without breaking backward compatibility. Can be used with
622  * bpf_for_each(). See bpf_iter_scx_dsq_*().
623  */
624 struct bpf_iter_scx_dsq_kern {
625 	struct scx_dsq_list_node	cursor;
626 	struct scx_dispatch_q		*dsq;
627 	u64				slice;
628 	u64				vtime;
629 } __attribute__((aligned(8)));
630 
631 struct bpf_iter_scx_dsq {
632 	u64				__opaque[6];
633 } __attribute__((aligned(8)));
634 
635 
scx_get_task_state(const struct task_struct * p)636 u32 scx_get_task_state(const struct task_struct *p)
637 {
638 	return p->scx.flags & SCX_TASK_STATE_MASK;
639 }
640 
scx_set_task_state(struct task_struct * p,u32 state)641 void scx_set_task_state(struct task_struct *p, u32 state)
642 {
643 	u32 prev_state = scx_get_task_state(p);
644 	bool warn = false;
645 
646 	switch (state) {
647 	case SCX_TASK_NONE:
648 		warn = prev_state == SCX_TASK_DEAD;
649 		break;
650 	case SCX_TASK_INIT_BEGIN:
651 		warn = prev_state != SCX_TASK_NONE;
652 		break;
653 	case SCX_TASK_INIT:
654 		warn = prev_state != SCX_TASK_INIT_BEGIN;
655 		p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
656 		break;
657 	case SCX_TASK_READY:
658 		warn = !(prev_state == SCX_TASK_INIT ||
659 			 prev_state == SCX_TASK_ENABLED);
660 		break;
661 	case SCX_TASK_ENABLED:
662 		warn = prev_state != SCX_TASK_READY;
663 		break;
664 	case SCX_TASK_DEAD:
665 		warn = !(prev_state == SCX_TASK_NONE ||
666 			 prev_state == SCX_TASK_INIT_BEGIN);
667 		break;
668 	default:
669 		WARN_ONCE(1, "sched_ext: Invalid task state %d -> %d for %s[%d]",
670 			  prev_state, state, p->comm, p->pid);
671 		return;
672 	}
673 
674 	WARN_ONCE(warn, "sched_ext: Invalid task state transition 0x%x -> 0x%x for %s[%d]",
675 		  prev_state, state, p->comm, p->pid);
676 
677 	p->scx.flags &= ~SCX_TASK_STATE_MASK;
678 	p->scx.flags |= state;
679 }
680 
681 /**
682  * scx_task_iter_start - Lock scx_tasks_lock and start a task iteration
683  * @iter: iterator to init
684  * @cgrp: Optional root of cgroup subhierarchy to iterate
685  *
686  * Initialize @iter. Once initialized, @iter must eventually be stopped with
687  * scx_task_iter_stop().
688  *
689  * If @cgrp is %NULL, scx_tasks is used for iteration and this function returns
690  * with scx_tasks_lock held and @iter->cursor inserted into scx_tasks.
691  *
692  * If @cgrp is not %NULL, @cgrp and its descendants' tasks are walked using
693  * @iter->css_iter. The caller must be holding cgroup_lock() to prevent cgroup
694  * task migrations.
695  *
696  * The two modes of iterations are largely independent and it's likely that
697  * scx_tasks can be removed in favor of always using cgroup iteration if
698  * CONFIG_SCHED_CLASS_EXT depends on CONFIG_CGROUPS.
699  *
700  * scx_tasks_lock and the rq lock may be released using scx_task_iter_unlock()
701  * between this and the first next() call or between any two next() calls. If
702  * the locks are released between two next() calls, the caller is responsible
703  * for ensuring that the task being iterated remains accessible either through
704  * RCU read lock or obtaining a reference count.
705  *
706  * All tasks which existed when the iteration started are guaranteed to be
707  * visited as long as they are not dead.
708  */
scx_task_iter_start(struct scx_task_iter * iter,struct cgroup * cgrp)709 void scx_task_iter_start(struct scx_task_iter *iter, struct cgroup *cgrp)
710 {
711 	memset(iter, 0, sizeof(*iter));
712 
713 #ifdef CONFIG_EXT_SUB_SCHED
714 	if (cgrp) {
715 		lockdep_assert_held(&cgroup_mutex);
716 		iter->cgrp = cgrp;
717 		iter->css_pos = css_next_descendant_pre(NULL, &iter->cgrp->self);
718 		css_task_iter_start(iter->css_pos, CSS_TASK_ITER_WITH_DEAD,
719 				    &iter->css_iter);
720 		return;
721 	}
722 #endif
723 	raw_spin_lock_irq(&scx_tasks_lock);
724 
725 	iter->cursor = (struct sched_ext_entity){ .flags = SCX_TASK_CURSOR };
726 	list_add(&iter->cursor.tasks_node, &scx_tasks);
727 	iter->list_locked = true;
728 }
729 
__scx_task_iter_rq_unlock(struct scx_task_iter * iter)730 static void __scx_task_iter_rq_unlock(struct scx_task_iter *iter)
731 {
732 	if (iter->locked_task) {
733 		__balance_callbacks(iter->rq, &iter->rf);
734 		task_rq_unlock(iter->rq, iter->locked_task, &iter->rf);
735 		iter->locked_task = NULL;
736 	}
737 }
738 
739 /**
740  * scx_task_iter_unlock - Unlock rq and scx_tasks_lock held by a task iterator
741  * @iter: iterator to unlock
742  *
743  * If @iter is in the middle of a locked iteration, it may be locking the rq of
744  * the task currently being visited in addition to scx_tasks_lock. Unlock both.
745  * This function can be safely called anytime during an iteration. The next
746  * iterator operation will automatically restore the necessary locking.
747  */
scx_task_iter_unlock(struct scx_task_iter * iter)748 void scx_task_iter_unlock(struct scx_task_iter *iter)
749 {
750 	__scx_task_iter_rq_unlock(iter);
751 	if (iter->list_locked) {
752 		iter->list_locked = false;
753 		raw_spin_unlock_irq(&scx_tasks_lock);
754 	}
755 }
756 
__scx_task_iter_maybe_relock(struct scx_task_iter * iter)757 static void __scx_task_iter_maybe_relock(struct scx_task_iter *iter)
758 {
759 	if (!iter->list_locked) {
760 		raw_spin_lock_irq(&scx_tasks_lock);
761 		iter->list_locked = true;
762 	}
763 }
764 
765 /**
766  * scx_task_iter_relock - Re-acquire scx_tasks_lock and, optionally, @p's rq
767  * @iter: iterator to relock
768  * @p: task whose rq to lock, or %NULL for scx_tasks_lock only
769  *
770  * Counterpart to scx_task_iter_unlock(). Locking @p's rq is optional. Once
771  * re-acquired, both locks are managed by the iterator from here on.
772  */
scx_task_iter_relock(struct scx_task_iter * iter,struct task_struct * p)773 static void scx_task_iter_relock(struct scx_task_iter *iter,
774 				 struct task_struct *p)
775 {
776 	__scx_task_iter_maybe_relock(iter);
777 	if (p) {
778 		iter->rq = task_rq_lock(p, &iter->rf);
779 		iter->locked_task = p;
780 	}
781 }
782 
783 /**
784  * scx_task_iter_stop - Stop a task iteration and unlock scx_tasks_lock
785  * @iter: iterator to exit
786  *
787  * Exit a previously initialized @iter. Must be called with scx_tasks_lock held
788  * which is released on return. If the iterator holds a task's rq lock, that rq
789  * lock is also released. See scx_task_iter_start() for details.
790  */
scx_task_iter_stop(struct scx_task_iter * iter)791 void scx_task_iter_stop(struct scx_task_iter *iter)
792 {
793 #ifdef CONFIG_EXT_SUB_SCHED
794 	if (iter->cgrp) {
795 		if (iter->css_pos)
796 			css_task_iter_end(&iter->css_iter);
797 		__scx_task_iter_rq_unlock(iter);
798 		return;
799 	}
800 #endif
801 	__scx_task_iter_maybe_relock(iter);
802 	list_del_init(&iter->cursor.tasks_node);
803 	scx_task_iter_unlock(iter);
804 }
805 
806 /**
807  * scx_task_iter_next - Next task
808  * @iter: iterator to walk
809  *
810  * Visit the next task. See scx_task_iter_start() for details. Locks are dropped
811  * and re-acquired every %SCX_TASK_ITER_BATCH iterations to avoid causing stalls
812  * by holding scx_tasks_lock for too long.
813  */
scx_task_iter_next(struct scx_task_iter * iter)814 static struct task_struct *scx_task_iter_next(struct scx_task_iter *iter)
815 {
816 	struct list_head *cursor = &iter->cursor.tasks_node;
817 	struct sched_ext_entity *pos;
818 
819 	if (!(++iter->cnt % SCX_TASK_ITER_BATCH)) {
820 		scx_task_iter_unlock(iter);
821 		cond_resched();
822 	}
823 
824 #ifdef CONFIG_EXT_SUB_SCHED
825 	if (iter->cgrp) {
826 		while (iter->css_pos) {
827 			struct task_struct *p;
828 
829 			p = css_task_iter_next(&iter->css_iter);
830 			if (p)
831 				return p;
832 
833 			css_task_iter_end(&iter->css_iter);
834 			iter->css_pos = css_next_descendant_pre(iter->css_pos,
835 								&iter->cgrp->self);
836 			if (iter->css_pos)
837 				css_task_iter_start(iter->css_pos, CSS_TASK_ITER_WITH_DEAD,
838 						    &iter->css_iter);
839 		}
840 		return NULL;
841 	}
842 #endif
843 	__scx_task_iter_maybe_relock(iter);
844 
845 	list_for_each_entry(pos, cursor, tasks_node) {
846 		if (&pos->tasks_node == &scx_tasks)
847 			return NULL;
848 		if (!(pos->flags & SCX_TASK_CURSOR)) {
849 			list_move(cursor, &pos->tasks_node);
850 			return container_of(pos, struct task_struct, scx);
851 		}
852 	}
853 
854 	/* can't happen, should always terminate at scx_tasks above */
855 	BUG();
856 }
857 
858 /**
859  * scx_task_iter_next_locked - Next non-idle task with its rq locked
860  * @iter: iterator to walk
861  *
862  * Visit the non-idle task with its rq lock held. Allows callers to specify
863  * whether they would like to filter out dead tasks. See scx_task_iter_start()
864  * for details.
865  */
scx_task_iter_next_locked(struct scx_task_iter * iter)866 struct task_struct *scx_task_iter_next_locked(struct scx_task_iter *iter)
867 {
868 	struct task_struct *p;
869 
870 	__scx_task_iter_rq_unlock(iter);
871 
872 	while ((p = scx_task_iter_next(iter))) {
873 		/*
874 		 * scx_task_iter is used to prepare and move tasks into SCX
875 		 * while loading the BPF scheduler and vice-versa while
876 		 * unloading. The init_tasks ("swappers") should be excluded
877 		 * from the iteration because:
878 		 *
879 		 * - It's unsafe to use __setschduler_prio() on an init_task to
880 		 *   determine the sched_class to use as it won't preserve its
881 		 *   idle_sched_class.
882 		 *
883 		 * - ops.init/exit_task() can easily be confused if called with
884 		 *   init_tasks as they, e.g., share PID 0.
885 		 *
886 		 * As init_tasks are never scheduled through SCX, they can be
887 		 * skipped safely. Note that is_idle_task() which tests %PF_IDLE
888 		 * doesn't work here:
889 		 *
890 		 * - %PF_IDLE may not be set for an init_task whose CPU hasn't
891 		 *   yet been onlined.
892 		 *
893 		 * - %PF_IDLE can be set on tasks that are not init_tasks. See
894 		 *   play_idle_precise() used by CONFIG_IDLE_INJECT.
895 		 *
896 		 * Test for idle_sched_class as only init_tasks are on it.
897 		 */
898 		if (p->sched_class == &idle_sched_class)
899 			continue;
900 
901 		iter->rq = task_rq_lock(p, &iter->rf);
902 		iter->locked_task = p;
903 
904 		/*
905 		 * cgroup_task_dead() removes the dead tasks from cset->tasks
906 		 * after sched_ext_dead() and cgroup iteration may see tasks
907 		 * which already finished sched_ext_dead(). %SCX_TASK_DEAD is
908 		 * set by sched_ext_dead() under @p's rq lock. Test it to
909 		 * avoid visiting tasks which are already dead from SCX POV.
910 		 */
911 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
912 			__scx_task_iter_rq_unlock(iter);
913 			continue;
914 		}
915 
916 		return p;
917 	}
918 	return NULL;
919 }
920 
921 /**
922  * scx_dump_event - Dump an event 'kind' in 'events' to 's'
923  * @s: output seq_buf
924  * @events: event stats
925  * @kind: a kind of event to dump
926  */
927 #define scx_dump_event(s, events, kind) do {					\
928 	scx_dump_line(&(s), "%40s: %16lld", #kind, (events)->kind);		\
929 } while (0)
930 
931 
932 static void scx_read_events(struct scx_sched *sch,
933 			    struct scx_event_stats *events);
934 
scx_enable_state(void)935 static enum scx_enable_state scx_enable_state(void)
936 {
937 	return atomic_read(&scx_enable_state_var);
938 }
939 
scx_set_enable_state(enum scx_enable_state to)940 static enum scx_enable_state scx_set_enable_state(enum scx_enable_state to)
941 {
942 	return atomic_xchg(&scx_enable_state_var, to);
943 }
944 
scx_tryset_enable_state(enum scx_enable_state to,enum scx_enable_state from)945 static bool scx_tryset_enable_state(enum scx_enable_state to,
946 				    enum scx_enable_state from)
947 {
948 	int from_v = from;
949 
950 	return atomic_try_cmpxchg(&scx_enable_state_var, &from_v, to);
951 }
952 
953 /**
954  * wait_ops_state - Busy-wait the specified ops state to end
955  * @p: target task
956  * @opss: state to wait the end of
957  *
958  * Busy-wait for @p to transition out of @opss. This can only be used when the
959  * state part of @opss is %SCX_QUEUEING or %SCX_DISPATCHING. This function also
960  * has load_acquire semantics to ensure that the caller can see the updates made
961  * in the enqueueing and dispatching paths.
962  */
wait_ops_state(struct task_struct * p,unsigned long opss)963 static void wait_ops_state(struct task_struct *p, unsigned long opss)
964 {
965 	do {
966 		cpu_relax();
967 	} while (atomic_long_read_acquire(&p->scx.ops_state) == opss);
968 }
969 
__cpu_valid(s32 cpu)970 static inline bool __cpu_valid(s32 cpu)
971 {
972 	return likely(cpu >= 0 && cpu < nr_cpu_ids && cpu_possible(cpu));
973 }
974 
975 /**
976  * scx_cpu_valid - Verify a cpu number, to be used on ops input args
977  * @sch: scx_sched to abort on error
978  * @cpu: cpu number which came from a BPF ops
979  * @where: extra information reported on error
980  *
981  * @cpu is a cpu number which came from the BPF scheduler and can be any value.
982  * Verify that it is in range and one of the possible cpus. If invalid, trigger
983  * an ops error.
984  */
scx_cpu_valid(struct scx_sched * sch,s32 cpu,const char * where)985 bool scx_cpu_valid(struct scx_sched *sch, s32 cpu, const char *where)
986 {
987 	if (__cpu_valid(cpu)) {
988 		return true;
989 	} else {
990 		scx_error(sch, "invalid CPU %d%s%s", cpu, where ? " " : "", where ?: "");
991 		return false;
992 	}
993 }
994 
deferred_bal_cb_workfn(struct rq * rq)995 static void deferred_bal_cb_workfn(struct rq *rq)
996 {
997 	run_deferred(rq);
998 }
999 
deferred_irq_workfn(struct irq_work * irq_work)1000 static void deferred_irq_workfn(struct irq_work *irq_work)
1001 {
1002 	struct rq *rq = container_of(irq_work, struct rq, scx.deferred_irq_work);
1003 
1004 	raw_spin_rq_lock(rq);
1005 	run_deferred(rq);
1006 	scx_rq_lock_drop(rq);
1007 	raw_spin_rq_unlock(rq);
1008 }
1009 
1010 /**
1011  * schedule_deferred - Schedule execution of deferred actions on an rq
1012  * @rq: target rq
1013  *
1014  * Schedule execution of deferred actions on @rq. Deferred actions are executed
1015  * with @rq locked but unpinned, and thus can unlock @rq to e.g. migrate tasks
1016  * to other rqs.
1017  */
schedule_deferred(struct rq * rq)1018 static void schedule_deferred(struct rq *rq)
1019 {
1020 	/*
1021 	 * This is the fallback when schedule_deferred_locked() can't use
1022 	 * the cheaper balance callback or wakeup hook paths (the target
1023 	 * CPU is not in dispatch or wakeup). Currently, this is primarily
1024 	 * hit by reenqueue operations targeting a remote CPU.
1025 	 *
1026 	 * Queue on the target CPU. The deferred work can run from any CPU
1027 	 * correctly - the _locked() path already processes remote rqs from
1028 	 * the calling CPU - but targeting the owning CPU allows IPI delivery
1029 	 * without waiting for the calling CPU to re-enable IRQs and is
1030 	 * cheaper as the reenqueue runs locally.
1031 	 */
1032 	irq_work_queue_on(&rq->scx.deferred_irq_work, cpu_of(rq));
1033 }
1034 
1035 /**
1036  * schedule_deferred_locked - Schedule execution of deferred actions on an rq
1037  * @rq: target rq
1038  *
1039  * Schedule execution of deferred actions on @rq. Equivalent to
1040  * schedule_deferred() but requires @rq to be locked and can be more efficient.
1041  */
schedule_deferred_locked(struct rq * rq)1042 static void schedule_deferred_locked(struct rq *rq)
1043 {
1044 	lockdep_assert_rq_held(rq);
1045 
1046 	/*
1047 	 * If in the middle of waking up a task, task_woken_scx() will be called
1048 	 * afterwards which will then run the deferred actions, no need to
1049 	 * schedule anything.
1050 	 */
1051 	if (rq->scx.flags & SCX_RQ_IN_WAKEUP)
1052 		return;
1053 
1054 	/* Don't do anything if there already is a deferred operation. */
1055 	if (rq->scx.flags & SCX_RQ_BAL_CB_PENDING)
1056 		return;
1057 
1058 	/*
1059 	 * If in dispatch, the balance callbacks will be called before rq lock
1060 	 * is released. Schedule one.
1061 	 *
1062 	 *
1063 	 * We can't directly insert the callback into the
1064 	 * rq's list: The call can drop its lock and make the pending balance
1065 	 * callback visible to unrelated code paths that call rq_pin_lock().
1066 	 *
1067 	 * Just let dispatch_one() know that it must do it itself.
1068 	 */
1069 	if (rq->scx.flags & SCX_RQ_IN_DISPATCH) {
1070 		rq->scx.flags |= SCX_RQ_BAL_CB_PENDING;
1071 		return;
1072 	}
1073 
1074 	/*
1075 	 * No scheduler hooks available. Use the generic irq_work path. The
1076 	 * above WAKEUP and DISPATCH paths should cover most of the cases and
1077 	 * the time to IRQ re-enable shouldn't be long.
1078 	 */
1079 	schedule_deferred(rq);
1080 }
1081 
schedule_dsq_reenq(struct scx_sched * sch,struct scx_dispatch_q * dsq,u64 reenq_flags,struct rq * locked_rq)1082 void schedule_dsq_reenq(struct scx_sched *sch, struct scx_dispatch_q *dsq,
1083 			u64 reenq_flags, struct rq *locked_rq)
1084 {
1085 	struct rq *rq;
1086 
1087 	/*
1088 	 * Allowing reenqueues doesn't make sense while bypassing. This also
1089 	 * blocks from new reenqueues to be scheduled on dead scheds.
1090 	 */
1091 	if (unlikely(READ_ONCE(sch->bypass_depth)))
1092 		return;
1093 
1094 	if (dsq->id == SCX_DSQ_LOCAL) {
1095 		rq = container_of(dsq, struct rq, scx.local_dsq);
1096 
1097 		/*
1098 		 * A sub-sched lacking baseline access on the target cid has no
1099 		 * business triggering IPIs. The lockless test is fine: slipping
1100 		 * through right after a revoke is harmless and a wrong denial
1101 		 * can't happen - if the caller has seen its ownership, so does
1102 		 * this test.
1103 		 */
1104 		if (unlikely(scx_missing_caps(sch, cpu_of(rq), SCX_CAP_BASE))) {
1105 			__scx_add_event(sch, SCX_EV_SUB_REENQ_DENIED, 1);
1106 			return;
1107 		}
1108 
1109 		struct scx_sched_pcpu *sch_pcpu = per_cpu_ptr(sch->pcpu, cpu_of(rq));
1110 		struct scx_deferred_reenq_local *drl = &sch_pcpu->deferred_reenq_local;
1111 
1112 		/*
1113 		 * Pairs with smp_mb() in process_deferred_reenq_locals() and
1114 		 * guarantees that there is a reenq_local() afterwards.
1115 		 */
1116 		smp_mb();
1117 
1118 		if (list_empty(&drl->node) ||
1119 		    (READ_ONCE(drl->flags) & reenq_flags) != reenq_flags) {
1120 
1121 			guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
1122 
1123 			if (list_empty(&drl->node))
1124 				list_move_tail(&drl->node, &rq->scx.deferred_reenq_locals);
1125 			WRITE_ONCE(drl->flags, drl->flags | reenq_flags);
1126 		}
1127 	} else if (!(dsq->id & SCX_DSQ_FLAG_BUILTIN)) {
1128 		rq = this_rq();
1129 
1130 		struct scx_dsq_pcpu *dsq_pcpu = per_cpu_ptr(dsq->pcpu, cpu_of(rq));
1131 		struct scx_deferred_reenq_user *dru = &dsq_pcpu->deferred_reenq_user;
1132 
1133 		/*
1134 		 * Pairs with smp_mb() in process_deferred_reenq_users() and
1135 		 * guarantees that there is a reenq_user() afterwards.
1136 		 */
1137 		smp_mb();
1138 
1139 		if (list_empty(&dru->node) ||
1140 		    (READ_ONCE(dru->flags) & reenq_flags) != reenq_flags) {
1141 
1142 			guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
1143 
1144 			if (list_empty(&dru->node))
1145 				list_move_tail(&dru->node, &rq->scx.deferred_reenq_users);
1146 			WRITE_ONCE(dru->flags, dru->flags | reenq_flags);
1147 		}
1148 	} else {
1149 		scx_error(sch, "DSQ 0x%llx not allowed for reenq", dsq->id);
1150 		return;
1151 	}
1152 
1153 	if (rq == locked_rq)
1154 		schedule_deferred_locked(rq);
1155 	else
1156 		schedule_deferred(rq);
1157 }
1158 
1159 /*
1160  * p->scx.slice_oob packs an out-of-band slice request into one atomic64. A zero
1161  * word means no request. Otherwise the fields are:
1162  *
1163  *   63      SCX_SLICE_OOB_PENDING, set on every request
1164  *   62-43   lower bits of issuing scheduler's id
1165  *   42-0    requested slice duration in nsecs
1166  *
1167  * A duration of SCX_SLICE_OOB_DUR_MASK means SCX_SLICE_INF. A finite dur
1168  * saturates at SCX_SLICE_OOB_DUR_MASK - 1. The id is used to detect and ignore
1169  * a request that outlived a task ownership change.
1170  *
1171  * Only the low 20 bits of sch->id are packed, which is enough to make
1172  * collisions practically impossible. A theoretical collision just lets a stale
1173  * request through once.
1174  */
1175 enum scx_slice_oob_consts {
1176 	SCX_SLICE_OOB_DUR_BITS	= 43,
1177 	SCX_SLICE_OOB_ID_BITS	= 64 - SCX_SLICE_OOB_DUR_BITS - 1,
1178 
1179 	SCX_SLICE_OOB_DUR_MASK	= (1LLU << SCX_SLICE_OOB_DUR_BITS) - 1,
1180 	SCX_SLICE_OOB_ID_SHIFT	= SCX_SLICE_OOB_DUR_BITS,
1181 	SCX_SLICE_OOB_ID_MASK	= (1LLU << SCX_SLICE_OOB_ID_BITS) - 1,
1182 	SCX_SLICE_OOB_PENDING	= 1LLU << 63,
1183 };
1184 
1185 /*
1186  * Slice and dsq_vtime write rules
1187  *
1188  * While @p is running, sleeping or queued on an rq-owned DSQ, both fields are
1189  * protected by the rq lock. While running, the rq lock is required because
1190  * update_curr_scx() RMWs the slice and the cap check for slice extension is
1191  * only reliable under the rq lock.
1192  *
1193  * While @p is queued on a user DSQ or on the BPF side, the kernel neither
1194  * consumes nor decides on the fields. Synchronizing the writers is the BPF
1195  * scheduler's responsibility. An rq-locked scx_bpf_task_set_slice() write and a
1196  * concurrent DSQ insertion commit can race each other and whichever lands last
1197  * wins.
1198  *
1199  * A DSQ insert kfunc doesn't update the fields directly. The verdict carries
1200  * the values and apply_slice_vtime() commits them at the insertion.
1201  *
1202  * scx_bpf_task_set_slice() may be called from any context and writes directly
1203  * only if @p's rq lock is already held, otherwise it bounces through
1204  * p->scx.slice_oob, applied under @p's rq lock at the next slice consideration.
1205  *
1206  * While %SCX_TASK_PROTECTED is set, every scheduler-reachable slice update is
1207  * refused. See set_task_slice_keep_oob().
1208  *
1209  * dsq_vtime orders the next PRIQ insertion and has no running-side consumer, so
1210  * scx_bpf_task_set_dsq_vtime() writes it directly. Fork-time init and direct
1211  * BPF stores from non-cid-form schedulers are outside these rules.
1212  */
1213 
1214 /* clear a pending slice request */
clear_task_slice_oob(struct task_struct * p)1215 static void clear_task_slice_oob(struct task_struct *p)
1216 {
1217 	if (unlikely(atomic64_read(&p->scx.slice_oob)))
1218 		atomic64_set(&p->scx.slice_oob, 0);
1219 }
1220 
1221 /**
1222  * dsq_insert_head - FIFO head insertion honoring %SCX_TASK_PROTECTED
1223  * @dsq: DSQ to insert into
1224  * @p: task being inserted
1225  *
1226  * A HEAD insert should land behind any leading protected tasks. Return %true
1227  * indicates whether @p became the first entry.
1228  */
dsq_insert_head(struct scx_dispatch_q * dsq,struct task_struct * p)1229 static bool dsq_insert_head(struct scx_dispatch_q *dsq, struct task_struct *p)
1230 {
1231 	struct list_head *pos = &dsq->list;
1232 	struct scx_dsq_list_node *node;
1233 
1234 	/*
1235 	 * Only rq-owned DSQs can hold protected tasks and the associated rq
1236 	 * lock keeps their flags stable.
1237 	 */
1238 	if (!dsq_is_rq_owned(dsq)) {
1239 		list_add(&p->scx.dsq_list.node, &dsq->list);
1240 		return true;
1241 	}
1242 
1243 	list_for_each_entry(node, &dsq->list, node) {
1244 		struct task_struct *q;
1245 
1246 		if (WARN_ON_ONCE(node->flags & SCX_DSQ_LNODE_ITER_CURSOR))
1247 			continue;
1248 
1249 		q = container_of(node, struct task_struct, scx.dsq_list);
1250 		if (!(q->scx.flags & SCX_TASK_PROTECTED))
1251 			break;
1252 
1253 		pos = &node->node;
1254 	}
1255 
1256 	list_add(&p->scx.dsq_list.node, pos);
1257 
1258 	return pos == &dsq->list;
1259 }
1260 
1261 /**
1262  * set_task_slice_keep_oob - Set @p's slice, leaving any pending oob request
1263  * @p: task of interest
1264  * @slice: slice to set
1265  *
1266  * While %SCX_TASK_PROTECTED is set, BPF schedulers may not modify the slice.
1267  * Refuse and return %false.
1268  */
set_task_slice_keep_oob(struct task_struct * p,u64 slice)1269 static bool set_task_slice_keep_oob(struct task_struct *p, u64 slice)
1270 {
1271 	lockdep_assert_rq_held(task_rq(p));
1272 
1273 	if (unlikely(p->scx.flags & SCX_TASK_PROTECTED))
1274 		return false;
1275 
1276 	p->scx.slice = slice;
1277 	return true;
1278 }
1279 
1280 /* set @p's slice, superseding any pending out-of-band request */
scx_set_task_slice(struct task_struct * p,u64 slice)1281 bool scx_set_task_slice(struct task_struct *p, u64 slice)
1282 {
1283 	if (!set_task_slice_keep_oob(p, slice))
1284 		return false;
1285 	clear_task_slice_oob(p);
1286 	return true;
1287 }
1288 
1289 /**
1290  * scx_task_slice_ended - @p's slice is consumed or given up
1291  * @rq: rq @p is on
1292  * @p: task of interest
1293  *
1294  * End what rides on the slice - the protection, and the rescue if @p is being
1295  * rescued.
1296  *
1297  * A dequeue normally ends the slice too. The exception is a save/restore pair
1298  * on the running task. Attribute changes like renice cycle the task through
1299  * dequeue and enqueue while it keeps executing, so the slice continues. A
1300  * queued task instead loses its DSQ position on any dequeue and the slice ends
1301  * with it.
1302  */
scx_task_slice_ended(struct rq * rq,struct task_struct * p)1303 void scx_task_slice_ended(struct rq *rq, struct task_struct *p)
1304 {
1305 	lockdep_assert_rq_held(rq);
1306 
1307 	p->scx.flags &= ~SCX_TASK_PROTECTED;
1308 	if (unlikely(p == scx_rescuee(rq)))
1309 		scx_rescue_end(rq);
1310 }
1311 
1312 /* request @p's slice to be set to @slice, see the write rules above */
set_task_slice_oob(struct scx_sched * sch,struct task_struct * p,u64 slice)1313 static void set_task_slice_oob(struct scx_sched *sch, struct task_struct *p, u64 slice)
1314 {
1315 	u64 dur;
1316 
1317 	if (slice == SCX_SLICE_INF) {
1318 		dur = SCX_SLICE_OOB_DUR_MASK;
1319 	} else if (unlikely(slice >= SCX_SLICE_OOB_DUR_MASK)) {
1320 		dur = SCX_SLICE_OOB_DUR_MASK - 1;
1321 		scx_add_event(sch, SCX_EV_SLICE_CLAMPED, 1);
1322 	} else {
1323 		dur = slice;
1324 	}
1325 
1326 	atomic64_set(&p->scx.slice_oob, SCX_SLICE_OOB_PENDING |
1327 		     ((sch->id & SCX_SLICE_OOB_ID_MASK) << SCX_SLICE_OOB_ID_SHIFT) | dur);
1328 }
1329 
1330 /*
1331  * Apply a pending out-of-band slice request under @rq's lock. A request whose
1332  * packed id no longer matches @p's current owner is dropped. An extension needs
1333  * baseline cpu access on @p's cid, shortening is always allowed, and a
1334  * protected slice refuses both. %SCX_EV_SLICE_DENIED counts the denials. See
1335  * the write rules above.
1336  */
apply_task_slice_oob(struct rq * rq,struct task_struct * p)1337 static void apply_task_slice_oob(struct rq *rq, struct task_struct *p)
1338 {
1339 	u64 oob, dur, slice;
1340 
1341 	lockdep_assert_rq_held(rq);
1342 
1343 	if (likely(!atomic64_read(&p->scx.slice_oob)))
1344 		return;
1345 
1346 	oob = atomic64_xchg(&p->scx.slice_oob, 0);
1347 	if (unlikely(!oob))
1348 		return;
1349 
1350 	/* the issuing scheduler no longer owns @p, drop the request */
1351 	if (unlikely(((oob >> SCX_SLICE_OOB_ID_SHIFT) & SCX_SLICE_OOB_ID_MASK) !=
1352 		     (scx_task_sched(p)->id & SCX_SLICE_OOB_ID_MASK)))
1353 		return;
1354 
1355 	dur = oob & SCX_SLICE_OOB_DUR_MASK;
1356 	slice = dur == SCX_SLICE_OOB_DUR_MASK ? SCX_SLICE_INF : dur;
1357 
1358 	if (slice > p->scx.slice &&
1359 	    unlikely(scx_missing_caps(scx_task_sched(p), cpu_of(rq), SCX_CAP_BASE))) {
1360 		__scx_add_event(scx_task_sched(p), SCX_EV_SLICE_DENIED, 1);
1361 		return;
1362 	}
1363 
1364 	if (unlikely(!set_task_slice_keep_oob(p, slice)))
1365 		__scx_add_event(scx_task_sched(p), SCX_EV_SLICE_DENIED, 1);
1366 }
1367 
1368 /*
1369  * A dsq insert kfunc doesn't write slice or dsq_vtime. The verdict carries them
1370  * and they are committed here, at the insertion. A zero @slice keeps the
1371  * current value, floored at 1 so the task isn't treated as expired.
1372  */
apply_slice_vtime(struct task_struct * p,u64 slice,u64 vtime,u64 enq_flags)1373 static void apply_slice_vtime(struct task_struct *p, u64 slice, u64 vtime, u64 enq_flags)
1374 {
1375 	if (slice) {
1376 		p->scx.slice = slice;
1377 		/*
1378 		 * An explicit slice supersedes a pending oob request. A carried
1379 		 * default refill is not an explicit request and must keep it.
1380 		 */
1381 		if (!(enq_flags & SCX_ENQ_SLICE_DFL))
1382 			clear_task_slice_oob(p);
1383 	} else if (!p->scx.slice) {
1384 		p->scx.slice = 1;
1385 	}
1386 
1387 	if (enq_flags & SCX_ENQ_DSQ_PRIQ)
1388 		p->scx.dsq_vtime = vtime;
1389 }
1390 
update_curr_scx(struct rq * rq)1391 static void update_curr_scx(struct rq *rq)
1392 {
1393 	struct task_struct *curr = rq->curr;
1394 	s64 delta_exec;
1395 
1396 	/* apply even on 0 delta_exec, callers may still act on the slice */
1397 	apply_task_slice_oob(rq, curr);
1398 
1399 	delta_exec = update_curr_common(rq);
1400 	if (unlikely(delta_exec <= 0))
1401 		return;
1402 
1403 	if (curr->scx.slice != SCX_SLICE_INF)
1404 		curr->scx.slice -= min_t(u64, curr->scx.slice, delta_exec);
1405 
1406 	if (unlikely(curr == scx_rescuee(rq)))
1407 		scx_rescue_charge(rq, delta_exec);
1408 
1409 	dl_server_update(&rq->ext_server, delta_exec);
1410 }
1411 
scx_dsq_priq_less(struct rb_node * node_a,const struct rb_node * node_b)1412 static bool scx_dsq_priq_less(struct rb_node *node_a,
1413 			      const struct rb_node *node_b)
1414 {
1415 	const struct task_struct *a =
1416 		container_of(node_a, struct task_struct, scx.dsq_priq);
1417 	const struct task_struct *b =
1418 		container_of(node_b, struct task_struct, scx.dsq_priq);
1419 
1420 	return time_before64(a->scx.dsq_vtime, b->scx.dsq_vtime);
1421 }
1422 
dsq_inc_nr(struct scx_dispatch_q * dsq,struct task_struct * p,u64 enq_flags)1423 static void dsq_inc_nr(struct scx_dispatch_q *dsq, struct task_struct *p, u64 enq_flags)
1424 {
1425 	/* scx_bpf_dsq_nr_queued() reads ->nr without locking, use WRITE_ONCE() */
1426 	WRITE_ONCE(dsq->nr, dsq->nr + 1);
1427 
1428 	/*
1429 	 * Once @p reaches a local DSQ, it can only leave it by being dispatched
1430 	 * to the CPU or dequeued. In both cases, the only way @p can go back to
1431 	 * the BPF sched is through enqueueing. If being inserted into a local
1432 	 * DSQ with IMMED, persist the state until the next enqueueing event in
1433 	 * scx_do_enqueue_task() so that we can maintain IMMED protection
1434 	 * through e.g. SAVE/RESTORE cycles and slice extensions.
1435 	 */
1436 	if (enq_flags & SCX_ENQ_IMMED) {
1437 		if (unlikely(dsq->id != SCX_DSQ_LOCAL)) {
1438 			WARN_ON_ONCE(!(enq_flags & SCX_ENQ_GDSQ_FALLBACK));
1439 			return;
1440 		}
1441 		p->scx.flags |= SCX_TASK_IMMED;
1442 	}
1443 
1444 	if (p->scx.flags & SCX_TASK_IMMED) {
1445 		struct rq *rq = container_of(dsq, struct rq, scx.local_dsq);
1446 
1447 		if (WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL))
1448 			return;
1449 
1450 		rq->scx.nr_immed++;
1451 
1452 		/*
1453 		 * If @rq already had other tasks or the current task is not
1454 		 * done yet, @p can't go on the CPU immediately. Re-enqueue.
1455 		 */
1456 		if (unlikely(dsq->nr > 1 || !rq_is_open(rq, enq_flags)))
1457 			scx_schedule_reenq_local(rq, 0);
1458 	}
1459 }
1460 
dsq_dec_nr(struct scx_dispatch_q * dsq,struct task_struct * p)1461 static void dsq_dec_nr(struct scx_dispatch_q *dsq, struct task_struct *p)
1462 {
1463 	/* see dsq_inc_nr() */
1464 	WRITE_ONCE(dsq->nr, dsq->nr - 1);
1465 
1466 	if (p->scx.flags & SCX_TASK_IMMED) {
1467 		struct rq *rq = container_of(dsq, struct rq, scx.local_dsq);
1468 
1469 		if (WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL) ||
1470 		    WARN_ON_ONCE(rq->scx.nr_immed <= 0))
1471 			return;
1472 
1473 		rq->scx.nr_immed--;
1474 	}
1475 }
1476 
refill_task_slice_dfl(struct scx_sched * sch,struct task_struct * p)1477 static void refill_task_slice_dfl(struct scx_sched *sch, struct task_struct *p)
1478 {
1479 	/*
1480 	 * A default refill is not an explicit request, so it must not drop a
1481 	 * pending out-of-band one, which is applied when @p next runs.
1482 	 */
1483 	set_task_slice_keep_oob(p, READ_ONCE(sch->slice_dfl));
1484 	__scx_add_event(sch, SCX_EV_REFILL_SLICE_DFL, 1);
1485 }
1486 
1487 /*
1488  * Return true if @p is moving due to an internal SCX migration, false
1489  * otherwise.
1490  */
task_scx_migrating(struct task_struct * p)1491 static inline bool task_scx_migrating(struct task_struct *p)
1492 {
1493 	/*
1494 	 * We only need to check sticky_cpu: it is set to the destination
1495 	 * CPU in move_remote_task_to_local_dsq() before deactivate_task()
1496 	 * and cleared when the task is enqueued on the destination, so it
1497 	 * is only non-negative during an internal SCX migration.
1498 	 */
1499 	return p->scx.sticky_cpu >= 0;
1500 }
1501 
1502 /*
1503  * Call ops.dequeue() if the task is in BPF custody and not migrating.
1504  * Clears %SCX_TASK_IN_CUSTODY when the callback is invoked.
1505  */
call_task_dequeue(struct scx_sched * sch,struct rq * rq,struct task_struct * p,u64 deq_flags)1506 static void call_task_dequeue(struct scx_sched *sch, struct rq *rq,
1507 			      struct task_struct *p, u64 deq_flags)
1508 {
1509 	if (!(p->scx.flags & SCX_TASK_IN_CUSTODY) || task_scx_migrating(p))
1510 		return;
1511 
1512 	if (SCX_HAS_OP(sch, dequeue))
1513 		SCX_CALL_OP_TASK(sch, dequeue, rq, p, deq_flags);
1514 
1515 	p->scx.flags &= ~SCX_TASK_IN_CUSTODY;
1516 }
1517 
rq_owned_post_enq(struct scx_sched * sch,struct rq * rq,struct scx_dispatch_q * dsq,struct task_struct * p,u64 enq_flags)1518 static void rq_owned_post_enq(struct scx_sched *sch, struct rq *rq,
1519 			      struct scx_dispatch_q *dsq, struct task_struct *p,
1520 			      u64 enq_flags)
1521 {
1522 	call_task_dequeue(sch, rq, p, 0);
1523 
1524 	/*
1525 	 * Only local inserts get the wakeup treatment below. Rejects kick the
1526 	 * deferred reenq and rescue parks are paced by the rescue timer.
1527 	 */
1528 	if (unlikely(dsq->id != SCX_DSQ_LOCAL)) {
1529 		if (dsq->id == SCX_DSQ_REJECT)
1530 			schedule_deferred_locked(rq);
1531 		return;
1532 	}
1533 
1534 	/*
1535 	 * Note that @rq's lock may be dropped between this enqueue and @p
1536 	 * actually getting on CPU. This gives higher-class tasks (e.g. RT)
1537 	 * an opportunity to wake up on @rq and prevent @p from running.
1538 	 * Here are some concrete examples:
1539 	 *
1540 	 * Example 1:
1541 	 *
1542 	 * We dispatch two tasks from a single ops.dispatch():
1543 	 * - First, a local task to this CPU's local DSQ;
1544 	 * - Second, a local/remote task to a remote CPU's local DSQ.
1545 	 * We must drop the local rq lock in order to finish the second
1546 	 * dispatch. In that time, an RT task can wake up on the local rq.
1547 	 *
1548 	 * Example 2:
1549 	 *
1550 	 * We dispatch a local/remote task to a remote CPU's local DSQ.
1551 	 * We must drop the remote rq lock before the dispatched task can run,
1552 	 * which gives an RT task an opportunity to wake up on the remote rq.
1553 	 *
1554 	 * Both examples work the same if we replace dispatching with moving
1555 	 * the tasks from a user-created DSQ.
1556 	 *
1557 	 * We must detect these wakeups so that we can re-enqueue IMMED tasks
1558 	 * from @rq's local DSQ. scx_wakeup_preempt() serves exactly this
1559 	 * purpose, but for it to be invoked, we must ensure that we bump
1560 	 * @rq->next_class to &ext_sched_class if it's currently idle.
1561 	 *
1562 	 * wakeup_preempt() does the bumping, and since we only invoke it if
1563 	 * @rq->next_class is below &ext_sched_class, it will also
1564 	 * resched_curr(rq).
1565 	 */
1566 	if (sched_class_above(p->sched_class, rq->next_class))
1567 		wakeup_preempt(rq, p, 0);
1568 
1569 	/*
1570 	 * If @rq is in dispatch, the CPU is already vacant and looking for the
1571 	 * next task to run. No need to preempt or trigger resched after moving
1572 	 * @p into its local DSQ.
1573 	 * Note that the wakeup_preempt() above may have already triggered
1574 	 * a resched if @rq->next_class was idle. It's harmless, since
1575 	 * need_resched is cleared immediately after task pick.
1576 	 */
1577 	if (rq->scx.flags & SCX_RQ_IN_DISPATCH)
1578 		return;
1579 
1580 	if ((enq_flags & SCX_ENQ_PREEMPT) && p != rq->curr &&
1581 	    rq->curr->sched_class == &ext_sched_class) {
1582 		if (likely(scx_set_task_slice(rq->curr, 0)))
1583 			resched_curr(rq);
1584 		else
1585 			__scx_add_event(sch, SCX_EV_SLICE_DENIED, 1);
1586 	}
1587 }
1588 
scx_dispatch_enqueue(struct scx_sched * sch,struct rq * rq,struct scx_dispatch_q * dsq,struct task_struct * p,u64 slice,u64 vtime,u64 enq_flags)1589 static void scx_dispatch_enqueue(struct scx_sched *sch, struct rq *rq,
1590 				 struct scx_dispatch_q *dsq, struct task_struct *p,
1591 				 u64 slice, u64 vtime, u64 enq_flags)
1592 {
1593 	bool is_rq_owned = false;
1594 
1595 	if (dsq->id == SCX_DSQ_LOCAL) {
1596 		dsq = scx_resolve_local_dsq(sch, rq, p, &enq_flags);
1597 		is_rq_owned = true;
1598 	}
1599 
1600 	WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node));
1601 	WARN_ON_ONCE((p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) ||
1602 		     !RB_EMPTY_NODE(&p->scx.dsq_priq));
1603 
1604 	if (!is_rq_owned) {
1605 		raw_spin_lock_nested(&dsq->lock,
1606 			(enq_flags & SCX_ENQ_NESTED) ? SINGLE_DEPTH_NESTING : 0);
1607 
1608 		if (unlikely(dsq->id == SCX_DSQ_INVALID)) {
1609 			scx_error(sch, "attempting to dispatch to a destroyed dsq");
1610 			/* fall back to the global dsq */
1611 			raw_spin_unlock(&dsq->lock);
1612 			dsq = find_global_dsq(sch, task_cpu(p));
1613 			raw_spin_lock(&dsq->lock);
1614 		}
1615 	}
1616 
1617 	if (unlikely((dsq->id & SCX_DSQ_FLAG_BUILTIN) &&
1618 		     (enq_flags & SCX_ENQ_DSQ_PRIQ))) {
1619 		/*
1620 		 * SCX_DSQ_LOCAL and SCX_DSQ_GLOBAL DSQs always consume from
1621 		 * their FIFO queues. To avoid confusion and accidentally
1622 		 * starving vtime-dispatched tasks by FIFO-dispatched tasks, we
1623 		 * disallow any internal DSQ from doing vtime ordering of
1624 		 * tasks.
1625 		 */
1626 		scx_error(sch, "cannot use vtime ordering for built-in DSQs");
1627 		enq_flags &= ~SCX_ENQ_DSQ_PRIQ;
1628 	}
1629 
1630 	/*
1631 	 * @dsq is locked and @enq_flags is sanitized. Commit the carried slice
1632 	 * and vtime before the PRIQ insertion below reads the new dsq_vtime.
1633 	 */
1634 	if (enq_flags & SCX_ENQ_APPLY_SLICE)
1635 		apply_slice_vtime(p, slice, vtime, enq_flags);
1636 
1637 	if (enq_flags & SCX_ENQ_DSQ_PRIQ) {
1638 		struct rb_node *rbp;
1639 
1640 		/*
1641 		 * A PRIQ DSQ shouldn't be using FIFO enqueueing. As tasks are
1642 		 * linked to both the rbtree and list on PRIQs, this can only be
1643 		 * tested easily when adding the first task.
1644 		 */
1645 		if (unlikely(RB_EMPTY_ROOT(&dsq->priq) &&
1646 			     nldsq_next_task(dsq, NULL, false)))
1647 			scx_error(sch, "DSQ ID 0x%016llx already had FIFO-enqueued tasks",
1648 				  dsq->id);
1649 
1650 		p->scx.dsq_flags |= SCX_TASK_DSQ_ON_PRIQ;
1651 		rb_add(&p->scx.dsq_priq, &dsq->priq, scx_dsq_priq_less);
1652 
1653 		/*
1654 		 * Find the previous task and insert after it on the list so
1655 		 * that @dsq->list is vtime ordered.
1656 		 */
1657 		rbp = rb_prev(&p->scx.dsq_priq);
1658 		if (rbp) {
1659 			struct task_struct *prev =
1660 				container_of(rbp, struct task_struct,
1661 					     scx.dsq_priq);
1662 			list_add(&p->scx.dsq_list.node, &prev->scx.dsq_list.node);
1663 			/* first task unchanged - no update needed */
1664 		} else {
1665 			list_add(&p->scx.dsq_list.node, &dsq->list);
1666 			/* not builtin and new task is at head - use fastpath */
1667 			rcu_assign_pointer(dsq->first_task, p);
1668 		}
1669 	} else {
1670 		/* a FIFO DSQ shouldn't be using PRIQ enqueuing */
1671 		if (unlikely(!RB_EMPTY_ROOT(&dsq->priq)))
1672 			scx_error(sch, "DSQ ID 0x%016llx already had PRIQ-enqueued tasks",
1673 				  dsq->id);
1674 
1675 		if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT)) {
1676 			/* new task inserted at head - use fastpath */
1677 			if (dsq_insert_head(dsq, p) && !(dsq->id & SCX_DSQ_FLAG_BUILTIN))
1678 				rcu_assign_pointer(dsq->first_task, p);
1679 		} else {
1680 			/*
1681 			 * dsq->list can contain parked BPF iterator cursors, so
1682 			 * list_empty() here isn't a reliable proxy for "no real
1683 			 * task in the DSQ". Test dsq->first_task directly.
1684 			 */
1685 			list_add_tail(&p->scx.dsq_list.node, &dsq->list);
1686 			if (!dsq->first_task && !(dsq->id & SCX_DSQ_FLAG_BUILTIN))
1687 				rcu_assign_pointer(dsq->first_task, p);
1688 		}
1689 	}
1690 
1691 	/* seq records the order tasks are queued, used by BPF DSQ iterator */
1692 	WRITE_ONCE(dsq->seq, dsq->seq + 1);
1693 	p->scx.dsq_seq = dsq->seq;
1694 
1695 	dsq_inc_nr(dsq, p, enq_flags);
1696 	p->scx.dsq = dsq;
1697 
1698 	/*
1699 	 * Update custody and call ops.dequeue() before clearing ops_state:
1700 	 * once ops_state is cleared, waiters in ops_dequeue() can proceed
1701 	 * and dequeue_task_scx() will RMW p->scx.flags. If we clear
1702 	 * ops_state first, both sides would modify p->scx.flags
1703 	 * concurrently in a non-atomic way.
1704 	 */
1705 	if (is_rq_owned) {
1706 		rq_owned_post_enq(sch, rq, dsq, p, enq_flags);
1707 	} else {
1708 		/*
1709 		 * Global and bypass DSQs are terminal - the task leaves the
1710 		 * scheduler's custody, so ops.dequeue() fires here. It can run
1711 		 * without @p's rq lock (finish_dispatch() passes the dispatch
1712 		 * rq); that's safe because dequeue_task_scx() waits on
1713 		 * SCX_OPSS_DISPATCHING (see the ops_state note above) and so
1714 		 * can't race it. A non-terminal DSQ keeps the task in custody.
1715 		 */
1716 		if (dsq->id == SCX_DSQ_GLOBAL || dsq->id == SCX_DSQ_BYPASS)
1717 			call_task_dequeue(sch, rq, p, 0);
1718 		else
1719 			p->scx.flags |= SCX_TASK_IN_CUSTODY;
1720 
1721 		raw_spin_unlock(&dsq->lock);
1722 	}
1723 
1724 	/*
1725 	 * We're transitioning out of QUEUEING or DISPATCHING. store_release to
1726 	 * match waiters' load_acquire.
1727 	 */
1728 	if (enq_flags & SCX_ENQ_CLEAR_OPSS)
1729 		atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1730 }
1731 
scx_task_unlink_from_dsq(struct task_struct * p,struct scx_dispatch_q * dsq)1732 void scx_task_unlink_from_dsq(struct task_struct *p, struct scx_dispatch_q *dsq)
1733 {
1734 	WARN_ON_ONCE(list_empty(&p->scx.dsq_list.node));
1735 
1736 	if (p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) {
1737 		rb_erase(&p->scx.dsq_priq, &dsq->priq);
1738 		RB_CLEAR_NODE(&p->scx.dsq_priq);
1739 		p->scx.dsq_flags &= ~SCX_TASK_DSQ_ON_PRIQ;
1740 	}
1741 
1742 	list_del_init(&p->scx.dsq_list.node);
1743 	dsq_dec_nr(dsq, p);
1744 
1745 	if (!(dsq->id & SCX_DSQ_FLAG_BUILTIN) && rcu_access_pointer(dsq->first_task) == p) {
1746 		struct task_struct *first_task;
1747 
1748 		first_task = nldsq_next_task(dsq, NULL, false);
1749 		rcu_assign_pointer(dsq->first_task, first_task);
1750 	}
1751 }
1752 
scx_dispatch_dequeue(struct rq * rq,struct task_struct * p)1753 void scx_dispatch_dequeue(struct rq *rq, struct task_struct *p)
1754 {
1755 	struct scx_dispatch_q *dsq = p->scx.dsq;
1756 	bool is_rq_owned = dsq && dsq_is_rq_owned(dsq);
1757 
1758 	lockdep_assert_rq_held(rq);
1759 
1760 	if (!dsq) {
1761 		/*
1762 		 * If !dsq && on-list, @p is on @rq's ddsp_deferred_locals.
1763 		 * Unlinking is all that's needed to cancel.
1764 		 */
1765 		if (unlikely(!list_empty(&p->scx.dsq_list.node)))
1766 			list_del_init(&p->scx.dsq_list.node);
1767 
1768 		/*
1769 		 * When dispatching directly from the BPF scheduler to a local
1770 		 * DSQ, the task isn't associated with any DSQ but
1771 		 * @p->scx.holding_cpu may be set under the protection of
1772 		 * %SCX_OPSS_DISPATCHING.
1773 		 */
1774 		if (p->scx.holding_cpu >= 0)
1775 			p->scx.holding_cpu = -1;
1776 
1777 		return;
1778 	}
1779 
1780 	if (!is_rq_owned)
1781 		raw_spin_lock(&dsq->lock);
1782 
1783 	/*
1784 	 * Now that we hold @dsq->lock, @p->holding_cpu and @p->scx.dsq_* can't
1785 	 * change underneath us.
1786 	*/
1787 	if (p->scx.holding_cpu < 0) {
1788 		/* @p must still be on @dsq, dequeue */
1789 		scx_task_unlink_from_dsq(p, dsq);
1790 	} else {
1791 		/*
1792 		 * We're racing against dispatch_to_local_dsq() which already
1793 		 * removed @p from @dsq and set @p->scx.holding_cpu. Clear the
1794 		 * holding_cpu which tells dispatch_to_local_dsq() that it lost
1795 		 * the race.
1796 		 */
1797 		WARN_ON_ONCE(!list_empty(&p->scx.dsq_list.node));
1798 		p->scx.holding_cpu = -1;
1799 	}
1800 	p->scx.dsq = NULL;
1801 
1802 	if (!is_rq_owned)
1803 		raw_spin_unlock(&dsq->lock);
1804 }
1805 
1806 /*
1807  * Abbreviated version of scx_dispatch_dequeue() that can be used when both
1808  * @p's rq and dsq are locked.
1809  */
dispatch_dequeue_locked(struct task_struct * p,struct scx_dispatch_q * dsq)1810 static void dispatch_dequeue_locked(struct task_struct *p,
1811 				    struct scx_dispatch_q *dsq)
1812 {
1813 	lockdep_assert_rq_held(task_rq(p));
1814 	lockdep_assert_held(&dsq->lock);
1815 
1816 	scx_task_unlink_from_dsq(p, dsq);
1817 	p->scx.dsq = NULL;
1818 }
1819 
find_dsq_for_dispatch(struct scx_sched * sch,struct rq * rq,u64 dsq_id,s32 tcpu)1820 static struct scx_dispatch_q *find_dsq_for_dispatch(struct scx_sched *sch,
1821 						    struct rq *rq, u64 dsq_id,
1822 						    s32 tcpu)
1823 {
1824 	struct scx_dispatch_q *dsq;
1825 
1826 	if (dsq_id == SCX_DSQ_LOCAL)
1827 		return &rq->scx.local_dsq;
1828 
1829 	if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
1830 		s32 cpu = scx_cpu_ret(sch, dsq_id & SCX_DSQ_LOCAL_CPU_MASK);
1831 
1832 		if (!scx_cpu_valid(sch, cpu, "in SCX_DSQ_LOCAL_ON dispatch verdict"))
1833 			return find_global_dsq(sch, tcpu);
1834 
1835 		return &cpu_rq(cpu)->scx.local_dsq;
1836 	}
1837 
1838 	if (dsq_id == SCX_DSQ_GLOBAL)
1839 		dsq = find_global_dsq(sch, tcpu);
1840 	else
1841 		dsq = find_user_dsq(sch, dsq_id);
1842 
1843 	/*
1844 	 * Built-in DSQs are never inserted into dsq_hash, so REJECT and RESCUE
1845 	 * hit the error below. They cannot be reached with an ID.
1846 	 */
1847 	if (unlikely(!dsq)) {
1848 		scx_error(sch, "non-existent DSQ 0x%llx", dsq_id);
1849 		return find_global_dsq(sch, tcpu);
1850 	}
1851 
1852 	return dsq;
1853 }
1854 
mark_direct_dispatch(struct scx_sched * sch,struct task_struct * ddsp_task,struct task_struct * p,u64 dsq_id,u64 slice,u64 vtime,u64 enq_flags)1855 static void mark_direct_dispatch(struct scx_sched *sch,
1856 				 struct task_struct *ddsp_task,
1857 				 struct task_struct *p, u64 dsq_id,
1858 				 u64 slice, u64 vtime, u64 enq_flags)
1859 {
1860 	/*
1861 	 * Mark that dispatch already happened from ops.select_cpu() or
1862 	 * ops.enqueue() by spoiling direct_dispatch_task with a non-NULL value
1863 	 * which can never match a valid task pointer.
1864 	 */
1865 	__this_cpu_write(direct_dispatch_task, ERR_PTR(-ESRCH));
1866 
1867 	/* @p must match the task on the enqueue path */
1868 	if (unlikely(p != ddsp_task)) {
1869 		if (IS_ERR(ddsp_task))
1870 			scx_error(sch, "%s[%d] already direct-dispatched",
1871 				  p->comm, p->pid);
1872 		else
1873 			scx_error(sch, "scheduling for %s[%d] but trying to direct-dispatch %s[%d]",
1874 				  ddsp_task->comm, ddsp_task->pid,
1875 				  p->comm, p->pid);
1876 		return;
1877 	}
1878 
1879 	WARN_ON_ONCE(p->scx.ddsp_dsq_id != SCX_DSQ_INVALID);
1880 	WARN_ON_ONCE(p->scx.ddsp_enq_flags);
1881 
1882 	p->scx.ddsp_slice = slice;
1883 	p->scx.ddsp_vtime = vtime;
1884 	p->scx.ddsp_dsq_id = dsq_id;
1885 	p->scx.ddsp_enq_flags = enq_flags;
1886 }
1887 
1888 /*
1889  * Clear @p direct dispatch state when leaving the scheduler.
1890  *
1891  * Direct dispatch state must be cleared in the following cases:
1892  *  - direct_dispatch(): cleared on the synchronous enqueue path, deferred
1893  *    dispatch keeps the state until consumed
1894  *  - process_ddsp_deferred_locals(): cleared after consuming deferred state,
1895  *  - scx_do_enqueue_task(): cleared on enqueue fallbacks where the dispatch
1896  *    verdict is ignored (local/global/bypass)
1897  *  - dequeue_task_scx(): cleared after scx_dispatch_dequeue(), covering
1898  *    deferred cancellation and holding_cpu races
1899  *  - scx_disable_task(): cleared for queued wakeup tasks, which are excluded by
1900  *    the scx_bypass() loop, so that stale state is not reused by a subsequent
1901  *    scheduler instance
1902  */
clear_direct_dispatch(struct task_struct * p)1903 static inline void clear_direct_dispatch(struct task_struct *p)
1904 {
1905 	p->scx.ddsp_dsq_id = SCX_DSQ_INVALID;
1906 	p->scx.ddsp_enq_flags = 0;
1907 }
1908 
direct_dispatch(struct scx_sched * sch,struct task_struct * p,u64 enq_flags)1909 static void direct_dispatch(struct scx_sched *sch, struct task_struct *p,
1910 			    u64 enq_flags)
1911 {
1912 	struct rq *rq = task_rq(p);
1913 	struct scx_dispatch_q *dsq =
1914 		find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, task_cpu(p));
1915 	u64 ddsp_enq_flags, slice, vtime;
1916 
1917 	p->scx.ddsp_enq_flags |= enq_flags;
1918 
1919 	/*
1920 	 * We are in the enqueue path with @rq locked and pinned, and thus can't
1921 	 * double lock a remote rq and enqueue to its local DSQ. For
1922 	 * DSQ_LOCAL_ON verdicts targeting the local DSQ of a remote CPU, defer
1923 	 * the enqueue so that it's executed when @rq can be unlocked.
1924 	 */
1925 	if (dsq->id == SCX_DSQ_LOCAL && dsq != &rq->scx.local_dsq) {
1926 		unsigned long opss;
1927 
1928 		opss = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_STATE_MASK;
1929 
1930 		switch (opss & SCX_OPSS_STATE_MASK) {
1931 		case SCX_OPSS_NONE:
1932 			break;
1933 		case SCX_OPSS_QUEUEING:
1934 			/*
1935 			 * As @p was never passed to the BPF side, _release is
1936 			 * not strictly necessary. Still do it for consistency.
1937 			 */
1938 			atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1939 			break;
1940 		default:
1941 			WARN_ONCE(true, "sched_ext: %s[%d] has invalid ops state 0x%lx in direct_dispatch()",
1942 				  p->comm, p->pid, opss);
1943 			atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1944 			break;
1945 		}
1946 
1947 		WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node));
1948 		list_add_tail(&p->scx.dsq_list.node,
1949 			      &rq->scx.ddsp_deferred_locals);
1950 		schedule_deferred_locked(rq);
1951 		return;
1952 	}
1953 
1954 	ddsp_enq_flags = p->scx.ddsp_enq_flags;
1955 	slice = p->scx.ddsp_slice;
1956 	vtime = p->scx.ddsp_vtime;
1957 	clear_direct_dispatch(p);
1958 
1959 	scx_dispatch_enqueue(sch, rq, dsq, p, slice, vtime,
1960 			     ddsp_enq_flags | SCX_ENQ_APPLY_SLICE | SCX_ENQ_CLEAR_OPSS);
1961 }
1962 
scx_rq_online(struct rq * rq)1963 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 
scx_do_enqueue_task(struct rq * rq,struct task_struct * p,u64 enq_flags,int sticky_cpu)1975 void scx_do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags,
1976 			 int sticky_cpu)
1977 {
1978 	struct scx_sched *sch = scx_task_sched(p);
1979 	struct task_struct **ddsp_taskp;
1980 	struct scx_dispatch_q *dsq;
1981 	unsigned long qseq;
1982 
1983 	WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_QUEUED));
1984 
1985 	/* internal movements - rq migration / RESTORE */
1986 	if (sticky_cpu == cpu_of(rq))
1987 		goto local_norefill;
1988 
1989 	/*
1990 	 * Clear persistent TASK_IMMED for fresh enqueues, see dsq_inc_nr().
1991 	 * Note that exiting and migration-disabled tasks that skip
1992 	 * ops.enqueue() below will lose IMMED protection unless
1993 	 * %SCX_OPS_ENQ_EXITING / %SCX_OPS_ENQ_MIGRATION_DISABLED are set.
1994 	 */
1995 	p->scx.flags &= ~SCX_TASK_IMMED;
1996 
1997 	/*
1998 	 * A task reenqueued too many times without running means the scheduler
1999 	 * keeps re-deciding a placement it can't honor, e.g. re-inserting to a
2000 	 * cid it lacks caps on. Eject the owning scheduler and strand the task
2001 	 * to be picked up during sched exit.
2002 	 */
2003 	if (enq_flags & SCX_ENQ_REENQ) {
2004 		if (++p->scx.reenq_cnt > 1)
2005 			__scx_add_event(sch, SCX_EV_REENQ_REPEAT, 1);
2006 
2007 		if (unlikely(p->scx.reenq_cnt > SCX_REENQ_MAX_REPEAT)) {
2008 			__scx_exit(sch, SCX_EXIT_ERROR_REENQ, 0, cpu_of(rq),
2009 				   "%s[%d] reenqueued %u times without running",
2010 				   p->comm, p->pid, p->scx.reenq_cnt);
2011 			return;
2012 		}
2013 	}
2014 
2015 	/*
2016 	 * If !scx_rq_online(), we already told the BPF scheduler that the CPU
2017 	 * is offline and are just running the hotplug path. Don't bother the
2018 	 * BPF scheduler.
2019 	 */
2020 	if (!scx_rq_online(rq))
2021 		goto local;
2022 
2023 	if (scx_bypassing(sch, cpu_of(rq))) {
2024 		__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
2025 		goto bypass;
2026 	}
2027 
2028 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
2029 		goto direct;
2030 
2031 	/* see %SCX_OPS_ENQ_EXITING */
2032 	if (!(sch->ops.flags & SCX_OPS_ENQ_EXITING) &&
2033 	    unlikely(p->flags & PF_EXITING)) {
2034 		__scx_add_event(sch, SCX_EV_ENQ_SKIP_EXITING, 1);
2035 		enq_flags |= SCX_ENQ_RESCUE;	/* avoid looping on cap rejection */
2036 		goto local;
2037 	}
2038 
2039 	/* see %SCX_OPS_ENQ_MIGRATION_DISABLED */
2040 	if (!(sch->ops.flags & SCX_OPS_ENQ_MIGRATION_DISABLED) &&
2041 	    is_migration_disabled(p)) {
2042 		__scx_add_event(sch, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED, 1);
2043 		goto local;
2044 	}
2045 
2046 	if (unlikely(!SCX_HAS_OP(sch, enqueue)))
2047 		goto global;
2048 
2049 	/* DSQ bypass didn't trigger, enqueue on the BPF scheduler */
2050 	qseq = rq->scx.ops_qseq++ << SCX_OPSS_QSEQ_SHIFT;
2051 
2052 	WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
2053 	atomic_long_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq);
2054 
2055 	ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
2056 	WARN_ON_ONCE(*ddsp_taskp);
2057 	*ddsp_taskp = p;
2058 
2059 	SCX_CALL_OP_TASK(sch, enqueue, rq, p, enq_flags);
2060 
2061 	*ddsp_taskp = NULL;
2062 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
2063 		goto direct;
2064 
2065 	/*
2066 	 * Task is now in BPF scheduler's custody. Set %SCX_TASK_IN_CUSTODY
2067 	 * so ops.dequeue() is called when it leaves custody.
2068 	 */
2069 	p->scx.flags |= SCX_TASK_IN_CUSTODY;
2070 
2071 	/*
2072 	 * If not directly dispatched, QUEUEING isn't clear yet and dispatch or
2073 	 * dequeue may be waiting. The store_release matches their load_acquire.
2074 	 */
2075 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_QUEUED | qseq);
2076 	return;
2077 
2078 direct:
2079 	direct_dispatch(sch, p, enq_flags);
2080 	return;
2081 local_norefill:
2082 	scx_dispatch_enqueue(sch, rq, &rq->scx.local_dsq, p, 0, 0, enq_flags);
2083 	return;
2084 local:
2085 	dsq = &rq->scx.local_dsq;
2086 	goto enqueue;
2087 global:
2088 	dsq = find_global_dsq(sch, task_cpu(p));
2089 	goto enqueue;
2090 bypass:
2091 	dsq = bypass_enq_target_dsq(sch, task_cpu(p));
2092 	goto enqueue;
2093 
2094 enqueue:
2095 	refill_task_slice_dfl(sch, p);
2096 	clear_direct_dispatch(p);
2097 	scx_dispatch_enqueue(sch, rq, dsq, p, 0, 0, enq_flags);
2098 }
2099 
task_runnable(const struct task_struct * p)2100 static bool task_runnable(const struct task_struct *p)
2101 {
2102 	return !list_empty(&p->scx.runnable_node);
2103 }
2104 
set_task_runnable(struct rq * rq,struct task_struct * p)2105 static void set_task_runnable(struct rq *rq, struct task_struct *p)
2106 {
2107 	lockdep_assert_rq_held(rq);
2108 
2109 	if (p->scx.flags & SCX_TASK_RESET_RUNNABLE_AT) {
2110 		p->scx.runnable_at = jiffies;
2111 		p->scx.flags &= ~SCX_TASK_RESET_RUNNABLE_AT;
2112 	}
2113 
2114 	/*
2115 	 * list_add_tail() must be used. scx_bypass() depends on tasks being
2116 	 * appended to the runnable_list.
2117 	 */
2118 	list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list);
2119 
2120 	/*
2121 	 * Record the rq @p is runnable on, maintained under the rq lock so it
2122 	 * stays valid unlike task_cpu(), which a remote wakeup can move under
2123 	 * pi_lock alone.
2124 	 */
2125 	WRITE_ONCE(p->scx.runnable_cpu, cpu_of(rq));
2126 }
2127 
clr_task_runnable(struct task_struct * p,bool reset_runnable_at)2128 static void clr_task_runnable(struct task_struct *p, bool reset_runnable_at)
2129 {
2130 	list_del_init(&p->scx.runnable_node);
2131 	WRITE_ONCE(p->scx.runnable_cpu, -1);
2132 	if (reset_runnable_at) {
2133 		p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
2134 		p->scx.reenq_cnt = 0;
2135 	}
2136 }
2137 
enqueue_task_scx(struct rq * rq,struct task_struct * p,int core_enq_flags)2138 static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int core_enq_flags)
2139 {
2140 	struct scx_sched *sch = scx_task_sched(p);
2141 	int sticky_cpu = p->scx.sticky_cpu;
2142 	u64 enq_flags = core_enq_flags | rq->scx.remote_activate_enq_flags;
2143 
2144 	if (enq_flags & ENQUEUE_WAKEUP)
2145 		rq->scx.flags |= SCX_RQ_IN_WAKEUP;
2146 
2147 	/*
2148 	 * Restoring a running task will be immediately followed by
2149 	 * set_next_task_scx() which expects the task to not be on the BPF
2150 	 * scheduler as tasks can only start running through local DSQs. Force
2151 	 * direct-dispatch into the local DSQ by setting the sticky_cpu. Mark
2152 	 * IGNORE_CAPS to force entry into the local DSQ.
2153 	 */
2154 	if (unlikely(enq_flags & ENQUEUE_RESTORE) && task_current(rq, p)) {
2155 		sticky_cpu = cpu_of(rq);
2156 		enq_flags |= SCX_ENQ_IGNORE_CAPS;
2157 	}
2158 
2159 	if (p->scx.flags & SCX_TASK_QUEUED) {
2160 		WARN_ON_ONCE(!task_runnable(p));
2161 		goto out;
2162 	}
2163 
2164 	set_task_runnable(rq, p);
2165 	p->scx.flags |= SCX_TASK_QUEUED;
2166 	rq->scx.nr_running++;
2167 	add_nr_running(rq, 1);
2168 
2169 	if (SCX_HAS_OP(sch, runnable) && !task_on_rq_migrating(p))
2170 		SCX_CALL_OP_TASK(sch, runnable, rq, p, enq_flags);
2171 
2172 	/* Start dl_server if this is the first task being enqueued */
2173 	if (rq->scx.nr_running == 1)
2174 		dl_server_start(&rq->ext_server);
2175 
2176 	scx_do_enqueue_task(rq, p, enq_flags, sticky_cpu);
2177 
2178 	if (sticky_cpu >= 0)
2179 		p->scx.sticky_cpu = -1;
2180 out:
2181 	rq->scx.flags &= ~SCX_RQ_IN_WAKEUP;
2182 
2183 	if ((enq_flags & SCX_ENQ_CPU_SELECTED) &&
2184 	    unlikely(cpu_of(rq) != p->scx.selected_cpu))
2185 		__scx_add_event(sch, SCX_EV_SELECT_CPU_FALLBACK, 1);
2186 }
2187 
ops_dequeue(struct rq * rq,struct task_struct * p,u64 deq_flags)2188 static void ops_dequeue(struct rq *rq, struct task_struct *p, u64 deq_flags)
2189 {
2190 	struct scx_sched *sch = scx_task_sched(p);
2191 	unsigned long opss;
2192 
2193 	/* dequeue is always temporary, don't reset runnable_at */
2194 	clr_task_runnable(p, false);
2195 
2196 retry:
2197 	/* acquire ensures that we see the preceding updates on QUEUED */
2198 	opss = atomic_long_read_acquire(&p->scx.ops_state);
2199 
2200 	switch (opss & SCX_OPSS_STATE_MASK) {
2201 	case SCX_OPSS_NONE:
2202 		break;
2203 	case SCX_OPSS_QUEUEING:
2204 		/*
2205 		 * QUEUEING is started and finished while holding @p's rq lock.
2206 		 * As we're holding the rq lock now, we shouldn't see QUEUEING.
2207 		 */
2208 		BUG();
2209 	case SCX_OPSS_QUEUED:
2210 		/*
2211 		 * A queued task must always be in BPF scheduler's custody. If
2212 		 * SCX_TASK_IN_CUSTODY is clear, finish_dispatch() on another
2213 		 * CPU has already passed call_task_dequeue() (which clears the
2214 		 * flag), but has not yet written SCX_OPSS_NONE. That final
2215 		 * store does not require this rq's lock, so retrying with
2216 		 * cpu_relax() is bounded: we will observe NONE (or DISPATCHING,
2217 		 * handled by the fallthrough) on a subsequent iteration.
2218 		 */
2219 		if (unlikely(!(READ_ONCE(p->scx.flags) & SCX_TASK_IN_CUSTODY))) {
2220 			cpu_relax();
2221 			goto retry;
2222 		}
2223 
2224 		if (atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
2225 					    SCX_OPSS_NONE))
2226 			break;
2227 		fallthrough;
2228 	case SCX_OPSS_DISPATCHING:
2229 		/*
2230 		 * If @p is being dispatched from the BPF scheduler to a DSQ,
2231 		 * wait for the transfer to complete so that @p doesn't get
2232 		 * added to its DSQ after dequeueing is complete.
2233 		 *
2234 		 * As we're waiting on DISPATCHING with the rq locked, the
2235 		 * dispatching side shouldn't try to lock the rq while
2236 		 * DISPATCHING is set. See dispatch_to_local_dsq().
2237 		 *
2238 		 * DISPATCHING shouldn't have qseq set and control can reach
2239 		 * here with NONE @opss from the above QUEUED case block.
2240 		 * Explicitly wait on %SCX_OPSS_DISPATCHING instead of @opss.
2241 		 */
2242 		wait_ops_state(p, SCX_OPSS_DISPATCHING);
2243 		BUG_ON(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
2244 		break;
2245 	}
2246 
2247 	/*
2248 	 * Call ops.dequeue() if the task is still in BPF custody.
2249 	 *
2250 	 * The code that clears ops_state to %SCX_OPSS_NONE does not always
2251 	 * clear %SCX_TASK_IN_CUSTODY: in dispatch_to_local_dsq(), when
2252 	 * we're moving a task that was in %SCX_OPSS_DISPATCHING to a
2253 	 * remote CPU's local DSQ, we only set ops_state to %SCX_OPSS_NONE
2254 	 * so that a concurrent dequeue can proceed, but we clear
2255 	 * %SCX_TASK_IN_CUSTODY only when we later enqueue or move the
2256 	 * task. So we can see NONE + IN_CUSTODY here and we must handle
2257 	 * it. Similarly, after waiting on %SCX_OPSS_DISPATCHING we see
2258 	 * NONE but the task may still have %SCX_TASK_IN_CUSTODY set until
2259 	 * it is enqueued on the destination.
2260 	 */
2261 	call_task_dequeue(sch, rq, p, deq_flags);
2262 }
2263 
dequeue_task_scx(struct rq * rq,struct task_struct * p,int core_deq_flags)2264 static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int core_deq_flags)
2265 {
2266 	struct scx_sched *sch = scx_task_sched(p);
2267 	u64 deq_flags = core_deq_flags;
2268 
2269 	/*
2270 	 * Set %SCX_DEQ_SCHED_CHANGE when the dequeue is due to a property
2271 	 * change (not sleep).
2272 	 */
2273 	if (!(deq_flags & DEQUEUE_SLEEP))
2274 		deq_flags |= SCX_DEQ_SCHED_CHANGE;
2275 
2276 	if (!(p->scx.flags & SCX_TASK_QUEUED)) {
2277 		WARN_ON_ONCE(task_runnable(p));
2278 		return true;
2279 	}
2280 
2281 	ops_dequeue(rq, p, deq_flags);
2282 
2283 	/*
2284 	 * A currently running task which is going off @rq first gets dequeued
2285 	 * and then stops running. As we want running <-> stopping transitions
2286 	 * to be contained within runnable <-> quiescent transitions, trigger
2287 	 * ->stopping() early here instead of in put_prev_task_scx().
2288 	 *
2289 	 * @p may go through multiple stopping <-> running transitions between
2290 	 * here and put_prev_task_scx() if task attribute changes occur while
2291 	 * dispatch_one() leaves @rq unlocked. However, they don't contain any
2292 	 * information meaningful to the BPF scheduler and can be suppressed by
2293 	 * skipping the callbacks if the task is !QUEUED.
2294 	 */
2295 	if (task_current(rq, p) &&
2296 	    (SCX_HAS_OP(sch, stopping) || unlikely(p == scx_rescuee(rq)))) {
2297 		update_curr_scx(rq);
2298 		if (SCX_HAS_OP(sch, stopping))
2299 			SCX_CALL_OP_TASK(sch, stopping, rq, p, false);
2300 	}
2301 
2302 	if (SCX_HAS_OP(sch, quiescent) && !task_on_rq_migrating(p))
2303 		SCX_CALL_OP_TASK(sch, quiescent, rq, p, deq_flags);
2304 
2305 	if (deq_flags & SCX_DEQ_SLEEP)
2306 		p->scx.flags |= SCX_TASK_DEQD_FOR_SLEEP;
2307 	else
2308 		p->scx.flags &= ~SCX_TASK_DEQD_FOR_SLEEP;
2309 
2310 	p->scx.flags &= ~SCX_TASK_QUEUED;
2311 	rq->scx.nr_running--;
2312 	sub_nr_running(rq, 1);
2313 
2314 	scx_dispatch_dequeue(rq, p);
2315 
2316 	/* see scx_task_slice_ended() for the save/restore exception */
2317 	if (!((deq_flags & DEQUEUE_SAVE) && task_current(rq, p)))
2318 		scx_task_slice_ended(rq, p);
2319 
2320 	clear_direct_dispatch(p);
2321 	return true;
2322 }
2323 
yield_task_scx(struct rq * rq)2324 static void yield_task_scx(struct rq *rq)
2325 {
2326 	struct task_struct *p = rq->donor;
2327 	struct scx_sched *sch = scx_task_sched(p);
2328 
2329 	/* a yield gives the slice up */
2330 	scx_task_slice_ended(rq, p);
2331 
2332 	if (SCX_HAS_OP(sch, yield))
2333 		SCX_CALL_OP_2TASKS_RET(sch, yield, rq, p, NULL);
2334 	else
2335 		scx_set_task_slice(p, 0);
2336 }
2337 
yield_to_task_scx(struct rq * rq,struct task_struct * to)2338 static bool yield_to_task_scx(struct rq *rq, struct task_struct *to)
2339 {
2340 	struct task_struct *from = rq->donor;
2341 	struct scx_sched *sch = scx_task_sched(from);
2342 
2343 	/* like a plain yield, giving the slice up ends the protection */
2344 	scx_task_slice_ended(rq, from);
2345 
2346 	if (SCX_HAS_OP(sch, yield) && sch == scx_task_sched(to))
2347 		return SCX_CALL_OP_2TASKS_RET(sch, yield, rq, from, to);
2348 	else
2349 		return false;
2350 }
2351 
wakeup_preempt_scx(struct rq * rq,struct task_struct * p,int wake_flags)2352 static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p, int wake_flags)
2353 {
2354 	/*
2355 	 * Preemption between SCX tasks is implemented by resetting the victim
2356 	 * task's slice to 0 and triggering reschedule on the target CPU.
2357 	 * Nothing to do.
2358 	 */
2359 	if (p->sched_class == &ext_sched_class)
2360 		return;
2361 
2362 	/*
2363 	 * Getting preempted by a higher-priority class. Reenqueue IMMED tasks.
2364 	 * This captures all preemption cases including:
2365 	 *
2366 	 * - A SCX task is currently running.
2367 	 *
2368 	 * - @rq is waking from idle due to a SCX task waking to it.
2369 	 *
2370 	 * - A higher-priority wakes up while SCX dispatch is in progress.
2371 	 */
2372 	if (rq->scx.nr_immed)
2373 		scx_schedule_reenq_local(rq, 0);
2374 }
2375 
scx_move_local_task_to_local_dsq(struct scx_sched * sch,struct task_struct * p,u64 enq_flags,struct scx_dispatch_q * src_dsq,struct rq * dst_rq)2376 void scx_move_local_task_to_local_dsq(struct scx_sched *sch, struct task_struct *p,
2377 				      u64 enq_flags, struct scx_dispatch_q *src_dsq,
2378 				      struct rq *dst_rq)
2379 {
2380 	struct scx_dispatch_q *dst_dsq = scx_resolve_local_dsq(sch, dst_rq, p, &enq_flags);
2381 
2382 	/* @p is on @dst_rq, an rq-owned @src_dsq is covered by the rq lock */
2383 	if (!dsq_is_rq_owned(src_dsq))
2384 		lockdep_assert_held(&src_dsq->lock);
2385 	lockdep_assert_rq_held(dst_rq);
2386 
2387 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
2388 
2389 	if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT))
2390 		dsq_insert_head(dst_dsq, p);
2391 	else
2392 		list_add_tail(&p->scx.dsq_list.node, &dst_dsq->list);
2393 
2394 	dsq_inc_nr(dst_dsq, p, enq_flags);
2395 	p->scx.dsq = dst_dsq;
2396 
2397 	rq_owned_post_enq(sch, dst_rq, dst_dsq, p, enq_flags);
2398 }
2399 
2400 /**
2401  * move_remote_task_to_local_dsq - Move a task from a foreign rq to a local DSQ
2402  * @sch: scheduler placing @p
2403  * @p: task to move
2404  * @enq_flags: %SCX_ENQ_*
2405  * @src_rq: rq to move the task from, locked on entry, released on return
2406  * @dst_rq: rq to move the task into, locked on return
2407  *
2408  * Move @p which is currently on @src_rq to @dst_rq's local DSQ.
2409  */
move_remote_task_to_local_dsq(struct scx_sched * sch,struct task_struct * p,u64 enq_flags,struct rq * src_rq,struct rq * dst_rq)2410 static void move_remote_task_to_local_dsq(struct scx_sched *sch,
2411 					  struct task_struct *p, u64 enq_flags,
2412 					  struct rq *src_rq, struct rq *dst_rq)
2413 {
2414 	lockdep_assert_rq_held(src_rq);
2415 
2416 	/*
2417 	 * Set sticky_cpu before deactivate_task() to properly mark the
2418 	 * beginning of an SCX-internal migration.
2419 	 */
2420 	p->scx.sticky_cpu = cpu_of(dst_rq);
2421 	deactivate_task(src_rq, p, 0);
2422 	set_task_cpu(p, cpu_of(dst_rq));
2423 
2424 	switch_rq_lock(src_rq, dst_rq);
2425 
2426 	/*
2427 	 * activate_task() below truncates enq_flags to 32 bits and re-derives
2428 	 * @p's owner, dropping our scx flags and the placing @sch. We own @rq,
2429 	 * so stash both across the call. The enqueue reads them back, keeping
2430 	 * the scx flags and checking caps against the placer, not the owner.
2431 	 */
2432 	WARN_ON_ONCE(!cpumask_test_cpu(cpu_of(dst_rq), p->cpus_ptr));
2433 	WARN_ON_ONCE(dst_rq->scx.remote_activate_enq_flags ||
2434 		     dst_rq->scx.remote_activate_sch);
2435 	dst_rq->scx.remote_activate_enq_flags = enq_flags;
2436 	dst_rq->scx.remote_activate_sch = sch;
2437 	activate_task(dst_rq, p, 0);
2438 	dst_rq->scx.remote_activate_enq_flags = 0;
2439 	dst_rq->scx.remote_activate_sch = NULL;
2440 }
2441 
2442 /*
2443  * Similar to kernel/sched/core.c::is_cpu_allowed(). However, there are two
2444  * differences:
2445  *
2446  * - is_cpu_allowed() asks "Can this task run on this CPU?" while
2447  *   task_can_run_on_remote_rq() asks "Can the BPF scheduler migrate the task to
2448  *   this CPU?".
2449  *
2450  *   While migration is disabled, is_cpu_allowed() has to say "yes" as the task
2451  *   must be allowed to finish on the CPU that it's currently on regardless of
2452  *   the CPU state. However, task_can_run_on_remote_rq() must say "no" as the
2453  *   BPF scheduler shouldn't attempt to migrate a task which has migration
2454  *   disabled.
2455  *
2456  * - The BPF scheduler is bypassed while the rq is offline and we can always say
2457  *   no to the BPF scheduler initiated migrations while offline.
2458  *
2459  * The caller must ensure that @p and @rq are on different CPUs.
2460  * If enforce == true, caller must hold @p's rq lock.
2461  */
task_can_run_on_remote_rq(struct scx_sched * sch,struct task_struct * p,struct rq * rq,bool enforce)2462 static bool task_can_run_on_remote_rq(struct scx_sched *sch,
2463 				      struct task_struct *p, struct rq *rq,
2464 				      bool enforce)
2465 {
2466 	s32 cpu = cpu_of(rq);
2467 
2468 	/*
2469 	 * To prevent races with @p still running on its old CPU while switching
2470 	 * out, make sure we're holding @p's rq lock so as not to risk
2471 	 * erroneously killing the BPF scheduler.
2472 	 */
2473 	if (enforce)
2474 		lockdep_assert_rq_held(task_rq(p));
2475 
2476 	WARN_ON_ONCE(task_cpu(p) == cpu);
2477 
2478 	/*
2479 	 * If @p has migration disabled, @p->cpus_ptr is updated to contain only
2480 	 * the pinned CPU in migrate_disable_switch() while @p is being switched
2481 	 * out. However, put_prev_task_scx() is called before @p->cpus_ptr is
2482 	 * updated and thus another CPU may see @p on a DSQ inbetween leading to
2483 	 * @p passing the below task_allowed_on_cpu() check while migration is
2484 	 * disabled.
2485 	 *
2486 	 * Test the migration disabled state first as the race window is narrow
2487 	 * and the BPF scheduler failing to check migration disabled state can
2488 	 * easily be masked if task_allowed_on_cpu() is done first.
2489 	 */
2490 	if (unlikely(is_migration_disabled(p))) {
2491 		if (enforce)
2492 			scx_error(sch, "SCX_DSQ_LOCAL[_ON] cannot move migration disabled %s[%d] from CPU %d to %d",
2493 				  p->comm, p->pid, task_cpu(p), cpu);
2494 		return false;
2495 	}
2496 
2497 	/*
2498 	 * We don't require the BPF scheduler to avoid dispatching to offline
2499 	 * CPUs mostly for convenience but also because CPUs can go offline
2500 	 * between scx_bpf_dsq_insert() calls and here. Trigger error iff the
2501 	 * picked CPU is outside the allowed mask.
2502 	 */
2503 	if (!task_allowed_on_cpu(p, cpu)) {
2504 		if (enforce)
2505 			scx_error(sch, "SCX_DSQ_LOCAL[_ON] target CPU %d not allowed for %s[%d]",
2506 				  cpu, p->comm, p->pid);
2507 		return false;
2508 	}
2509 
2510 	if (!scx_rq_online(rq)) {
2511 		if (enforce)
2512 			__scx_add_event(sch, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE, 1);
2513 		return false;
2514 	}
2515 
2516 	return true;
2517 }
2518 
2519 /**
2520  * unlink_dsq_and_switch_rq_lock() - Unlink task and switch to its rq lock
2521  * @p: target task
2522  * @dsq: locked DSQ @p is currently on
2523  * @locked_rq: currently locked rq
2524  * @src_rq: rq @p is currently on, stable with @dsq locked
2525  *
2526  * Called with @dsq and @locked_rq locked. We want to move @p to a different DSQ,
2527  * including any local DSQ, but are not locking @src_rq. Locking @src_rq is
2528  * required when transferring into a local DSQ. Even when transferring into a
2529  * non-local DSQ, it's better to use the same mechanism to protect against
2530  * dequeues and maintain the invariant that @p->scx.dsq can only change while
2531  * @src_rq is locked, which e.g. scx_dump_task() depends on.
2532  *
2533  * We want to grab @src_rq but that can deadlock if we try while locking @dsq,
2534  * so we want to unlink @p from @dsq, drop its lock and then lock @src_rq. As
2535  * this may race with dequeue, which can't drop the rq lock or fail, do a little
2536  * dancing from our side.
2537  *
2538  * @p->scx.holding_cpu is set to this CPU before @dsq is unlocked. If @p gets
2539  * dequeued after we unlock @dsq but before locking @src_rq, the holding_cpu
2540  * would be cleared to -1. While other cpus may have updated it to different
2541  * values afterwards, as this operation can't be preempted or recurse, the
2542  * holding_cpu can never become this CPU again before we're done. Thus, we can
2543  * tell whether we lost to dequeue by testing whether the holding_cpu still
2544  * points to this CPU. See scx_dispatch_dequeue() for the counterpart.
2545  *
2546  * On return, @dsq is unlocked and @src_rq is locked. Returns %true if @p is
2547  * still valid. %false if lost to dequeue.
2548  */
unlink_dsq_and_switch_rq_lock(struct task_struct * p,struct scx_dispatch_q * dsq,struct rq * locked_rq,struct rq * src_rq)2549 static bool unlink_dsq_and_switch_rq_lock(struct task_struct *p,
2550 					  struct scx_dispatch_q *dsq,
2551 					  struct rq *locked_rq,
2552 					  struct rq *src_rq)
2553 {
2554 	s32 cpu = raw_smp_processor_id();
2555 
2556 	lockdep_assert_held(&dsq->lock);
2557 	lockdep_assert_rq_held(locked_rq);
2558 
2559 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
2560 	scx_task_unlink_from_dsq(p, dsq);
2561 	p->scx.holding_cpu = cpu;
2562 
2563 	raw_spin_unlock(&dsq->lock);
2564 	switch_rq_lock(locked_rq, src_rq);
2565 
2566 	/* task_rq couldn't have changed if we're still the holding cpu */
2567 	return likely(p->scx.holding_cpu == cpu) &&
2568 		!WARN_ON_ONCE(src_rq != task_rq(p));
2569 }
2570 
consume_remote_task(struct scx_sched * sch,struct rq * this_rq,struct task_struct * p,u64 enq_flags,struct scx_dispatch_q * dsq,struct rq * src_rq)2571 static bool consume_remote_task(struct scx_sched *sch, struct rq *this_rq,
2572 				struct task_struct *p, u64 enq_flags,
2573 				struct scx_dispatch_q *dsq, struct rq *src_rq)
2574 {
2575 	if (unlink_dsq_and_switch_rq_lock(p, dsq, this_rq, src_rq)) {
2576 		move_remote_task_to_local_dsq(sch, p, enq_flags, src_rq, this_rq);
2577 		return true;
2578 	} else {
2579 		switch_rq_lock(src_rq, this_rq);
2580 		return false;
2581 	}
2582 }
2583 
2584 /**
2585  * move_task_between_dsqs() - Move a task from one DSQ to another
2586  * @sch: scx_sched being operated on
2587  * @p: target task
2588  * @enq_flags: %SCX_ENQ_*
2589  * @src_dsq: DSQ @p is currently on, must not be a local DSQ
2590  * @dst_dsq: DSQ @p is being moved to, can be any DSQ
2591  *
2592  * Must be called with @p's task_rq and @src_dsq locked. If @dst_dsq is a local
2593  * DSQ and @p is on a different CPU, @p will be migrated and thus its task_rq
2594  * will change. As @p's task_rq is locked, this function doesn't need to use the
2595  * holding_cpu mechanism.
2596  *
2597  * On return, @src_dsq is unlocked and only @p's new task_rq, which is the
2598  * return value, is locked.
2599  */
move_task_between_dsqs(struct scx_sched * sch,struct task_struct * p,u64 enq_flags,struct scx_dispatch_q * src_dsq,struct scx_dispatch_q * dst_dsq)2600 static struct rq *move_task_between_dsqs(struct scx_sched *sch,
2601 					 struct task_struct *p, u64 enq_flags,
2602 					 struct scx_dispatch_q *src_dsq,
2603 					 struct scx_dispatch_q *dst_dsq)
2604 {
2605 	struct rq *src_rq = task_rq(p), *dst_rq;
2606 
2607 	BUG_ON(src_dsq->id == SCX_DSQ_LOCAL);
2608 	lockdep_assert_held(&src_dsq->lock);
2609 	lockdep_assert_rq_held(src_rq);
2610 
2611 	if (dst_dsq->id == SCX_DSQ_LOCAL) {
2612 		dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
2613 		if (src_rq != dst_rq &&
2614 		    unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) {
2615 			dst_dsq = find_global_dsq(sch, task_cpu(p));
2616 			dst_rq = src_rq;
2617 			enq_flags |= SCX_ENQ_GDSQ_FALLBACK;
2618 		}
2619 	} else {
2620 		/* no need to migrate if destination is a non-local DSQ */
2621 		dst_rq = src_rq;
2622 	}
2623 
2624 	/*
2625 	 * Move @p into $dst_dsq. If $dst_dsq is the local DSQ of a different
2626 	 * CPU, @p will be migrated.
2627 	 */
2628 	if (dst_dsq->id == SCX_DSQ_LOCAL) {
2629 		/* @p is going from a non-local DSQ to a local DSQ */
2630 		if (src_rq == dst_rq) {
2631 			scx_task_unlink_from_dsq(p, src_dsq);
2632 			scx_move_local_task_to_local_dsq(sch, p, enq_flags, src_dsq, dst_rq);
2633 			raw_spin_unlock(&src_dsq->lock);
2634 		} else {
2635 			raw_spin_unlock(&src_dsq->lock);
2636 			move_remote_task_to_local_dsq(sch, p, enq_flags, src_rq, dst_rq);
2637 		}
2638 	} else {
2639 		/*
2640 		 * @p is going from a non-local DSQ to a non-local DSQ. As
2641 		 * $src_dsq is already locked, do an abbreviated dequeue.
2642 		 */
2643 		dispatch_dequeue_locked(p, src_dsq);
2644 		raw_spin_unlock(&src_dsq->lock);
2645 
2646 		scx_dispatch_enqueue(sch, dst_rq, dst_dsq, p, 0, 0, enq_flags);
2647 	}
2648 
2649 	return dst_rq;
2650 }
2651 
scx_consume_dispatch_q(struct scx_sched * sch,struct rq * rq,struct scx_dispatch_q * dsq,u64 enq_flags)2652 bool scx_consume_dispatch_q(struct scx_sched *sch, struct rq *rq,
2653 			    struct scx_dispatch_q *dsq, u64 enq_flags)
2654 {
2655 	struct task_struct *p;
2656 retry:
2657 	/*
2658 	 * The caller can't expect to successfully consume a task if the task's
2659 	 * addition to @dsq isn't guaranteed to be visible somehow. Test
2660 	 * @dsq->list without locking and skip if it seems empty.
2661 	 */
2662 	if (list_empty(&dsq->list))
2663 		return false;
2664 
2665 	raw_spin_lock(&dsq->lock);
2666 
2667 	nldsq_for_each_task(p, dsq) {
2668 		struct rq *task_rq = task_rq(p);
2669 
2670 		/*
2671 		 * This loop can lead to multiple lockup scenarios, e.g. the BPF
2672 		 * scheduler can put an enormous number of affinitized tasks into
2673 		 * a contended DSQ, or the outer retry loop can repeatedly race
2674 		 * against scx_bypass() dequeueing tasks from @dsq trying to put
2675 		 * the system into the bypass mode. This can easily live-lock the
2676 		 * machine. If aborting, exit from all non-bypass DSQs.
2677 		 */
2678 		if (unlikely(READ_ONCE(sch->aborting)) && dsq->id != SCX_DSQ_BYPASS)
2679 			break;
2680 
2681 		if (rq == task_rq) {
2682 			scx_task_unlink_from_dsq(p, dsq);
2683 			scx_move_local_task_to_local_dsq(sch, p, enq_flags, dsq, rq);
2684 			raw_spin_unlock(&dsq->lock);
2685 			return true;
2686 		}
2687 
2688 		if (task_can_run_on_remote_rq(sch, p, rq, false)) {
2689 			if (likely(consume_remote_task(sch, rq, p, enq_flags, dsq, task_rq)))
2690 				return true;
2691 			goto retry;
2692 		}
2693 	}
2694 
2695 	raw_spin_unlock(&dsq->lock);
2696 	return false;
2697 }
2698 
scx_consume_global_dsq(struct scx_sched * sch,struct rq * rq)2699 bool scx_consume_global_dsq(struct scx_sched *sch, struct rq *rq)
2700 {
2701 	int node = cpu_to_node(cpu_of(rq));
2702 
2703 	return scx_consume_dispatch_q(sch, rq, &sch->pnode[node]->global_dsq, 0);
2704 }
2705 
2706 /**
2707  * dispatch_to_local_dsq - Dispatch a task to a local dsq
2708  * @sch: scx_sched being operated on
2709  * @rq: current rq which is locked
2710  * @dst_dsq: destination DSQ
2711  * @p: task to dispatch
2712  * @slice: slice carried by the insert verdict, 0 keeps the current value
2713  * @vtime: vtime carried by the insert verdict, committed on PRIQ inserts
2714  * @enq_flags: %SCX_ENQ_*
2715  *
2716  * We're holding @rq lock and want to dispatch @p to @dst_dsq which is a local
2717  * DSQ. This function performs all the synchronization dancing needed because
2718  * local DSQs are protected with rq locks.
2719  *
2720  * The caller must have exclusive ownership of @p (e.g. through
2721  * %SCX_OPSS_DISPATCHING).
2722  */
dispatch_to_local_dsq(struct scx_sched * sch,struct rq * rq,struct scx_dispatch_q * dst_dsq,struct task_struct * p,u64 slice,u64 vtime,u64 enq_flags)2723 static void dispatch_to_local_dsq(struct scx_sched *sch, struct rq *rq,
2724 				  struct scx_dispatch_q *dst_dsq, struct task_struct *p,
2725 				  u64 slice, u64 vtime, u64 enq_flags)
2726 {
2727 	struct rq *src_rq = task_rq(p);
2728 	struct rq *dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
2729 	struct rq *locked_rq = rq;
2730 
2731 	/*
2732 	 * We're synchronized against dequeue through DISPATCHING. As @p can't
2733 	 * be dequeued, its task_rq and cpus_allowed are stable too.
2734 	 *
2735 	 * If dispatching to @rq that @p is already on, no lock dancing needed.
2736 	 */
2737 	if (rq == src_rq && rq == dst_rq) {
2738 		scx_dispatch_enqueue(sch, rq, dst_dsq, p, slice, vtime,
2739 				     enq_flags | SCX_ENQ_APPLY_SLICE | SCX_ENQ_CLEAR_OPSS);
2740 		return;
2741 	}
2742 
2743 	/*
2744 	 * @p is on a possibly remote @src_rq which we need to lock to move the
2745 	 * task. If dequeue is in progress, it'd be locking @src_rq and waiting
2746 	 * on DISPATCHING, so we can't grab @src_rq lock while holding
2747 	 * DISPATCHING.
2748 	 *
2749 	 * As DISPATCHING guarantees that @p is wholly ours, we can pretend that
2750 	 * we're moving from a DSQ and use the same mechanism - mark the task
2751 	 * under transfer with holding_cpu, release DISPATCHING and then follow
2752 	 * the same protocol. See unlink_dsq_and_switch_rq_lock().
2753 	 */
2754 	p->scx.holding_cpu = raw_smp_processor_id();
2755 
2756 	/* store_release ensures that dequeue sees the above */
2757 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
2758 
2759 	/* switch to @src_rq lock */
2760 	if (locked_rq != src_rq) {
2761 		switch_rq_lock(locked_rq, src_rq);
2762 		locked_rq = src_rq;
2763 	}
2764 
2765 	/* task_rq couldn't have changed if we're still the holding cpu */
2766 	if (likely(p->scx.holding_cpu == raw_smp_processor_id()) &&
2767 	    !WARN_ON_ONCE(src_rq != task_rq(p))) {
2768 		bool fallback = false;
2769 		/*
2770 		 * If @p is staying on the same rq, there's no need to go
2771 		 * through the full deactivate/activate cycle. Optimize by
2772 		 * abbreviating move_remote_task_to_local_dsq().
2773 		 */
2774 		if (src_rq == dst_rq) {
2775 			p->scx.holding_cpu = -1;
2776 			scx_dispatch_enqueue(sch, dst_rq, &dst_rq->scx.local_dsq, p,
2777 					     slice, vtime, enq_flags | SCX_ENQ_APPLY_SLICE);
2778 		} else if (unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) {
2779 			p->scx.holding_cpu = -1;
2780 			fallback = true;
2781 			scx_dispatch_enqueue(sch, src_rq, find_global_dsq(sch, task_cpu(p)),
2782 					     p, slice, vtime,
2783 					     enq_flags | SCX_ENQ_APPLY_SLICE |
2784 					     SCX_ENQ_GDSQ_FALLBACK);
2785 		} else {
2786 			apply_slice_vtime(p, slice, vtime, enq_flags);
2787 			move_remote_task_to_local_dsq(sch, p, enq_flags, src_rq, dst_rq);
2788 			/* task has been moved to dst_rq, which is now locked */
2789 			locked_rq = dst_rq;
2790 		}
2791 
2792 		/* if the destination CPU is idle, wake it up */
2793 		if (!fallback && sched_class_above(p->sched_class, dst_rq->curr->sched_class))
2794 			resched_curr(dst_rq);
2795 	}
2796 
2797 	/* switch back to @rq lock */
2798 	if (locked_rq != rq)
2799 		switch_rq_lock(locked_rq, rq);
2800 }
2801 
2802 /**
2803  * finish_dispatch - Asynchronously finish dispatching a task
2804  * @sch: the scheduler
2805  * @rq: current rq which is locked
2806  * @p: task to finish dispatching
2807  * @qseq_at_dispatch: qseq when @p started getting dispatched
2808  * @dsq_id: destination DSQ ID
2809  * @enq_flags: %SCX_ENQ_*
2810  *
2811  * Dispatching to local DSQs may need to wait for queueing to complete or
2812  * require rq lock dancing. As we don't wanna do either while inside
2813  * ops.dispatch() to avoid locking order inversion, we split dispatching into
2814  * two parts. scx_bpf_dsq_insert() which is called by ops.dispatch() records the
2815  * task and its qseq. Once ops.dispatch() returns, this function is called to
2816  * finish up.
2817  *
2818  * There is no guarantee that @p is still valid for dispatching or even that it
2819  * was valid in the first place. Make sure that the task is still owned by the
2820  * BPF scheduler and claim the ownership before dispatching.
2821  */
finish_dispatch(struct scx_sched * sch,struct rq * rq,struct task_struct * p,unsigned long qseq_at_dispatch,u64 dsq_id,u64 slice,u64 vtime,u64 enq_flags)2822 static void finish_dispatch(struct scx_sched *sch, struct rq *rq, struct task_struct *p,
2823 			    unsigned long qseq_at_dispatch, u64 dsq_id,
2824 			    u64 slice, u64 vtime, u64 enq_flags)
2825 {
2826 	struct scx_dispatch_q *dsq;
2827 	unsigned long opss;
2828 
2829 retry:
2830 	/*
2831 	 * No need for _acquire here. @p is accessed only after a successful
2832 	 * try_cmpxchg to DISPATCHING.
2833 	 */
2834 	opss = atomic_long_read(&p->scx.ops_state);
2835 
2836 	switch (opss & SCX_OPSS_STATE_MASK) {
2837 	case SCX_OPSS_DISPATCHING:
2838 	case SCX_OPSS_NONE:
2839 		/* someone else already got to it */
2840 		return;
2841 	case SCX_OPSS_QUEUED:
2842 		/*
2843 		 * If qseq doesn't match, @p has gone through at least one
2844 		 * dispatch/dequeue and re-enqueue cycle between
2845 		 * scx_bpf_dsq_insert() and here and we have no claim on it.
2846 		 */
2847 		if ((opss & SCX_OPSS_QSEQ_MASK) != qseq_at_dispatch)
2848 			return;
2849 
2850 		/* see SCX_EV_INSERT_NOT_OWNED definition */
2851 		if (unlikely(!scx_task_on_sched(sch, p))) {
2852 			__scx_add_event(sch, SCX_EV_INSERT_NOT_OWNED, 1);
2853 			return;
2854 		}
2855 
2856 		/*
2857 		 * While we know @p is accessible, we don't yet have a claim on
2858 		 * it - the BPF scheduler is allowed to dispatch tasks
2859 		 * spuriously and there can be a racing dequeue attempt. Let's
2860 		 * claim @p by atomically transitioning it from QUEUED to
2861 		 * DISPATCHING.
2862 		 */
2863 		if (likely(atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
2864 						   SCX_OPSS_DISPATCHING)))
2865 			break;
2866 		goto retry;
2867 	case SCX_OPSS_QUEUEING:
2868 		/*
2869 		 * scx_do_enqueue_task() is in the process of transferring the
2870 		 * task to the BPF scheduler while holding @p's rq lock. As we
2871 		 * aren't holding any kernel or BPF resource that the enqueue
2872 		 * path may depend upon, it's safe to wait.
2873 		 */
2874 		wait_ops_state(p, opss);
2875 		goto retry;
2876 	}
2877 
2878 	BUG_ON(!(p->scx.flags & SCX_TASK_QUEUED));
2879 
2880 	dsq = find_dsq_for_dispatch(sch, rq, dsq_id, task_cpu(p));
2881 
2882 	if (dsq->id == SCX_DSQ_LOCAL)
2883 		dispatch_to_local_dsq(sch, rq, dsq, p, slice, vtime, enq_flags);
2884 	else
2885 		scx_dispatch_enqueue(sch, rq, dsq, p, slice, vtime,
2886 				     enq_flags | SCX_ENQ_APPLY_SLICE | SCX_ENQ_CLEAR_OPSS);
2887 }
2888 
scx_flush_dispatch_buf(struct scx_sched * sch,struct rq * rq)2889 void scx_flush_dispatch_buf(struct scx_sched *sch, struct rq *rq)
2890 {
2891 	struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
2892 	u32 u;
2893 
2894 	for (u = 0; u < dspc->cursor; u++) {
2895 		struct scx_dsp_buf_ent *ent = &dspc->buf[u];
2896 
2897 		finish_dispatch(sch, rq, ent->task, ent->qseq, ent->dsq_id,
2898 				ent->slice, ent->vtime, ent->enq_flags);
2899 	}
2900 
2901 	dspc->nr_tasks += dspc->cursor;
2902 	dspc->cursor = 0;
2903 }
2904 
maybe_queue_balance_callback(struct rq * rq)2905 static inline void maybe_queue_balance_callback(struct rq *rq)
2906 {
2907 	lockdep_assert_rq_held(rq);
2908 
2909 	if (!(rq->scx.flags & SCX_RQ_BAL_CB_PENDING))
2910 		return;
2911 
2912 	queue_balance_callback(rq, &rq->scx.deferred_bal_cb,
2913 				deferred_bal_cb_workfn);
2914 
2915 	rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING;
2916 }
2917 
dispatch_one(struct rq * rq,struct task_struct * prev)2918 static enum scx_dsp_verdict dispatch_one(struct rq *rq, struct task_struct *prev)
2919 {
2920 	struct scx_sched *sch = scx_root_protected_live();
2921 	enum scx_dsp_verdict verdict;
2922 	s32 cpu = cpu_of(rq);
2923 
2924 	lockdep_assert_rq_held(rq);
2925 	rq->scx.flags |= SCX_RQ_IN_DISPATCH;
2926 
2927 	scx_process_sync_ecaps(rq, prev);
2928 
2929 	if ((sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) &&
2930 	    unlikely(rq->scx.cpu_released)) {
2931 		/*
2932 		 * If the previous sched_class for the current CPU was not SCX,
2933 		 * notify the BPF scheduler that it again has control of the
2934 		 * core. This callback complements ->cpu_release(), which is
2935 		 * emitted in switch_class().
2936 		 */
2937 		if (sch->ops.cpu_acquire)
2938 			SCX_CALL_OP(sch, cpu_acquire, rq, cpu, NULL);
2939 		rq->scx.cpu_released = false;
2940 	}
2941 
2942 	if (prev->sched_class == &ext_sched_class) {
2943 		update_curr_scx(rq);
2944 
2945 		/*
2946 		 * If @prev is runnable & has slice left, it has priority and
2947 		 * fetching more just increases latency for the fetched tasks.
2948 		 * Tell pick_task_scx() to keep running @prev. If the BPF
2949 		 * scheduler wants to handle this explicitly, it should
2950 		 * implement ->cpu_release().
2951 		 *
2952 		 * See scx_disable_workfn() for the explanation on the bypassing
2953 		 * test.
2954 		 */
2955 		if ((prev->scx.flags & SCX_TASK_QUEUED) && prev->scx.slice &&
2956 		    !scx_bypassing(sch, cpu)) {
2957 			verdict = SCX_DSP_PREV;
2958 			goto has_tasks;
2959 		}
2960 	}
2961 
2962 	/* if there already are tasks to run, nothing to do */
2963 	if (rq->scx.local_dsq.nr) {
2964 		verdict = SCX_DSP_LOCAL;
2965 		goto has_tasks;
2966 	}
2967 
2968 	verdict = scx_dispatch_sched(sch, rq, prev, false);
2969 	if (verdict != SCX_DSP_NONE)
2970 		goto has_tasks;
2971 
2972 	/*
2973 	 * Didn't find another task to run. Keep running @prev unless
2974 	 * %SCX_OPS_ENQ_LAST is in effect.
2975 	 */
2976 	if ((prev->scx.flags & SCX_TASK_QUEUED) &&
2977 	    (!(sch->ops.flags & SCX_OPS_ENQ_LAST) || scx_bypassing(sch, cpu)) &&
2978 	    scx_task_can_stay_on_cpu(rq, prev)) {
2979 		__scx_add_event(sch, SCX_EV_DISPATCH_KEEP_LAST, 1);
2980 		verdict = SCX_DSP_PREV;
2981 		goto has_tasks;
2982 	}
2983 	rq->scx.flags &= ~SCX_RQ_IN_DISPATCH;
2984 	return SCX_DSP_NONE;
2985 
2986 has_tasks:
2987 	/*
2988 	 * @rq may have extra IMMED tasks without reenq scheduled:
2989 	 *
2990 	 * - rq_is_open() can't reliably tell when and how slice is going to be
2991 	 *   modified for $curr and allows IMMED tasks to be queued while
2992 	 *   dispatch is in progress.
2993 	 *
2994 	 * - A non-IMMED HEAD task can get queued in front of an IMMED task
2995 	 *   between the IMMED queueing and the subsequent scheduling event.
2996 	 */
2997 	if (unlikely(rq->scx.local_dsq.nr > 1 && rq->scx.nr_immed))
2998 		scx_schedule_reenq_local(rq, 0);
2999 
3000 	rq->scx.flags &= ~SCX_RQ_IN_DISPATCH;
3001 	return verdict;
3002 }
3003 
set_next_task_scx(struct rq * rq,struct task_struct * p,bool first)3004 static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first)
3005 {
3006 	struct scx_sched *sch = scx_task_sched(p);
3007 
3008 	if (p->scx.flags & SCX_TASK_QUEUED) {
3009 		/*
3010 		 * Core-sched might decide to execute @p before it is
3011 		 * dispatched. Call ops_dequeue() to notify the BPF scheduler.
3012 		 */
3013 		ops_dequeue(rq, p, SCX_DEQ_CORE_SCHED_EXEC);
3014 		scx_dispatch_dequeue(rq, p);
3015 	}
3016 
3017 	p->se.exec_start = rq_clock_task(rq);
3018 
3019 	/* see dequeue_task_scx() on why we skip when !QUEUED */
3020 	if (SCX_HAS_OP(sch, running) && (p->scx.flags & SCX_TASK_QUEUED))
3021 		SCX_CALL_OP_TASK(sch, running, rq, p);
3022 
3023 	clr_task_runnable(p, true);
3024 
3025 	/* apply any pending out-of-band slice request before the tick decision */
3026 	apply_task_slice_oob(rq, p);
3027 
3028 	/*
3029 	 * @p is getting newly scheduled or got kicked after someone updated its
3030 	 * slice. Update SCX_RQ_CAN_STOP_TICK to reflect whether the tick can be
3031 	 * stopped. See scx_can_stop_tick().
3032 	 *
3033 	 * Moreover, refresh the load_avgs just when transitioning in and out of
3034 	 * nohz. In the future, we might want to add a mechanism to update
3035 	 * load_avgs periodically on tick-stopped CPUs.
3036 	 */
3037 	if (p->scx.slice == SCX_SLICE_INF) {
3038 		if (!(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) {
3039 			/*
3040 			 * Bypass mode always assigns finite slices, so @p
3041 			 * can't have an infinite slice while bypassing.
3042 			 * Therefore, sched_update_tick_dependency() can safely
3043 			 * evaluate the outgoing task.
3044 			 */
3045 			rq->scx.flags |= SCX_RQ_CAN_STOP_TICK;
3046 			sched_update_tick_dependency(rq);
3047 
3048 			update_other_load_avgs(rq);
3049 		}
3050 	} else {
3051 		if (rq->scx.flags & SCX_RQ_CAN_STOP_TICK) {
3052 			rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK;
3053 			update_other_load_avgs(rq);
3054 		}
3055 
3056 		/*
3057 		 * @rq still references the outgoing scheduling context. A finite
3058 		 * slice is sufficient by itself to require the tick.
3059 		 */
3060 		if (tick_nohz_full_cpu(cpu_of(rq)))
3061 			tick_nohz_dep_set_cpu(cpu_of(rq), TICK_DEP_BIT_SCHED);
3062 	}
3063 }
3064 
3065 static enum scx_cpu_preempt_reason
preempt_reason_from_class(const struct sched_class * class)3066 preempt_reason_from_class(const struct sched_class *class)
3067 {
3068 	if (class == &stop_sched_class)
3069 		return SCX_CPU_PREEMPT_STOP;
3070 	if (class == &dl_sched_class)
3071 		return SCX_CPU_PREEMPT_DL;
3072 	if (class == &rt_sched_class)
3073 		return SCX_CPU_PREEMPT_RT;
3074 	return SCX_CPU_PREEMPT_UNKNOWN;
3075 }
3076 
switch_class(struct rq * rq,struct task_struct * next)3077 static void switch_class(struct rq *rq, struct task_struct *next)
3078 {
3079 	struct scx_sched *sch = scx_root_protected_live();
3080 	const struct sched_class *next_class = next->sched_class;
3081 
3082 	if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT))
3083 		return;
3084 
3085 	/*
3086 	 * The callback is conceptually meant to convey that the CPU is no
3087 	 * longer under the control of SCX. Therefore, don't invoke the callback
3088 	 * if the next class is below SCX (in which case the BPF scheduler has
3089 	 * actively decided not to schedule any tasks on the CPU).
3090 	 */
3091 	if (sched_class_above(&ext_sched_class, next_class))
3092 		return;
3093 
3094 	/*
3095 	 * At this point we know that SCX was preempted by a higher priority
3096 	 * sched_class, so invoke the ->cpu_release() callback if we have not
3097 	 * done so already. We only send the callback once between SCX being
3098 	 * preempted, and it regaining control of the CPU.
3099 	 *
3100 	 * ->cpu_release() complements ->cpu_acquire(), which is emitted the
3101 	 *  next time that dispatch_one() is invoked.
3102 	 */
3103 	if (!rq->scx.cpu_released) {
3104 		if (sch->ops.cpu_release) {
3105 			struct scx_cpu_release_args args = {
3106 				.reason = preempt_reason_from_class(next_class),
3107 				.task = next,
3108 			};
3109 
3110 			SCX_CALL_OP(sch, cpu_release, rq, cpu_of(rq), &args);
3111 		}
3112 		rq->scx.cpu_released = true;
3113 	}
3114 }
3115 
put_prev_task_scx(struct rq * rq,struct task_struct * p,struct task_struct * next)3116 static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
3117 			      struct task_struct *next)
3118 {
3119 	struct scx_sched *sch = scx_task_sched(p);
3120 	bool rescue_keep = false;
3121 
3122 	/* see kick_sync_wait_bal_cb() */
3123 	smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
3124 
3125 	update_curr_scx(rq);
3126 
3127 	/*
3128 	 * If the slice is consumed, protection ends with it. A rescuee
3129 	 * preempted beforehand keeps going, see scx_rescue_keep().
3130 	 */
3131 	if (!p->scx.slice) {
3132 		if (unlikely(p == scx_rescuee(rq)))
3133 			rescue_keep = scx_rescue_keep(rq, p);
3134 		if (!rescue_keep)
3135 			scx_task_slice_ended(rq, p);
3136 	}
3137 
3138 	/* see dequeue_task_scx() on why we skip when !QUEUED */
3139 	if (SCX_HAS_OP(sch, stopping) && (p->scx.flags & SCX_TASK_QUEUED))
3140 		SCX_CALL_OP_TASK(sch, stopping, rq, p, true);
3141 
3142 	if (p->scx.flags & SCX_TASK_QUEUED) {
3143 		set_task_runnable(rq, p);
3144 
3145 		/*
3146 		 * If @p has slice left and is being put, @p is getting
3147 		 * preempted by a higher priority scheduler class or core-sched
3148 		 * forcing a different task. Leave it at the head of the local
3149 		 * DSQ unless it was an IMMED task. IMMED tasks should not
3150 		 * linger on a busy CPU, reenqueue them to the BPF scheduler.
3151 		 *
3152 		 * An open rescue must keep @p on the local DSQ even if the
3153 		 * scheduler zeroed the slice in ops.stopping() above.
3154 		 */
3155 		if ((p->scx.slice || unlikely(p == scx_rescuee(rq))) &&
3156 		    !scx_bypassing(sch, cpu_of(rq))) {
3157 			if (p->scx.flags & SCX_TASK_IMMED) {
3158 				p->scx.flags |= SCX_TASK_REENQ_PREEMPTED;
3159 				scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
3160 				p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
3161 			} else {
3162 				u64 enq_flags = 0;
3163 
3164 				/*
3165 				 * Keep a preempted rescue going. If preempted
3166 				 * by another SCX task, append to the local DSQ,
3167 				 * see scx_rescue_keep().
3168 				 */
3169 				if (unlikely(p == scx_rescuee(rq))) {
3170 					enq_flags |= SCX_ENQ_IGNORE_CAPS;
3171 					if (!rescue_keep)
3172 						enq_flags |= SCX_ENQ_HEAD;
3173 				} else {
3174 					enq_flags |= SCX_ENQ_HEAD;
3175 				}
3176 
3177 				scx_dispatch_enqueue(sch, rq, &rq->scx.local_dsq, p, 0, 0,
3178 						     enq_flags);
3179 			}
3180 			goto switch_class;
3181 		}
3182 
3183 		/*
3184 		 * If @p is runnable but we're about to enter a lower
3185 		 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell
3186 		 * ops.enqueue() that @p is the only one available for this cpu,
3187 		 * which should trigger an explicit follow-up scheduling event.
3188 		 * This doesn't apply if the baseline access on the CPU is lost.
3189 		 *
3190 		 * Under core scheduling, a pick dispatches only when nothing is
3191 		 * locally runnable and can legitimately go idle with @p still
3192 		 * runnable (see do_pick_task_scx()).
3193 		 */
3194 		if (next && sched_class_above(&ext_sched_class, next->sched_class) &&
3195 		    scx_task_can_stay_on_cpu(rq, p)) {
3196 			WARN_ON_ONCE(!sched_core_enabled(rq) &&
3197 				     !(sch->ops.flags & SCX_OPS_ENQ_LAST));
3198 			scx_do_enqueue_task(rq, p, SCX_ENQ_LAST, -1);
3199 		} else {
3200 			scx_do_enqueue_task(rq, p, 0, -1);
3201 		}
3202 	}
3203 
3204 switch_class:
3205 	if (next && next->sched_class != &ext_sched_class)
3206 		switch_class(rq, next);
3207 }
3208 
kick_sync_wait_bal_cb(struct rq * rq)3209 static void kick_sync_wait_bal_cb(struct rq *rq)
3210 {
3211 	struct scx_kick_syncs __rcu *ks;
3212 	unsigned long *ksyncs;
3213 	bool waited;
3214 	s32 cpu;
3215 
3216 	/*
3217 	 * This callback is queued and normally flushed within @rq's own
3218 	 * scheduling pass. However, dispatch can drop the rq lock while it sits
3219 	 * queued, and lock takers in that window (the sched class change paths,
3220 	 * the scx task iterator) flush pending balance callbacks on release,
3221 	 * running this one on a foreign CPU whose snapshots are unrelated. The
3222 	 * kicked CPUs are already on their way to advance the kick_syncs being
3223 	 * waited on. Don't get in the way.
3224 	 */
3225 	if (unlikely(cpu_of(rq) != smp_processor_id()))
3226 		return;
3227 
3228 	ks = __this_cpu_read(scx_kick_syncs);
3229 	ksyncs = rcu_dereference_sched(ks)->syncs;
3230 
3231 	/*
3232 	 * Drop rq lock and enable IRQs while waiting. IRQs must be enabled
3233 	 * — a target CPU may be waiting for us to process an IPI (e.g. TLB
3234 	 * flush) while we wait for its kick_sync to advance.
3235 	 *
3236 	 * Also, keep advancing our own kick_sync so that new kick_sync waits
3237 	 * targeting us, which can start after we drop the lock, cannot form
3238 	 * cyclic dependencies.
3239 	 */
3240 retry:
3241 	waited = false;
3242 	for_each_cpu(cpu, rq->scx.cpus_to_sync) {
3243 		/*
3244 		 * smp_load_acquire() pairs with smp_store_release() on
3245 		 * kick_sync updates on the target CPUs.
3246 		 */
3247 		if (cpu == cpu_of(rq) ||
3248 		    smp_load_acquire(&cpu_rq(cpu)->scx.kick_sync) != ksyncs[cpu]) {
3249 			cpumask_clear_cpu(cpu, rq->scx.cpus_to_sync);
3250 			continue;
3251 		}
3252 
3253 		scx_rq_lock_drop(rq);
3254 		raw_spin_rq_unlock_irq(rq);
3255 		while (READ_ONCE(cpu_rq(cpu)->scx.kick_sync) == ksyncs[cpu]) {
3256 			smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
3257 			cpu_relax();
3258 		}
3259 		raw_spin_rq_lock_irq(rq);
3260 		waited = true;
3261 	}
3262 
3263 	if (waited)
3264 		goto retry;
3265 }
3266 
first_local_task(struct rq * rq)3267 static struct task_struct *first_local_task(struct rq *rq)
3268 {
3269 	return list_first_entry_or_null(&rq->scx.local_dsq.list,
3270 					struct task_struct, scx.dsq_list.node);
3271 }
3272 
3273 /*
3274  * Run dispatch and queue the follow-up work for a pick.
3275  */
dispatch_pick(struct rq * rq,struct rq_flags * rf,struct task_struct * prev)3276 static enum scx_dsp_verdict dispatch_pick(struct rq *rq, struct rq_flags *rf,
3277 					  struct task_struct *prev)
3278 {
3279 	enum scx_dsp_verdict verdict;
3280 
3281 	rq_unpin_lock(rq, rf);
3282 	verdict = dispatch_one(rq, prev);
3283 	rq_repin_lock(rq, rf);
3284 	maybe_queue_balance_callback(rq);
3285 
3286 	/*
3287 	 * Defer to a balance callback which can drop rq lock and enable IRQs.
3288 	 * Waiting directly in the pick path would deadlock against CPUs sending
3289 	 * us IPIs (e.g. TLB flushes) while we wait for them.
3290 	 */
3291 	if (unlikely(rq->scx.kick_sync_pending)) {
3292 		rq->scx.kick_sync_pending = false;
3293 		queue_balance_callback(rq, &rq->scx.kick_sync_bal_cb,
3294 				       kick_sync_wait_bal_cb);
3295 	}
3296 
3297 	return verdict;
3298 }
3299 
3300 #ifdef CONFIG_SCHED_CORE
3301 /*
3302  * Dispatch for a pick when core scheduling is enabled. The selection picks for
3303  * all SMT siblings and the rq_i->core_pick state it builds must stay atomic
3304  * throughout. If the dispatch released the rq lock, anything can have happened
3305  * in between - return %SCX_DSP_RETRY to restart the selection against current
3306  * state.
3307  */
dispatch_core_pick(struct rq * rq,struct rq_flags * rf,struct task_struct * prev)3308 static enum scx_dsp_verdict dispatch_core_pick(struct rq *rq, struct rq_flags *rf,
3309 					       struct task_struct *prev)
3310 {
3311 	enum scx_dsp_verdict verdict;
3312 	u32 seq = rq->scx.lock_drop_seq;
3313 
3314 	/* another dispatch is in flight on @rq, let that handle it */
3315 	if (rq->scx.flags & SCX_RQ_IN_DISPATCH)
3316 		return SCX_DSP_NONE;
3317 
3318 	rq_unpin_lock(rq, rf);
3319 
3320 	verdict = dispatch_one(rq, prev);
3321 
3322 	if (cpu_of(rq) == smp_processor_id()) {
3323 		maybe_queue_balance_callback(rq);
3324 
3325 		/* see dispatch_pick() */
3326 		if (unlikely(rq->scx.kick_sync_pending)) {
3327 			rq->scx.kick_sync_pending = false;
3328 			queue_balance_callback(rq, &rq->scx.kick_sync_bal_cb,
3329 					       kick_sync_wait_bal_cb);
3330 		}
3331 	} else if (unlikely(rq->scx.flags & SCX_RQ_BAL_CB_PENDING)) {
3332 		/*
3333 		 * Balance callbacks must run in the context that queued them,
3334 		 * so they can't be queued on another CPU's rq. Run the deferred
3335 		 * work directly instead.
3336 		 */
3337 		rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING;
3338 		run_deferred(rq);
3339 	}
3340 
3341 	rq_repin_lock(rq, rf);
3342 
3343 	/* if dispatch_one() released the rq lock, restart the selection */
3344 	if (rq->scx.lock_drop_seq != seq)
3345 		return SCX_DSP_RETRY;
3346 
3347 	return verdict;
3348 }
3349 #else	/* CONFIG_SCHED_CORE */
dispatch_core_pick(struct rq * rq,struct rq_flags * rf,struct task_struct * prev)3350 static enum scx_dsp_verdict dispatch_core_pick(struct rq *rq, struct rq_flags *rf,
3351 					       struct task_struct *prev)
3352 {
3353 	return SCX_DSP_NONE;
3354 }
3355 #endif	/* CONFIG_SCHED_CORE */
3356 
3357 static struct task_struct *
do_pick_task_scx(struct rq * rq,struct rq_flags * rf,bool force_scx)3358 do_pick_task_scx(struct rq *rq, struct rq_flags *rf, bool force_scx)
3359 {
3360 	struct task_struct *prev = rq->curr;
3361 	enum scx_dsp_verdict verdict;
3362 	struct task_struct *p;
3363 
3364 	/* see kick_sync_wait_bal_cb() */
3365 	smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
3366 
3367 	rq_modified_begin(rq, &ext_sched_class);
3368 
3369 	if (sched_core_enabled(rq))
3370 		verdict = dispatch_core_pick(rq, rf, prev);
3371 	else
3372 		verdict = dispatch_pick(rq, rf, prev);
3373 
3374 	if (verdict == SCX_DSP_RETRY)
3375 		return RETRY_TASK;
3376 
3377 	/*
3378 	 * If any higher-priority sched class enqueued a runnable task on this
3379 	 * rq during dispatch_one(), abort and return RETRY_TASK, so that the
3380 	 * scheduler loop can restart.
3381 	 *
3382 	 * If @force_scx is true, always try to pick a SCHED_EXT task,
3383 	 * regardless of any higher-priority sched classes activity.
3384 	 */
3385 	if (!force_scx && rq_modified_above(rq, &ext_sched_class))
3386 		return RETRY_TASK;
3387 
3388 	/*
3389 	 * If we're keeping @prev, replenish slice if necessary and keep running
3390 	 * @prev. Otherwise, pop the first one from the local DSQ.
3391 	 */
3392 	if (verdict == SCX_DSP_PREV) {
3393 		p = prev;
3394 		if (!p->scx.slice) {
3395 			/* the slice is consumed, protection ends */
3396 			scx_task_slice_ended(rq, p);
3397 			refill_task_slice_dfl(scx_task_sched(p), p);
3398 		}
3399 	} else {
3400 		p = first_local_task(rq);
3401 		if (!p)
3402 			return NULL;
3403 
3404 		if (unlikely(!p->scx.slice) && scx_task_can_stay_on_cpu(rq, p)) {
3405 			struct scx_sched *sch = scx_task_sched(p);
3406 
3407 			if (!scx_bypassing(sch, cpu_of(rq)) &&
3408 			    !sch->warned_zero_slice) {
3409 				printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in %s()\n",
3410 						p->comm, p->pid, __func__);
3411 				sch->warned_zero_slice = true;
3412 			}
3413 			refill_task_slice_dfl(sch, p);
3414 		}
3415 	}
3416 
3417 	return p;
3418 }
3419 
pick_task_scx(struct rq * rq,struct rq_flags * rf)3420 static struct task_struct *pick_task_scx(struct rq *rq, struct rq_flags *rf)
3421 {
3422 	return do_pick_task_scx(rq, rf, false);
3423 }
3424 
3425 /*
3426  * Select the next task to run from the ext scheduling class.
3427  *
3428  * Use do_pick_task_scx() directly with @force_scx enabled, since the
3429  * dl_server must always select a sched_ext task.
3430  */
3431 static struct task_struct *
ext_server_pick_task(struct sched_dl_entity * dl_se,struct rq_flags * rf)3432 ext_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
3433 {
3434 	if (!scx_enabled())
3435 		return NULL;
3436 
3437 	return do_pick_task_scx(dl_se->rq, rf, true);
3438 }
3439 
3440 /*
3441  * Initialize the ext server deadline entity.
3442  */
ext_server_init(struct rq * rq)3443 void ext_server_init(struct rq *rq)
3444 {
3445 	struct sched_dl_entity *dl_se = &rq->ext_server;
3446 
3447 	init_dl_entity(dl_se);
3448 
3449 	dl_server_init(dl_se, rq, ext_server_pick_task);
3450 }
3451 
3452 #ifdef CONFIG_SCHED_CORE
3453 /**
3454  * scx_prio_less - Task ordering for core-sched
3455  * @a: task A
3456  * @b: task B
3457  * @in_fi: in forced idle state
3458  *
3459  * Core-sched is implemented as an additional scheduling layer on top of the
3460  * usual sched_class'es and needs to find out the expected task ordering. For
3461  * SCX, core-sched calls this function to interrogate the task ordering.
3462  *
3463  * A pair of tasks owned by one scheduler is ordered by the owner's
3464  * ops.core_sched_before(). A pair spanning two schedulers is ordered by their
3465  * nearest common ancestor which implements the op - the one case where the op
3466  * is called on tasks that the scheduler delegated to its sub-schedulers and may
3467  * not be scheduling anymore.
3468  *
3469  * When neither applies, or the deciding scheduler is bypassing on either task's
3470  * CPU, the default ordering runs the task which has been waiting longer first.
3471  * A running task counts as the most recently serviced and orders after every
3472  * waiting task. Waiting tasks are compared by @p->scx.runnable_at.
3473  *
3474  * Return: %true if @a should run after @b.
3475  */
scx_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)3476 bool scx_prio_less(const struct task_struct *a, const struct task_struct *b,
3477 		   bool in_fi)
3478 {
3479 	struct scx_sched *sch_a = scx_task_sched(a);
3480 	struct scx_sched *sch_b = scx_task_sched(b);
3481 	struct scx_sched *sch = NULL;
3482 	bool a_running, b_running;
3483 
3484 	if (sch_a == sch_b) {
3485 		if (SCX_HAS_OP(sch_a, core_sched_before))
3486 			sch = sch_a;
3487 	} else {
3488 		s32 level;
3489 
3490 		for (level = min(sch_a->level, sch_b->level); level >= 0; level--) {
3491 			struct scx_sched *anc = sch_a->ancestors[level];
3492 
3493 			if (anc == sch_b->ancestors[level] &&
3494 			    SCX_HAS_OP(anc, core_sched_before)) {
3495 				sch = anc;
3496 				break;
3497 			}
3498 		}
3499 	}
3500 
3501 	/*
3502 	 * scx_prio_less() returns whether @a should run after @b while
3503 	 * ops.core_sched_before() returns whether its first argument should run
3504 	 * before the second. Swap the arguments.
3505 	 *
3506 	 * The const qualifiers are dropped from task_struct pointers when
3507 	 * calling ops.core_sched_before(). Accesses are controlled by the
3508 	 * verifier.
3509 	 */
3510 	if (sch && !scx_bypassing(sch, task_cpu(a)) && !scx_bypassing(sch, task_cpu(b)))
3511 		return SCX_CALL_OP_2TASKS_RET(sch, core_sched_before, task_rq(a),
3512 					      (struct task_struct *)b,
3513 					      (struct task_struct *)a);
3514 
3515 	/*
3516 	 * runnable_at is refreshed only on enqueue, so a task which keeps
3517 	 * occupying its CPU carries a stale stamp. A running task is the most
3518 	 * recently serviced whatever its stamp says. Order it after every
3519 	 * waiting task.
3520 	 */
3521 	a_running = a->on_cpu;
3522 	b_running = b->on_cpu;
3523 	if (a_running != b_running)
3524 		return a_running;
3525 
3526 	return time_after(a->scx.runnable_at, b->scx.runnable_at);
3527 }
3528 #endif	/* CONFIG_SCHED_CORE */
3529 
select_task_rq_scx(struct task_struct * p,int prev_cpu,int wake_flags)3530 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags)
3531 {
3532 	struct scx_sched *sch = scx_task_sched(p);
3533 	bool bypassing;
3534 
3535 	/*
3536 	 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it
3537 	 * can be a good migration opportunity with low cache and memory
3538 	 * footprint. Returning a CPU different than @prev_cpu triggers
3539 	 * immediate rq migration. However, for SCX, as the current rq
3540 	 * association doesn't dictate where the task is going to run, this
3541 	 * doesn't fit well. If necessary, we can later add a dedicated method
3542 	 * which can decide to preempt self to force it through the regular
3543 	 * scheduling path.
3544 	 */
3545 	if (unlikely(wake_flags & WF_EXEC))
3546 		return prev_cpu;
3547 
3548 	bypassing = scx_bypassing(sch, task_cpu(p));
3549 	if (likely(SCX_HAS_OP(sch, select_cpu)) && !bypassing) {
3550 		s32 cpu;
3551 		struct task_struct **ddsp_taskp;
3552 
3553 		ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
3554 		WARN_ON_ONCE(*ddsp_taskp);
3555 		*ddsp_taskp = p;
3556 
3557 		this_rq()->scx.in_select_cpu = true;
3558 		cpu = SCX_CALL_OP_TASK_RET(sch, select_cpu, NULL, p,
3559 					   scx_cpu_arg(prev_cpu), wake_flags);
3560 		cpu = scx_cpu_ret(sch, cpu);
3561 		this_rq()->scx.in_select_cpu = false;
3562 		p->scx.selected_cpu = cpu;
3563 		*ddsp_taskp = NULL;
3564 		if (scx_cpu_valid(sch, cpu, "from ops.select_cpu()"))
3565 			return cpu;
3566 		else
3567 			return prev_cpu;
3568 	} else {
3569 		s32 cpu;
3570 
3571 		/*
3572 		 * While bypassing, the enqueue path routes @p to a bypass DSQ
3573 		 * without consulting the direct-dispatch target, making the
3574 		 * default selection pointless. It doesn't work anyway when the
3575 		 * scheduler does its own idle tracking and the built-in idle
3576 		 * cpumasks are not updated. Leave @p on @prev_cpu.
3577 		 */
3578 		if (bypassing) {
3579 			__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
3580 			p->scx.selected_cpu = prev_cpu;
3581 			return prev_cpu;
3582 		}
3583 
3584 		cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, NULL, 0);
3585 		if (cpu >= 0) {
3586 			/*
3587 			 * Carry the slice refill and let the insertion commit
3588 			 * it under rq lock. See the write rules.
3589 			 */
3590 			__scx_add_event(sch, SCX_EV_REFILL_SLICE_DFL, 1);
3591 			p->scx.ddsp_slice = READ_ONCE(sch->slice_dfl);
3592 			p->scx.ddsp_enq_flags = SCX_ENQ_SLICE_DFL;
3593 			p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL;
3594 		} else {
3595 			cpu = prev_cpu;
3596 		}
3597 		p->scx.selected_cpu = cpu;
3598 
3599 		return cpu;
3600 	}
3601 }
3602 
task_woken_scx(struct rq * rq,struct task_struct * p)3603 static void task_woken_scx(struct rq *rq, struct task_struct *p)
3604 {
3605 	run_deferred(rq);
3606 }
3607 
set_cpus_allowed_scx(struct task_struct * p,struct affinity_context * ac)3608 static void set_cpus_allowed_scx(struct task_struct *p,
3609 				 struct affinity_context *ac)
3610 {
3611 	struct scx_sched *sch = scx_task_sched(p);
3612 
3613 	set_cpus_allowed_common(p, ac);
3614 
3615 	if (task_dead_and_done(p))
3616 		return;
3617 
3618 	/*
3619 	 * The effective cpumask is stored in @p->cpus_ptr which may temporarily
3620 	 * differ from the configured one in @p->cpus_mask. Always tell the bpf
3621 	 * scheduler the effective one.
3622 	 *
3623 	 * Fine-grained memory write control is enforced by BPF making the const
3624 	 * designation pointless. Cast it away when calling the operation.
3625 	 */
3626 	if (SCX_HAS_OP(sch, set_cpumask))
3627 		scx_call_op_set_cpumask(sch, task_rq(p), p, (struct cpumask *)p->cpus_ptr);
3628 }
3629 
handle_hotplug(struct rq * rq,bool online)3630 static void handle_hotplug(struct rq *rq, bool online)
3631 {
3632 	struct scx_sched *sch = scx_root_protected();
3633 	s32 cpu = cpu_of(rq);
3634 	s32 cpu_or_cid = cpu;
3635 
3636 	atomic_long_inc(&scx_hotplug_seq);
3637 
3638 	/*
3639 	 * scx_root updates are protected by cpus_read_lock() and will stay
3640 	 * stable here. Note that we can't depend on scx_enabled() test as the
3641 	 * hotplug ops need to be enabled before __scx_enabled is set.
3642 	 */
3643 	if (unlikely(!sch))
3644 		return;
3645 
3646 	if (scx_enabled())
3647 		scx_idle_update_selcpu_topology(&sch->ops);
3648 
3649 	if (online)
3650 		scx_online_ecaps(rq);
3651 	else
3652 		scx_offline_ecaps(rq);
3653 
3654 	/*
3655 	 * The tables can't be retired while this function is running as the
3656 	 * retirement is inside cpus_read_lock. However, scx_cpu_arg() is
3657 	 * awkward here as the tables can be NULL after root enable failure and
3658 	 * lockdep would trigger without surrounding rcu_read_lock(). Open code
3659 	 * the translation. If the table is NULL, the ops are also cleared and
3660 	 * @cpu_or_cid goes unused.
3661 	 */
3662 	if (scx_is_cid_type()) {
3663 		s16 *tbl = rcu_dereference_check(scx_cpu_to_cid_tbl,
3664 						 lockdep_is_cpus_held());
3665 
3666 		if (tbl)
3667 			cpu_or_cid = tbl[cpu];
3668 	}
3669 
3670 	if (online && SCX_HAS_OP(sch, cpu_online))
3671 		SCX_CALL_OP(sch, cpu_online, NULL, cpu_or_cid);
3672 	else if (!online && SCX_HAS_OP(sch, cpu_offline))
3673 		SCX_CALL_OP(sch, cpu_offline, NULL, cpu_or_cid);
3674 	else
3675 		scx_exit(sch, SCX_EXIT_UNREG_KERN,
3676 			 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
3677 			 "cpu %d going %s, exiting scheduler", cpu,
3678 			 online ? "online" : "offline");
3679 }
3680 
scx_rq_activate(struct rq * rq)3681 void scx_rq_activate(struct rq *rq)
3682 {
3683 	handle_hotplug(rq, true);
3684 }
3685 
scx_rq_deactivate(struct rq * rq)3686 void scx_rq_deactivate(struct rq *rq)
3687 {
3688 	handle_hotplug(rq, false);
3689 }
3690 
rq_online_scx(struct rq * rq)3691 static void rq_online_scx(struct rq *rq)
3692 {
3693 	rq->scx.flags |= SCX_RQ_ONLINE;
3694 }
3695 
rq_offline_scx(struct rq * rq)3696 static void rq_offline_scx(struct rq *rq)
3697 {
3698 	rq->scx.flags &= ~SCX_RQ_ONLINE;
3699 	scx_rescue_flush(rq);
3700 }
3701 
check_rq_for_timeouts(struct rq * rq)3702 static bool check_rq_for_timeouts(struct rq *rq)
3703 {
3704 	struct scx_sched *sch;
3705 	struct task_struct *p;
3706 	struct rq_flags rf;
3707 	bool timed_out = false;
3708 
3709 	rq_lock_irqsave(rq, &rf);
3710 	sch = rcu_dereference_bh(scx_root);
3711 	if (unlikely(!sch))
3712 		goto out_unlock;
3713 
3714 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) {
3715 		struct scx_sched *sch = scx_task_sched(p);
3716 		unsigned long last_runnable = p->scx.runnable_at;
3717 
3718 		if (unlikely(time_after(jiffies,
3719 					last_runnable + READ_ONCE(sch->watchdog_timeout)))) {
3720 			struct scx_dispatch_q *dsq = READ_ONCE(p->scx.dsq);
3721 			u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable);
3722 
3723 			/*
3724 			 * A task can be stuck on a DSQ that a sched other than
3725 			 * its owner is responsible for draining, e.g. an
3726 			 * ancestor's bypass DSQ while the owner is bypassing.
3727 			 * Blame the drainer. The local DSQ is consumed by the
3728 			 * cpu itself and keeps blame on the owner.
3729 			 */
3730 			if (dsq && dsq->sched && dsq->id != SCX_DSQ_LOCAL)
3731 				sch = dsq->sched;
3732 
3733 			__scx_exit(sch, SCX_EXIT_ERROR_STALL, 0, cpu_of(rq),
3734 				   "%s[%d] failed to run for %u.%03us",
3735 				   p->comm, p->pid, dur_ms / 1000,
3736 				   dur_ms % 1000);
3737 			timed_out = true;
3738 			break;
3739 		}
3740 	}
3741 out_unlock:
3742 	rq_unlock_irqrestore(rq, &rf);
3743 	return timed_out;
3744 }
3745 
scx_watchdog_workfn(struct work_struct * work)3746 static void scx_watchdog_workfn(struct work_struct *work)
3747 {
3748 	unsigned long intv;
3749 	int cpu;
3750 
3751 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
3752 
3753 	for_each_online_cpu(cpu) {
3754 		if (unlikely(check_rq_for_timeouts(cpu_rq(cpu))))
3755 			break;
3756 
3757 		cond_resched();
3758 	}
3759 
3760 	intv = READ_ONCE(scx_watchdog_interval);
3761 	if (intv < ULONG_MAX)
3762 		queue_delayed_work(system_dfl_wq, to_delayed_work(work), intv);
3763 }
3764 
scx_tick(struct rq * rq)3765 void scx_tick(struct rq *rq)
3766 {
3767 	struct scx_sched *root;
3768 	unsigned long last_check;
3769 
3770 	if (!scx_enabled())
3771 		return;
3772 
3773 	root = rcu_dereference_bh(scx_root);
3774 	if (unlikely(!root))
3775 		return;
3776 
3777 	last_check = READ_ONCE(scx_watchdog_timestamp);
3778 	if (unlikely(time_after(jiffies,
3779 				last_check + READ_ONCE(root->watchdog_timeout)))) {
3780 		u32 dur_ms = jiffies_to_msecs(jiffies - last_check);
3781 
3782 		scx_exit(root, SCX_EXIT_ERROR_STALL, 0,
3783 			 "watchdog failed to check in for %u.%03us",
3784 			 dur_ms / 1000, dur_ms % 1000);
3785 	}
3786 
3787 	update_other_load_avgs(rq);
3788 }
3789 
task_tick_scx(struct rq * rq,struct task_struct * curr,int queued)3790 static void task_tick_scx(struct rq *rq, struct task_struct *curr, int queued)
3791 {
3792 	struct scx_sched *sch = scx_task_sched(curr);
3793 
3794 	update_curr_scx(rq);
3795 
3796 	/*
3797 	 * While disabling, always resched as we can't trust the slice
3798 	 * management.
3799 	 */
3800 	if (scx_bypassing(sch, cpu_of(rq)))
3801 		scx_set_task_slice(curr, 0);
3802 	else if (SCX_HAS_OP(sch, tick))
3803 		SCX_CALL_OP_TASK(sch, tick, rq, curr);
3804 
3805 	if (!curr->scx.slice)
3806 		resched_curr(rq);
3807 }
3808 
3809 #ifdef CONFIG_EXT_GROUP_SCHED
tg_cgrp(struct task_group * tg)3810 static struct cgroup *tg_cgrp(struct task_group *tg)
3811 {
3812 	/*
3813 	 * If CGROUP_SCHED is disabled, @tg is NULL. If @tg is an autogroup,
3814 	 * @tg->css.cgroup is NULL. In both cases, @tg can be treated as the
3815 	 * root cgroup.
3816 	 */
3817 	if (tg && tg->css.cgroup)
3818 		return tg->css.cgroup;
3819 	else
3820 		return &cgrp_dfl_root.cgrp;
3821 }
3822 
3823 #define SCX_INIT_TASK_ARGS_CGROUP(cgrp)		.cgroup = (cgrp),
3824 
3825 #else	/* CONFIG_EXT_GROUP_SCHED */
3826 
3827 #define SCX_INIT_TASK_ARGS_CGROUP(cgrp)
3828 
3829 #endif	/* CONFIG_EXT_GROUP_SCHED */
3830 
3831 /**
3832  * __scx_init_task - Initialize a task for a sched
3833  * @sch: sched to initialize @p for
3834  * @p: task of interest
3835  * @cgrp: cgroup @p is joining, %NULL for @p's current task_group's cgroup
3836  * @fork: %true if @p is being forked
3837  *
3838  * Pre-commit cgroup migration passes @cgrp explicitly as @p's task_group
3839  * still reflects the source.
3840  *
3841  * Return 0 on success, -errno on failure.
3842  */
__scx_init_task(struct scx_sched * sch,struct task_struct * p,struct cgroup * cgrp,bool fork)3843 int __scx_init_task(struct scx_sched *sch, struct task_struct *p,
3844 		    struct cgroup *cgrp, bool fork)
3845 {
3846 	int ret;
3847 
3848 	p->scx.disallow = false;
3849 
3850 	if (SCX_HAS_OP(sch, init_task)) {
3851 		struct scx_init_task_args args = {
3852 			SCX_INIT_TASK_ARGS_CGROUP(cgrp ?: tg_cgrp(task_group(p)))
3853 			.fork = fork,
3854 		};
3855 
3856 		ret = SCX_CALL_OP_RET(sch, init_task, NULL, p, &args);
3857 		if (unlikely(ret)) {
3858 			ret = scx_ops_sanitize_err(sch, "init_task", ret);
3859 			return ret;
3860 		}
3861 	}
3862 
3863 	if (p->scx.disallow) {
3864 		if (unlikely(scx_parent(sch))) {
3865 			scx_error(sch, "non-root ops.init_task() set task->scx.disallow for %s[%d]",
3866 				  p->comm, p->pid);
3867 		} else if (unlikely(fork)) {
3868 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] during fork",
3869 				  p->comm, p->pid);
3870 		} else if (unlikely(scx_enable_state() != SCX_ENABLING)) {
3871 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] outside the enable path",
3872 				  p->comm, p->pid);
3873 		} else {
3874 			struct rq *rq;
3875 			struct rq_flags rf;
3876 
3877 			rq = task_rq_lock(p, &rf);
3878 
3879 			/*
3880 			 * We're in the load path and @p->policy will be applied
3881 			 * right after. Reverting @p->policy here and rejecting
3882 			 * %SCHED_EXT transitions from scx_check_setscheduler()
3883 			 * guarantees that if ops.init_task() sets @p->disallow,
3884 			 * @p can never be in SCX.
3885 			 */
3886 			if (p->policy == SCHED_EXT) {
3887 				p->policy = SCHED_NORMAL;
3888 				atomic_long_inc(&scx_nr_rejected);
3889 			}
3890 
3891 			task_rq_unlock(rq, p, &rf);
3892 		}
3893 	}
3894 
3895 	return 0;
3896 }
3897 
__scx_enable_task(struct scx_sched * sch,struct task_struct * p)3898 static void __scx_enable_task(struct scx_sched *sch, struct task_struct *p)
3899 {
3900 	struct rq *rq = task_rq(p);
3901 	u32 weight;
3902 
3903 	lockdep_assert_rq_held(rq);
3904 
3905 	/*
3906 	 * Verify the task is not in BPF scheduler's custody. If flag
3907 	 * transitions are consistent, the flag should always be clear
3908 	 * here.
3909 	 */
3910 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_IN_CUSTODY);
3911 
3912 	/*
3913 	 * Set the weight before calling ops.enable() so that the scheduler
3914 	 * doesn't see a stale value if they inspect the task struct.
3915 	 */
3916 	if (task_has_idle_policy(p))
3917 		weight = WEIGHT_IDLEPRIO;
3918 	else
3919 		weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO];
3920 
3921 	p->scx.weight = sched_weight_to_cgroup(weight);
3922 
3923 	if (SCX_HAS_OP(sch, enable))
3924 		SCX_CALL_OP_TASK(sch, enable, rq, p);
3925 
3926 	if (SCX_HAS_OP(sch, set_weight))
3927 		SCX_CALL_OP_TASK(sch, set_weight, rq, p, p->scx.weight);
3928 }
3929 
scx_enable_task(struct scx_sched * sch,struct task_struct * p)3930 void scx_enable_task(struct scx_sched *sch, struct task_struct *p)
3931 {
3932 	__scx_enable_task(sch, p);
3933 	scx_set_task_state(p, SCX_TASK_ENABLED);
3934 }
3935 
scx_disable_task(struct scx_sched * sch,struct task_struct * p)3936 static void scx_disable_task(struct scx_sched *sch, struct task_struct *p)
3937 {
3938 	struct rq *rq = task_rq(p);
3939 
3940 	lockdep_assert_rq_held(rq);
3941 	WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED);
3942 
3943 	clear_direct_dispatch(p);
3944 
3945 	if (SCX_HAS_OP(sch, disable))
3946 		SCX_CALL_OP_TASK(sch, disable, rq, p);
3947 	scx_set_task_state(p, SCX_TASK_READY);
3948 
3949 	/*
3950 	 * Reset the SCX-managed fields when @p leaves the BPF scheduler's
3951 	 * control, after ops.disable() has observed their final values.
3952 	 */
3953 	p->scx.dsq_vtime = 0;
3954 	scx_task_slice_ended(rq, p);
3955 	scx_set_task_slice(p, 0);
3956 	p->scx.reenq_cnt = 0;
3957 
3958 	/*
3959 	 * Verify the task is not in BPF scheduler's custody. If flag
3960 	 * transitions are consistent, the flag should always be clear
3961 	 * here.
3962 	 */
3963 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_IN_CUSTODY);
3964 }
3965 
__scx_disable_and_exit_task(struct scx_sched * sch,struct task_struct * p)3966 void __scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p)
3967 {
3968 	struct scx_exit_task_args args = {
3969 		.cancelled = false,
3970 	};
3971 
3972 	lockdep_assert_held(&p->pi_lock);
3973 	lockdep_assert_rq_held(task_rq(p));
3974 
3975 	switch (scx_get_task_state(p)) {
3976 	case SCX_TASK_NONE:
3977 		return;
3978 	case SCX_TASK_INIT:
3979 		args.cancelled = true;
3980 		break;
3981 	case SCX_TASK_READY:
3982 		break;
3983 	case SCX_TASK_ENABLED:
3984 		scx_disable_task(sch, p);
3985 		break;
3986 	default:
3987 		WARN_ON_ONCE(true);
3988 		return;
3989 	}
3990 
3991 	if (SCX_HAS_OP(sch, exit_task))
3992 		SCX_CALL_OP_TASK(sch, exit_task, task_rq(p), p, &args);
3993 }
3994 
3995 /*
3996  * Undo a completed __scx_init_task(sch, p, false) when scx_enable_task() never
3997  * ran. The task state has not been transitioned, so this mirrors the
3998  * SCX_TASK_INIT branch in __scx_disable_and_exit_task().
3999  */
scx_sub_init_cancel_task(struct scx_sched * sch,struct task_struct * p)4000 void scx_sub_init_cancel_task(struct scx_sched *sch, struct task_struct *p)
4001 {
4002 	struct scx_exit_task_args args = { .cancelled = true };
4003 
4004 	lockdep_assert_held(&p->pi_lock);
4005 	lockdep_assert_rq_held(task_rq(p));
4006 
4007 	/* @p was never associated with @sch, dispatch on the explicit @sch */
4008 	if (SCX_HAS_OP(sch, exit_task))
4009 		__SCX_CALL_OP_TASK(sch, ops, exit_task, task_rq(p), p, &args);
4010 }
4011 
scx_disable_and_exit_task(struct scx_sched * sch,struct task_struct * p)4012 void scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p)
4013 {
4014 	__scx_disable_and_exit_task(sch, p);
4015 
4016 	/*
4017 	 * If set, @p exited between __scx_init_task() and scx_enable_task() in
4018 	 * scx_sub_enable() and is initialized for both the associated sched and
4019 	 * its parent. Exit for the child too - scx_enable_task() never ran for
4020 	 * it, so undo only init_task. The flag is only set on the sub-enable
4021 	 * path, so it's always clear when @p arrives here in %SCX_TASK_NONE.
4022 	 */
4023 	if (p->scx.flags & SCX_TASK_SUB_INIT) {
4024 		if (!WARN_ON_ONCE(!scx_enabling_sub_sched))
4025 			scx_sub_init_cancel_task(scx_enabling_sub_sched, p);
4026 		p->scx.flags &= ~SCX_TASK_SUB_INIT;
4027 	}
4028 
4029 	scx_set_task_sched(p, NULL);
4030 	scx_set_task_state(p, SCX_TASK_NONE);
4031 }
4032 
init_scx_entity(struct sched_ext_entity * scx)4033 void init_scx_entity(struct sched_ext_entity *scx)
4034 {
4035 	memset(scx, 0, sizeof(*scx));
4036 	INIT_LIST_HEAD(&scx->dsq_list.node);
4037 	RB_CLEAR_NODE(&scx->dsq_priq);
4038 	scx->sticky_cpu = -1;
4039 	scx->holding_cpu = -1;
4040 	scx->runnable_cpu = -1;
4041 	INIT_LIST_HEAD(&scx->runnable_node);
4042 	scx->runnable_at = jiffies;
4043 	scx->ddsp_dsq_id = SCX_DSQ_INVALID;
4044 	scx->slice = SCX_SLICE_DFL;
4045 }
4046 
4047 /* See scx_tid_alloc / scx_tid_cursor. */
scx_alloc_tid(void)4048 static u64 scx_alloc_tid(void)
4049 {
4050 	struct scx_tid_alloc *ta;
4051 
4052 	guard(preempt)();
4053 	ta = this_cpu_ptr(&scx_tid_alloc);
4054 
4055 	if (unlikely(ta->next >= ta->end)) {
4056 		ta->next = atomic64_fetch_add(SCX_TID_CHUNK, &scx_tid_cursor);
4057 		ta->end = ta->next + SCX_TID_CHUNK;
4058 	}
4059 	return ta->next++;
4060 }
4061 
scx_tid_hash_insert(struct task_struct * p)4062 static void scx_tid_hash_insert(struct task_struct *p)
4063 {
4064 	int ret;
4065 
4066 	lockdep_assert_held(&scx_tasks_lock);
4067 
4068 	ret = rhashtable_lookup_insert_fast(&scx_tid_hash,
4069 					    &p->scx.tid_hash_node,
4070 					    scx_tid_hash_params);
4071 	WARN_ON_ONCE(ret);
4072 }
4073 
scx_pre_fork(struct task_struct * p)4074 void scx_pre_fork(struct task_struct *p)
4075 {
4076 	/*
4077 	 * BPF scheduler enable/disable paths want to be able to iterate and
4078 	 * update all tasks which can become complex when racing forks. As
4079 	 * enable/disable are very cold paths, let's use a percpu_rwsem to
4080 	 * exclude forks.
4081 	 */
4082 	percpu_down_read(&scx_fork_rwsem);
4083 }
4084 
scx_fork(struct task_struct * p,struct kernel_clone_args * kargs)4085 int scx_fork(struct task_struct *p, struct kernel_clone_args *kargs)
4086 {
4087 	s32 ret;
4088 
4089 	percpu_rwsem_assert_held(&scx_fork_rwsem);
4090 
4091 	p->scx.tid = scx_alloc_tid();
4092 
4093 	if (scx_init_task_enabled) {
4094 #ifdef CONFIG_EXT_SUB_SCHED
4095 		struct scx_sched *sch = scx_cgroup_sched(kargs->cset->dfl_cgrp);
4096 #else
4097 		struct scx_sched *sch = scx_root_protected_live();
4098 #endif
4099 		scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
4100 		ret = __scx_init_task(sch, p, NULL, true);
4101 		if (unlikely(ret)) {
4102 			scx_set_task_state(p, SCX_TASK_NONE);
4103 			return ret;
4104 		}
4105 		scx_set_task_state(p, SCX_TASK_INIT);
4106 		scx_set_task_sched(p, sch);
4107 	}
4108 
4109 	return 0;
4110 }
4111 
scx_post_fork(struct task_struct * p)4112 void scx_post_fork(struct task_struct *p)
4113 {
4114 	if (scx_init_task_enabled) {
4115 		scx_set_task_state(p, SCX_TASK_READY);
4116 
4117 		/*
4118 		 * Enable the task immediately if it's running on sched_ext.
4119 		 * Otherwise, it'll be enabled in switching_to_scx() if and
4120 		 * when it's ever configured to run with a SCHED_EXT policy.
4121 		 */
4122 		if (p->sched_class == &ext_sched_class) {
4123 			struct rq_flags rf;
4124 			struct rq *rq;
4125 
4126 			rq = task_rq_lock(p, &rf);
4127 			scx_enable_task(scx_task_sched(p), p);
4128 			task_rq_unlock(rq, p, &rf);
4129 		}
4130 	}
4131 
4132 	scoped_guard(raw_spinlock_irq, &scx_tasks_lock) {
4133 		list_add_tail(&p->scx.tasks_node, &scx_tasks);
4134 		if (scx_tid_to_task_enabled())
4135 			scx_tid_hash_insert(p);
4136 	}
4137 
4138 	percpu_up_read(&scx_fork_rwsem);
4139 }
4140 
scx_cancel_fork(struct task_struct * p)4141 void scx_cancel_fork(struct task_struct *p)
4142 {
4143 	if (scx_init_task_enabled) {
4144 		struct rq *rq;
4145 		struct rq_flags rf;
4146 
4147 		rq = task_rq_lock(p, &rf);
4148 		WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY);
4149 		scx_disable_and_exit_task(scx_task_sched(p), p);
4150 		task_rq_unlock(rq, p, &rf);
4151 	}
4152 
4153 	percpu_up_read(&scx_fork_rwsem);
4154 }
4155 
4156 /**
4157  * task_dead_and_done - Is a task dead and done running?
4158  * @p: target task
4159  *
4160  * Once sched_ext_dead() removes the dead task from scx_tasks and exits it, the
4161  * task no longer exists from SCX's POV. However, certain sched_class ops may be
4162  * invoked on these dead tasks leading to failures - e.g. sched_setscheduler()
4163  * may try to switch a task which finished sched_ext_dead() back into SCX
4164  * triggering invalid SCX task state transitions and worse.
4165  *
4166  * Once a task has finished the final switch, sched_ext_dead() is the only thing
4167  * that needs to happen on the task. Use this test to short-circuit sched_class
4168  * operations which may be called on dead tasks.
4169  */
task_dead_and_done(struct task_struct * p)4170 static bool task_dead_and_done(struct task_struct *p)
4171 {
4172 	struct rq *rq = task_rq(p);
4173 
4174 	lockdep_assert_rq_held(rq);
4175 
4176 	/*
4177 	 * In do_task_dead(), a dying task sets %TASK_DEAD with preemption
4178 	 * disabled and __schedule(). If @p has %TASK_DEAD set and off CPU, @p
4179 	 * won't ever run again.
4180 	 */
4181 	return unlikely(READ_ONCE(p->__state) == TASK_DEAD) &&
4182 		!task_on_cpu(rq, p);
4183 }
4184 
sched_ext_dead(struct task_struct * p)4185 void sched_ext_dead(struct task_struct *p)
4186 {
4187 	/*
4188 	 * By the time control reaches here, @p has %TASK_DEAD set, switched out
4189 	 * for the last time and then dropped the rq lock - task_dead_and_done()
4190 	 * should be returning %true nullifying the straggling sched_class ops.
4191 	 * Remove from scx_tasks and exit @p.
4192 	 */
4193 	scoped_guard(raw_spinlock_irqsave, &scx_tasks_lock) {
4194 		list_del_init(&p->scx.tasks_node);
4195 		if (scx_tid_to_task_enabled())
4196 			rhashtable_remove_fast(&scx_tid_hash,
4197 					       &p->scx.tid_hash_node,
4198 					       scx_tid_hash_params);
4199 	}
4200 
4201 	/*
4202 	 * @p is off scx_tasks and wholly ours. scx_root_enable()'s READY ->
4203 	 * ENABLED transitions can't race us. Disable ops for @p.
4204 	 *
4205 	 * %SCX_TASK_DEAD synchronizes against cgroup task iteration - see
4206 	 * scx_task_iter_next_locked(). NONE tasks need no marking: cgroup
4207 	 * iteration is only used from sub-sched paths, which require root
4208 	 * enabled. Root enable transitions every live task to at least READY.
4209 	 *
4210 	 * %INIT_BEGIN means ops.init_task() is running for @p. Don't call
4211 	 * into ops; transition to %DEAD so the post-init recheck unwinds
4212 	 * via scx_sub_init_cancel_task().
4213 	 */
4214 	if (scx_get_task_state(p) != SCX_TASK_NONE) {
4215 		struct rq_flags rf;
4216 		struct rq *rq;
4217 
4218 		rq = task_rq_lock(p, &rf);
4219 		if (scx_get_task_state(p) != SCX_TASK_INIT_BEGIN)
4220 			scx_disable_and_exit_task(scx_task_sched(p), p);
4221 		scx_set_task_state(p, SCX_TASK_DEAD);
4222 		task_rq_unlock(rq, p, &rf);
4223 	}
4224 }
4225 
reweight_task_scx(struct rq * rq,struct task_struct * p,const struct load_weight * lw)4226 static void reweight_task_scx(struct rq *rq, struct task_struct *p,
4227 			      const struct load_weight *lw)
4228 {
4229 	struct scx_sched *sch = scx_task_sched(p);
4230 
4231 	lockdep_assert_rq_held(task_rq(p));
4232 
4233 	if (task_dead_and_done(p))
4234 		return;
4235 
4236 	/*
4237 	 * When switching sched_class away from SCX, reweight_task_scx()
4238 	 * is called _after_ scx_disable_task(). Skip calling ops.set_weight()
4239 	 * since the BPF scheduler may have already forgotten the task in
4240 	 * ops.disable().
4241 	 * p->scx.weight will be recalculated in scx_enable_task() if the task
4242 	 * ever returns to SCX class.
4243 	 */
4244 	if (scx_get_task_state(p) != SCX_TASK_ENABLED)
4245 		return;
4246 
4247 	p->scx.weight = sched_weight_to_cgroup(scale_load_down(lw->weight));
4248 	if (SCX_HAS_OP(sch, set_weight))
4249 		SCX_CALL_OP_TASK(sch, set_weight, rq, p, p->scx.weight);
4250 }
4251 
prio_changed_scx(struct rq * rq,struct task_struct * p,u64 oldprio)4252 static void prio_changed_scx(struct rq *rq, struct task_struct *p, u64 oldprio)
4253 {
4254 }
4255 
switching_to_scx(struct rq * rq,struct task_struct * p)4256 static void switching_to_scx(struct rq *rq, struct task_struct *p)
4257 {
4258 	struct scx_sched *sch = scx_task_sched(p);
4259 
4260 	if (task_dead_and_done(p))
4261 		return;
4262 
4263 	scx_enable_task(sch, p);
4264 
4265 	/*
4266 	 * set_cpus_allowed_scx() is not called while @p is associated with a
4267 	 * different scheduler class. Keep the BPF scheduler up-to-date.
4268 	 */
4269 	if (SCX_HAS_OP(sch, set_cpumask))
4270 		scx_call_op_set_cpumask(sch, rq, p, (struct cpumask *)p->cpus_ptr);
4271 }
4272 
switched_from_scx(struct rq * rq,struct task_struct * p)4273 static void switched_from_scx(struct rq *rq, struct task_struct *p)
4274 {
4275 	if (task_dead_and_done(p))
4276 		return;
4277 
4278 	/*
4279 	 * %NONE means SCX is no longer tracking @p at the task level (e.g.
4280 	 * scx_fail_parent() handed @p back to the parent at NONE pending the
4281 	 * parent's own teardown). There is nothing to disable; calling
4282 	 * scx_disable_task() would WARN on the non-%ENABLED state and trigger a
4283 	 * NONE -> READY validation failure.
4284 	 */
4285 	if (scx_get_task_state(p) == SCX_TASK_NONE)
4286 		return;
4287 
4288 	scx_disable_task(scx_task_sched(p), p);
4289 }
4290 
switched_to_scx(struct rq * rq,struct task_struct * p)4291 static void switched_to_scx(struct rq *rq, struct task_struct *p) {}
4292 
scx_check_setscheduler(struct task_struct * p,int policy)4293 int scx_check_setscheduler(struct task_struct *p, int policy)
4294 {
4295 	lockdep_assert_rq_held(task_rq(p));
4296 
4297 	/* if disallow, reject transitioning into SCX */
4298 	if (scx_enabled() && READ_ONCE(p->scx.disallow) &&
4299 	    p->policy != policy && policy == SCHED_EXT)
4300 		return -EACCES;
4301 
4302 	return 0;
4303 }
4304 
process_ddsp_deferred_locals(struct rq * rq)4305 static void process_ddsp_deferred_locals(struct rq *rq)
4306 {
4307 	struct task_struct *p;
4308 
4309 	lockdep_assert_rq_held(rq);
4310 
4311 	/*
4312 	 * Now that @rq can be unlocked, execute the deferred enqueueing of
4313 	 * tasks directly dispatched to the local DSQs of other CPUs. See
4314 	 * direct_dispatch(). Keep popping from the head instead of using
4315 	 * list_for_each_entry_safe() as dispatch_local_dsq() may unlock @rq
4316 	 * temporarily.
4317 	 */
4318 	while ((p = list_first_entry_or_null(&rq->scx.ddsp_deferred_locals,
4319 				struct task_struct, scx.dsq_list.node))) {
4320 		struct scx_sched *sch = scx_task_sched(p);
4321 		struct scx_dispatch_q *dsq;
4322 		u64 dsq_id = p->scx.ddsp_dsq_id;
4323 		u64 enq_flags = p->scx.ddsp_enq_flags;
4324 		u64 slice = p->scx.ddsp_slice;
4325 		u64 vtime = p->scx.ddsp_vtime;
4326 
4327 		list_del_init(&p->scx.dsq_list.node);
4328 		clear_direct_dispatch(p);
4329 
4330 		dsq = find_dsq_for_dispatch(sch, rq, dsq_id, task_cpu(p));
4331 		if (!WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL))
4332 			dispatch_to_local_dsq(sch, rq, dsq, p, slice, vtime, enq_flags);
4333 	}
4334 }
4335 
4336 /*
4337  * Determine whether @p should be reenqueued from a local DSQ.
4338  *
4339  * @reenq_flags is mutable and accumulates state across the DSQ walk:
4340  *
4341  * - %SCX_REENQ_TSR_NOT_FIRST: Set after the first task is visited. "First"
4342  *   tracks position in the DSQ list, not among IMMED tasks. A non-IMMED task at
4343  *   the head consumes the first slot.
4344  *
4345  * - %SCX_REENQ_TSR_RQ_OPEN: Set by reenq_local() before the walk if
4346  *   rq_is_open() is true.
4347  *
4348  * An IMMED task is kept (returns %false) only if it's the first task in the DSQ
4349  * AND the current task is done — i.e. it will execute immediately. All other
4350  * IMMED tasks are reenqueued. This means if a non-IMMED task sits at the head,
4351  * every IMMED task behind it gets reenqueued.
4352  *
4353  * Reenqueued tasks go through ops.enqueue() with %SCX_ENQ_REENQ |
4354  * %SCX_TASK_REENQ_IMMED. If the BPF scheduler dispatches back to the same local
4355  * DSQ with %SCX_ENQ_IMMED while the CPU is still unavailable, this triggers
4356  * another reenq cycle. Repetitions are bounded by %SCX_REENQ_MAX_REPEAT in
4357  * scx_do_enqueue_task(), which ejects the task's owning scheduler.
4358  */
local_task_should_reenq(struct rq * rq,struct task_struct * p,u64 * reenq_flags,u32 * reason)4359 static bool local_task_should_reenq(struct rq *rq, struct task_struct *p,
4360 				    u64 *reenq_flags, u32 *reason)
4361 {
4362 	bool first;
4363 
4364 	first = !(*reenq_flags & SCX_REENQ_TSR_NOT_FIRST);
4365 	*reenq_flags |= SCX_REENQ_TSR_NOT_FIRST;
4366 
4367 	if (unlikely((p->scx.flags & SCX_TASK_PROTECTED) || p == scx_rescuee(rq)))
4368 		return false;
4369 
4370 	*reason = SCX_TASK_REENQ_KFUNC;
4371 
4372 	if ((p->scx.flags & SCX_TASK_IMMED) &&
4373 	    (!first || !(*reenq_flags & SCX_REENQ_TSR_RQ_OPEN))) {
4374 		__scx_add_event(scx_task_sched(p), SCX_EV_REENQ_IMMED, 1);
4375 		*reason = SCX_TASK_REENQ_IMMED;
4376 		return true;
4377 	}
4378 
4379 	if ((*reenq_flags & SCX_REENQ_CAP_REVOKE) &&
4380 	    scx_task_reenq_on_cap_revoke(rq, p)) {
4381 		*reason = SCX_TASK_REENQ_CAP;
4382 		return true;
4383 	}
4384 
4385 	return *reenq_flags & SCX_REENQ_ANY;
4386 }
4387 
reenq_local(struct scx_sched * sch,struct rq * rq,u64 reenq_flags)4388 static u32 reenq_local(struct scx_sched *sch, struct rq *rq, u64 reenq_flags)
4389 {
4390 	LIST_HEAD(tasks);
4391 	u32 nr_enqueued = 0;
4392 	struct task_struct *p, *n;
4393 
4394 	lockdep_assert_rq_held(rq);
4395 
4396 	if (WARN_ON_ONCE(reenq_flags & __SCX_REENQ_TSR_MASK))
4397 		reenq_flags &= ~__SCX_REENQ_TSR_MASK;
4398 	if (rq_is_open(rq, 0))
4399 		reenq_flags |= SCX_REENQ_TSR_RQ_OPEN;
4400 
4401 	/*
4402 	 * The BPF scheduler may choose to dispatch tasks back to
4403 	 * @rq->scx.local_dsq. Move all candidate tasks off to a private list
4404 	 * first to avoid processing the same tasks repeatedly.
4405 	 */
4406 	list_for_each_entry_safe(p, n, &rq->scx.local_dsq.list,
4407 				 scx.dsq_list.node) {
4408 		struct scx_sched *task_sch = scx_task_sched(p);
4409 		u32 reason;
4410 
4411 		/*
4412 		 * If @p is being migrated, @p's current CPU may not agree with
4413 		 * its allowed CPUs and the migration_cpu_stop is about to
4414 		 * deactivate and re-activate @p anyway. Skip re-enqueueing.
4415 		 *
4416 		 * While racing sched property changes may also dequeue and
4417 		 * re-enqueue a migrating task while its current CPU and allowed
4418 		 * CPUs disagree, they use %ENQUEUE_RESTORE which is bypassed to
4419 		 * the current local DSQ for running tasks and thus are not
4420 		 * visible to the BPF scheduler.
4421 		 */
4422 		if (p->migration_pending)
4423 			continue;
4424 
4425 		if (!scx_is_descendant(task_sch, sch))
4426 			continue;
4427 
4428 		if (!local_task_should_reenq(rq, p, &reenq_flags, &reason))
4429 			continue;
4430 
4431 		scx_dispatch_dequeue(rq, p);
4432 
4433 		if (WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK))
4434 			p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
4435 		p->scx.flags |= reason;
4436 
4437 		list_add_tail(&p->scx.dsq_list.node, &tasks);
4438 	}
4439 
4440 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
4441 		list_del_init(&p->scx.dsq_list.node);
4442 
4443 		scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
4444 
4445 		p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
4446 		nr_enqueued++;
4447 	}
4448 
4449 	/*
4450 	 * The revoke that scheduled this scan may have raced the pick: curr
4451 	 * may be a now-capless task, either one that kept running or one
4452 	 * promoted off the local DSQ between the ecaps sync and this scan.
4453 	 * Zero the slice to evict it. The enqueue gate blocks new capless
4454 	 * inserts, so no later pick can slip through after the scan.
4455 	 */
4456 	if ((reenq_flags & SCX_REENQ_CAP_REVOKE) &&
4457 	    rq->curr->sched_class == &ext_sched_class &&
4458 	    scx_task_reenq_on_cap_revoke(rq, rq->curr)) {
4459 		scx_set_task_slice(rq->curr, 0);
4460 		resched_curr(rq);
4461 	}
4462 
4463 	return nr_enqueued;
4464 }
4465 
process_deferred_reenq_locals(struct rq * rq)4466 static void process_deferred_reenq_locals(struct rq *rq)
4467 {
4468 	lockdep_assert_rq_held(rq);
4469 
4470 	/*
4471 	 * A task can be re-queued within this loop when a reenqueued task
4472 	 * bounces straight back to the local DSQ. That recursion is bounded by
4473 	 * the per-task reenqueue cap in scx_do_enqueue_task().
4474 	 */
4475 	while (true) {
4476 		struct scx_sched *sch;
4477 		u64 reenq_flags;
4478 
4479 		scoped_guard (raw_spinlock, &rq->scx.deferred_reenq_lock) {
4480 			struct scx_deferred_reenq_local *drl =
4481 				list_first_entry_or_null(&rq->scx.deferred_reenq_locals,
4482 							 struct scx_deferred_reenq_local,
4483 							 node);
4484 			struct scx_sched_pcpu *sch_pcpu;
4485 
4486 			if (!drl)
4487 				return;
4488 
4489 			sch_pcpu = container_of(drl, struct scx_sched_pcpu,
4490 						deferred_reenq_local);
4491 			sch = sch_pcpu->sch;
4492 
4493 			reenq_flags = drl->flags;
4494 			WRITE_ONCE(drl->flags, 0);
4495 			list_del_init(&drl->node);
4496 		}
4497 
4498 		/* see schedule_dsq_reenq() */
4499 		smp_mb();
4500 
4501 		reenq_local(sch, rq, reenq_flags);
4502 	}
4503 }
4504 
user_task_should_reenq(struct task_struct * p,u64 reenq_flags,u32 * reason)4505 static bool user_task_should_reenq(struct task_struct *p, u64 reenq_flags, u32 *reason)
4506 {
4507 	*reason = SCX_TASK_REENQ_KFUNC;
4508 	return reenq_flags & SCX_REENQ_ANY;
4509 }
4510 
reenq_user(struct rq * rq,struct scx_dispatch_q * dsq,u64 reenq_flags)4511 static void reenq_user(struct rq *rq, struct scx_dispatch_q *dsq, u64 reenq_flags)
4512 {
4513 	struct rq *locked_rq = rq;
4514 	struct scx_sched *sch = dsq->sched;
4515 	struct scx_dsq_list_node cursor = INIT_DSQ_LIST_CURSOR(cursor, dsq, 0);
4516 	struct task_struct *p;
4517 	s32 nr_enqueued = 0;
4518 
4519 	lockdep_assert_rq_held(rq);
4520 
4521 	raw_spin_lock(&dsq->lock);
4522 
4523 	while (likely(!READ_ONCE(sch->bypass_depth))) {
4524 		struct rq *task_rq;
4525 		u32 reason;
4526 
4527 		p = nldsq_cursor_next_task(&cursor, dsq);
4528 		if (!p)
4529 			break;
4530 
4531 		if (!user_task_should_reenq(p, reenq_flags, &reason))
4532 			continue;
4533 
4534 		task_rq = task_rq(p);
4535 
4536 		if (locked_rq != task_rq) {
4537 			if (locked_rq) {
4538 				scx_rq_lock_drop(locked_rq);
4539 				raw_spin_rq_unlock(locked_rq);
4540 			}
4541 			if (unlikely(!raw_spin_rq_trylock(task_rq))) {
4542 				raw_spin_unlock(&dsq->lock);
4543 				raw_spin_rq_lock(task_rq);
4544 				raw_spin_lock(&dsq->lock);
4545 			}
4546 			locked_rq = task_rq;
4547 
4548 			/* did we lose @p while switching locks? */
4549 			if (nldsq_cursor_lost_task(&cursor, task_rq, dsq, p))
4550 				continue;
4551 		}
4552 
4553 		/* @p is on @dsq, its rq and @dsq are locked */
4554 		dispatch_dequeue_locked(p, dsq);
4555 		raw_spin_unlock(&dsq->lock);
4556 
4557 		if (WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK))
4558 			p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
4559 		p->scx.flags |= reason;
4560 
4561 		scx_do_enqueue_task(task_rq, p, SCX_ENQ_REENQ, -1);
4562 
4563 		p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
4564 
4565 		if (!(++nr_enqueued % SCX_TASK_ITER_BATCH)) {
4566 			scx_rq_lock_drop(locked_rq);
4567 			raw_spin_rq_unlock(locked_rq);
4568 			locked_rq = NULL;
4569 			cpu_relax();
4570 		}
4571 
4572 		raw_spin_lock(&dsq->lock);
4573 	}
4574 
4575 	list_del_init(&cursor.node);
4576 	raw_spin_unlock(&dsq->lock);
4577 
4578 	if (locked_rq != rq) {
4579 		if (locked_rq) {
4580 			scx_rq_lock_drop(locked_rq);
4581 			raw_spin_rq_unlock(locked_rq);
4582 		}
4583 		raw_spin_rq_lock(rq);
4584 	}
4585 }
4586 
process_deferred_reenq_users(struct rq * rq)4587 static void process_deferred_reenq_users(struct rq *rq)
4588 {
4589 	lockdep_assert_rq_held(rq);
4590 
4591 	while (true) {
4592 		struct scx_dispatch_q *dsq;
4593 		u64 dsq_id, reenq_flags;
4594 
4595 		scoped_guard (raw_spinlock, &rq->scx.deferred_reenq_lock) {
4596 			struct scx_deferred_reenq_user *dru =
4597 				list_first_entry_or_null(&rq->scx.deferred_reenq_users,
4598 							 struct scx_deferred_reenq_user,
4599 							 node);
4600 			struct scx_dsq_pcpu *dsq_pcpu;
4601 
4602 			if (!dru)
4603 				return;
4604 
4605 			dsq_pcpu = container_of(dru, struct scx_dsq_pcpu,
4606 						deferred_reenq_user);
4607 			dsq = dsq_pcpu->dsq;
4608 			reenq_flags = dru->flags;
4609 			WRITE_ONCE(dru->flags, 0);
4610 			list_del_init(&dru->node);
4611 		}
4612 
4613 		/* see schedule_dsq_reenq() */
4614 		smp_mb();
4615 
4616 		/* destroy_dsq() may have raced and invalidated @dsq, nothing to reenq */
4617 		dsq_id = READ_ONCE(dsq->id);
4618 		if (unlikely(dsq_id == SCX_DSQ_INVALID))
4619 			continue;
4620 
4621 		BUG_ON(dsq_id & SCX_DSQ_FLAG_BUILTIN);
4622 		reenq_user(rq, dsq, reenq_flags);
4623 	}
4624 }
4625 
run_deferred(struct rq * rq)4626 static void run_deferred(struct rq *rq)
4627 {
4628 	process_ddsp_deferred_locals(rq);
4629 
4630 	if (!list_empty(&rq->scx.deferred_reenq_locals))
4631 		process_deferred_reenq_locals(rq);
4632 
4633 	if (!list_empty(&rq->scx.deferred_reenq_users))
4634 		process_deferred_reenq_users(rq);
4635 
4636 	scx_reenq_reject(rq);
4637 }
4638 
4639 #ifdef CONFIG_NO_HZ_FULL
scx_can_stop_tick(struct rq * rq)4640 bool scx_can_stop_tick(struct rq *rq)
4641 {
4642 	struct task_struct *p = rq->curr;
4643 	struct scx_sched *sch = scx_task_sched(p);
4644 
4645 	if (p->sched_class != &ext_sched_class)
4646 		return true;
4647 
4648 	/*
4649 	 * @rq->curr may still reference an outgoing EXT task after it has been
4650 	 * dequeued. If no EXT tasks are accounted on @rq, ignore its stale
4651 	 * slice state. If another task is dispatched from a DSQ,
4652 	 * set_next_task_scx() will update the dependency for the incoming task.
4653 	 */
4654 	if (!rq->scx.nr_running)
4655 		return true;
4656 
4657 	if (scx_bypassing(sch, cpu_of(rq)))
4658 		return false;
4659 
4660 	/*
4661 	 * A running rescuee's charging and expiry are tick-driven, see
4662 	 * scx_rescue_charge(). Keep the tick while rescue is in progress.
4663 	 */
4664 	if (unlikely(p == scx_rescuee(rq)))
4665 		return false;
4666 
4667 	/*
4668 	 * @rq can dispatch from different DSQs, so we can't tell whether it
4669 	 * needs the tick or not by looking at nr_running. Allow stopping ticks
4670 	 * iff the BPF scheduler indicated so. See set_next_task_scx().
4671 	 */
4672 	return rq->scx.flags & SCX_RQ_CAN_STOP_TICK;
4673 }
4674 #endif
4675 
4676 #ifdef CONFIG_EXT_GROUP_SCHED
4677 
4678 DEFINE_STATIC_PERCPU_RWSEM(scx_cgroup_ops_rwsem);
4679 
scx_tg_init(struct task_group * tg)4680 void scx_tg_init(struct task_group *tg)
4681 {
4682 	tg->scx.weight = CGROUP_WEIGHT_DFL;
4683 	tg->scx.bw_period_us = default_bw_period_us();
4684 	tg->scx.bw_quota_us = RUNTIME_INF;
4685 	tg->scx.idle = false;
4686 }
4687 
4688 /**
4689  * scx_tg_sched - Resolve a task_group's sched
4690  * @tg: task_group of interest
4691  *
4692  * Return the sched that @tg's ops.cgroup_init() succeeded on, %NULL if @tg
4693  * isn't inited. An autogroup tg has no cgroup of its own and resolves to the
4694  * root sched.
4695  *
4696  * When a child sched exits, its task_groups are moved to the parent and
4697  * re-inited on it. A failed re-init fails the parent in turn and leaves the
4698  * task_group without a sched it's inited on, resolving to %NULL. See
4699  * scx_cgroup_return_subtree().
4700  *
4701  * Safe for callers read-locking the ops rwsem. tg->scx.sched rewrites
4702  * write-lock it, and tg on/offline can't overlap such callers as a css's files
4703  * are created after online and drained before offline.
4704  */
scx_tg_sched(struct task_group * tg)4705 static struct scx_sched *scx_tg_sched(struct task_group *tg)
4706 {
4707 	lockdep_assert(lockdep_is_held(&cgroup_mutex) ||
4708 		       lockdep_is_held(&scx_cgroup_ops_rwsem));
4709 
4710 	if (!tg->css.cgroup)
4711 		tg = &root_task_group;
4712 	/* INITED means ops.cgroup_init() succeeded on @tg->scx.sched */
4713 	return (tg->scx.flags & SCX_TG_INITED) ? tg->scx.sched : NULL;
4714 }
4715 
4716 /**
4717  * scx_tg_knob_sched - Resolve the sched receiving a task_group's knob updates
4718  * @tg: task_group of interest
4719  *
4720  * Knobs of a cgroup belong to the parent. Deliver the set_* ops to the
4721  * parent task_group's sched, which equals @tg's own sched everywhere except
4722  * at a sub-scheduler attach point, where the sub's parent sched receives
4723  * them.
4724  *
4725  * Return %NULL if the parent task_group has no sched. That can happen when the
4726  * parent's ops.cgroup_init() fails while a sub-scheduler is being disabled.
4727  *
4728  * The callers sit in @tg's cgroup file writes holding the ops rwsem read
4729  * side. That extends scx_tg_sched()'s file-write argument to the parent's
4730  * sched read: a parent css outlives its children's files.
4731  */
scx_tg_knob_sched(struct task_group * tg)4732 static struct scx_sched *scx_tg_knob_sched(struct task_group *tg)
4733 {
4734 	lockdep_assert(lockdep_is_held(&cgroup_mutex) ||
4735 		       lockdep_is_held(&scx_cgroup_ops_rwsem));
4736 
4737 	if (!tg->css.cgroup || !tg->css.parent)
4738 		return scx_tg_sched(&root_task_group);
4739 	return scx_tg_sched(css_tg(tg->css.parent));
4740 }
4741 
scx_tg_online(struct task_group * tg)4742 int scx_tg_online(struct task_group *tg)
4743 {
4744 	int ret = 0;
4745 
4746 	WARN_ON_ONCE(tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED));
4747 
4748 	if (scx_cgroup_enabled) {
4749 		struct scx_sched *sch;
4750 
4751 		/*
4752 		 * The cgroup lifetime notifier populates cgrp->scx_sched before
4753 		 * css_online, but only on the default hierarchy. Sub-scheds are
4754 		 * attached to the cgroup2 hierarchy, so a cgroup1 task_group
4755 		 * always belongs to the root sched.
4756 		 */
4757 		if (cgroup_on_dfl(tg->css.cgroup))
4758 			sch = scx_cgroup_sched(tg->css.cgroup);
4759 		else
4760 			sch = scx_tg_sched(&root_task_group);
4761 
4762 		if (SCX_HAS_OP(sch, cgroup_init)) {
4763 			struct scx_cgroup_init_args args =
4764 				{ .weight = tg->scx.weight,
4765 				  .bw_period_us = tg->scx.bw_period_us,
4766 				  .bw_quota_us = tg->scx.bw_quota_us,
4767 				  .bw_burst_us = tg->scx.bw_burst_us };
4768 
4769 			ret = SCX_CALL_OP_RET(sch, cgroup_init,
4770 					      NULL, tg->css.cgroup, &args);
4771 			if (ret)
4772 				ret = scx_ops_sanitize_err(sch, "cgroup_init", ret);
4773 		}
4774 		if (ret == 0) {
4775 			tg->scx.sched = sch;
4776 			tg->scx.flags |= SCX_TG_ONLINE | SCX_TG_INITED;
4777 		}
4778 	} else {
4779 		tg->scx.flags |= SCX_TG_ONLINE;
4780 	}
4781 
4782 	return ret;
4783 }
4784 
scx_tg_offline(struct task_group * tg)4785 void scx_tg_offline(struct task_group *tg)
4786 {
4787 	struct scx_sched *sch = tg->scx.sched;
4788 
4789 	WARN_ON_ONCE(!(tg->scx.flags & SCX_TG_ONLINE));
4790 
4791 	/* INITED implies non-NULL @sch, test before SCX_HAS_OP() derefs */
4792 	if (scx_cgroup_enabled && (tg->scx.flags & SCX_TG_INITED) &&
4793 	    SCX_HAS_OP(sch, cgroup_exit))
4794 		SCX_CALL_OP(sch, cgroup_exit, NULL, tg->css.cgroup);
4795 	tg->scx.sched = NULL;
4796 	tg->scx.flags &= ~(SCX_TG_ONLINE | SCX_TG_INITED);
4797 }
4798 
4799 /*
4800  * @p's sched for the cgroup migration paths. Stable as re-homes happen either
4801  * at CGROUP_TASK_MIGRATED of the same migration or under scx_cgroup_lock(),
4802  * both while holding cgroup_mutex.
4803  */
scx_cgroup_task_sched(struct task_struct * p)4804 static struct scx_sched *scx_cgroup_task_sched(struct task_struct *p)
4805 {
4806 	return rcu_dereference_protected(p->scx.sched, lockdep_is_held(&cgroup_mutex));
4807 }
4808 
scx_cgroup_can_attach(struct cgroup_taskset * tset)4809 int scx_cgroup_can_attach(struct cgroup_taskset *tset)
4810 {
4811 	struct cgroup_subsys_state *css;
4812 	struct task_struct *p;
4813 	int ret;
4814 
4815 	if (!scx_cgroup_enabled)
4816 		return 0;
4817 
4818 	cgroup_taskset_for_each(p, css, tset) {
4819 		struct scx_sched *sch = scx_cgroup_task_sched(p);
4820 		struct cgroup *from = tg_cgrp(task_group(p));
4821 		struct cgroup *to = tg_cgrp(css_tg(css));
4822 
4823 		WARN_ON_ONCE(p->scx.cgrp_moving_from);
4824 
4825 		/*
4826 		 * sched_move_task() omits identity migrations. Let's match the
4827 		 * behavior so that ops.cgroup_prep_move() and ops.cgroup_move()
4828 		 * always match one-to-one.
4829 		 */
4830 		if (from == to)
4831 			continue;
4832 
4833 		/*
4834 		 * The cgroup_move ops are delivered to @p's sched, and only for
4835 		 * moves that don't re-home @p. A re-homing move changes the dfl
4836 		 * cgroup's sched and is reported through the
4837 		 * exit_task/init_task pair that the re-homing generates.
4838 		 */
4839 		if (!sch || sch != scx_cgroup_sched(task_css_set(p)->mg_dst_cset->dfl_cgrp))
4840 			continue;
4841 
4842 		if (SCX_HAS_OP(sch, cgroup_prep_move)) {
4843 			ret = SCX_CALL_OP_RET(sch, cgroup_prep_move, NULL,
4844 					      p, from, css->cgroup);
4845 			if (ret) {
4846 				ret = scx_ops_sanitize_err(sch, "cgroup_prep_move", ret);
4847 				goto err;
4848 			}
4849 		}
4850 
4851 		p->scx.cgrp_moving_from = from;
4852 	}
4853 
4854 	return 0;
4855 
4856 err:
4857 	cgroup_taskset_for_each(p, css, tset) {
4858 		struct scx_sched *sch = scx_cgroup_task_sched(p);
4859 
4860 		/* cgrp_moving_from implies non-NULL @sch, test it first */
4861 		if (p->scx.cgrp_moving_from && SCX_HAS_OP(sch, cgroup_cancel_move))
4862 			SCX_CALL_OP(sch, cgroup_cancel_move, NULL,
4863 				    p, p->scx.cgrp_moving_from, css->cgroup);
4864 		p->scx.cgrp_moving_from = NULL;
4865 	}
4866 
4867 	return ret;
4868 }
4869 
scx_cgroup_move_task(struct task_struct * p)4870 void scx_cgroup_move_task(struct task_struct *p)
4871 {
4872 	struct scx_sched *sch;
4873 
4874 	if (!scx_cgroup_enabled)
4875 		return;
4876 
4877 	/*
4878 	 * Migration keys off css rather than cgroup identity, so it can hand an
4879 	 * unchanged-cgroup task here with cgrp_moving_from NULL. Nothing to
4880 	 * report to the BPF scheduler then, so skip it and keep prep_move and
4881 	 * move paired.
4882 	 */
4883 	sch = scx_cgroup_task_sched(p);
4884 	if (p->scx.cgrp_moving_from && SCX_HAS_OP(sch, cgroup_move))
4885 		SCX_CALL_OP_TASK(sch, cgroup_move, task_rq(p),
4886 				 p, p->scx.cgrp_moving_from,
4887 				 tg_cgrp(task_group(p)));
4888 	p->scx.cgrp_moving_from = NULL;
4889 }
4890 
scx_cgroup_cancel_attach(struct cgroup_taskset * tset)4891 void scx_cgroup_cancel_attach(struct cgroup_taskset *tset)
4892 {
4893 	struct cgroup_subsys_state *css;
4894 	struct task_struct *p;
4895 
4896 	if (!scx_cgroup_enabled)
4897 		return;
4898 
4899 	cgroup_taskset_for_each(p, css, tset) {
4900 		struct scx_sched *sch = scx_cgroup_task_sched(p);
4901 
4902 		/* cgrp_moving_from implies non-NULL @sch, test it first */
4903 		if (p->scx.cgrp_moving_from && SCX_HAS_OP(sch, cgroup_cancel_move))
4904 			SCX_CALL_OP(sch, cgroup_cancel_move, NULL,
4905 				    p, p->scx.cgrp_moving_from, css->cgroup);
4906 		p->scx.cgrp_moving_from = NULL;
4907 	}
4908 }
4909 
scx_group_set_weight(struct task_group * tg,unsigned long weight)4910 void scx_group_set_weight(struct task_group *tg, unsigned long weight)
4911 {
4912 	struct scx_sched *sch;
4913 
4914 	percpu_down_read(&scx_cgroup_ops_rwsem);
4915 	sch = scx_tg_knob_sched(tg);
4916 
4917 	if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_weight) &&
4918 	    tg->scx.weight != weight)
4919 		SCX_CALL_OP(sch, cgroup_set_weight, NULL, tg_cgrp(tg), weight);
4920 
4921 	tg->scx.weight = weight;
4922 
4923 	percpu_up_read(&scx_cgroup_ops_rwsem);
4924 }
4925 
scx_group_set_idle(struct task_group * tg,bool idle)4926 void scx_group_set_idle(struct task_group *tg, bool idle)
4927 {
4928 	struct scx_sched *sch;
4929 
4930 	percpu_down_read(&scx_cgroup_ops_rwsem);
4931 	sch = scx_tg_knob_sched(tg);
4932 
4933 	if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_idle))
4934 		SCX_CALL_OP(sch, cgroup_set_idle, NULL, tg_cgrp(tg), idle);
4935 
4936 	/* Update the task group's idle state */
4937 	tg->scx.idle = idle;
4938 
4939 	percpu_up_read(&scx_cgroup_ops_rwsem);
4940 }
4941 
scx_group_set_bandwidth(struct task_group * tg,u64 period_us,u64 quota_us,u64 burst_us)4942 void scx_group_set_bandwidth(struct task_group *tg,
4943 			     u64 period_us, u64 quota_us, u64 burst_us)
4944 {
4945 	struct scx_sched *sch;
4946 
4947 	percpu_down_read(&scx_cgroup_ops_rwsem);
4948 	sch = scx_tg_knob_sched(tg);
4949 
4950 	if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_bandwidth) &&
4951 	    (tg->scx.bw_period_us != period_us ||
4952 	     tg->scx.bw_quota_us != quota_us ||
4953 	     tg->scx.bw_burst_us != burst_us))
4954 		SCX_CALL_OP(sch, cgroup_set_bandwidth, NULL,
4955 			    tg_cgrp(tg), period_us, quota_us, burst_us);
4956 
4957 	tg->scx.bw_period_us = period_us;
4958 	tg->scx.bw_quota_us = quota_us;
4959 	tg->scx.bw_burst_us = burst_us;
4960 
4961 	percpu_up_read(&scx_cgroup_ops_rwsem);
4962 }
4963 #endif	/* CONFIG_EXT_GROUP_SCHED */
4964 
4965 #if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED)
root_cgroup(void)4966 static struct cgroup *root_cgroup(void)
4967 {
4968 	return &cgrp_dfl_root.cgrp;
4969 }
4970 
4971 /*
4972  * cgroup_lock() must nest outside the rwsem write side: a writer waiting
4973  * for cgroup_mutex deadlocks with cgroup teardown, which holds it while
4974  * draining a set_* file write blocked on the rwsem behind the writer.
4975  */
scx_cgroup_lock(void)4976 void scx_cgroup_lock(void)
4977 {
4978 	cgroup_lock();
4979 #ifdef CONFIG_EXT_GROUP_SCHED
4980 	percpu_down_write(&scx_cgroup_ops_rwsem);
4981 #endif
4982 }
4983 
scx_cgroup_unlock(void)4984 void scx_cgroup_unlock(void)
4985 {
4986 #ifdef CONFIG_EXT_GROUP_SCHED
4987 	percpu_up_write(&scx_cgroup_ops_rwsem);
4988 #endif
4989 	cgroup_unlock();
4990 }
4991 #else	/* CONFIG_EXT_GROUP_SCHED || CONFIG_EXT_SUB_SCHED */
root_cgroup(void)4992 static inline struct cgroup *root_cgroup(void) { return NULL; }
scx_cgroup_lock(void)4993 static inline void scx_cgroup_lock(void) {}
scx_cgroup_unlock(void)4994 static inline void scx_cgroup_unlock(void) {}
4995 #endif	/* CONFIG_EXT_GROUP_SCHED || CONFIG_EXT_SUB_SCHED */
4996 
4997 /*
4998  * Omitted operations:
4999  *
5000  * - migrate_task_rq: Unnecessary as task to cpu mapping is transient.
5001  *
5002  * - task_fork/dead: We need fork/dead notifications for all tasks regardless of
5003  *   their current sched_class. Call them directly from sched core instead.
5004  */
5005 DEFINE_SCHED_CLASS(ext) = {
5006 	.enqueue_task		= enqueue_task_scx,
5007 	.dequeue_task		= dequeue_task_scx,
5008 	.yield_task		= yield_task_scx,
5009 	.yield_to_task		= yield_to_task_scx,
5010 
5011 	.wakeup_preempt		= wakeup_preempt_scx,
5012 
5013 	.pick_task		= pick_task_scx,
5014 
5015 	.put_prev_task		= put_prev_task_scx,
5016 	.set_next_task		= set_next_task_scx,
5017 
5018 	.select_task_rq		= select_task_rq_scx,
5019 	.task_woken		= task_woken_scx,
5020 	.set_cpus_allowed	= set_cpus_allowed_scx,
5021 
5022 	.rq_online		= rq_online_scx,
5023 	.rq_offline		= rq_offline_scx,
5024 
5025 	.task_tick		= task_tick_scx,
5026 
5027 	.switching_to		= switching_to_scx,
5028 	.switched_from		= switched_from_scx,
5029 	.switched_to		= switched_to_scx,
5030 	.reweight_task		= reweight_task_scx,
5031 	.prio_changed		= prio_changed_scx,
5032 
5033 	.update_curr		= update_curr_scx,
5034 
5035 #ifdef CONFIG_UCLAMP_TASK
5036 	.uclamp_enabled		= 1,
5037 #endif
5038 };
5039 
scx_init_dsq(struct scx_dispatch_q * dsq,u64 dsq_id,struct scx_sched * sch)5040 s32 scx_init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id, struct scx_sched *sch)
5041 {
5042 	s32 cpu;
5043 
5044 	memset(dsq, 0, sizeof(*dsq));
5045 
5046 	raw_spin_lock_init(&dsq->lock);
5047 	INIT_LIST_HEAD(&dsq->list);
5048 	dsq->id = dsq_id;
5049 	dsq->sched = sch;
5050 
5051 	dsq->pcpu = alloc_percpu(struct scx_dsq_pcpu);
5052 	if (!dsq->pcpu)
5053 		return -ENOMEM;
5054 
5055 	for_each_possible_cpu(cpu) {
5056 		struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu, cpu);
5057 
5058 		pcpu->dsq = dsq;
5059 		INIT_LIST_HEAD(&pcpu->deferred_reenq_user.node);
5060 	}
5061 
5062 	return 0;
5063 }
5064 
exit_dsq(struct scx_dispatch_q * dsq)5065 static void exit_dsq(struct scx_dispatch_q *dsq)
5066 {
5067 	s32 cpu;
5068 
5069 	for_each_possible_cpu(cpu) {
5070 		struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu, cpu);
5071 		struct scx_deferred_reenq_user *dru = &pcpu->deferred_reenq_user;
5072 		struct rq *rq = cpu_rq(cpu);
5073 
5074 		/*
5075 		 * There must have been a RCU grace period since the last
5076 		 * insertion and @dsq should be off the deferred list by now.
5077 		 */
5078 		if (WARN_ON_ONCE(!list_empty(&dru->node))) {
5079 			guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
5080 			list_del_init(&dru->node);
5081 		}
5082 	}
5083 
5084 	free_percpu(dsq->pcpu);
5085 }
5086 
free_dsq_rcufn(struct rcu_head * rcu)5087 static void free_dsq_rcufn(struct rcu_head *rcu)
5088 {
5089 	struct scx_dispatch_q *dsq = container_of(rcu, struct scx_dispatch_q, rcu);
5090 
5091 	exit_dsq(dsq);
5092 	kfree(dsq);
5093 }
5094 
free_dsq_irq_workfn(struct irq_work * irq_work)5095 static void free_dsq_irq_workfn(struct irq_work *irq_work)
5096 {
5097 	struct llist_node *to_free = llist_del_all(&dsqs_to_free);
5098 	struct scx_dispatch_q *dsq, *tmp_dsq;
5099 
5100 	llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node)
5101 		call_rcu(&dsq->rcu, free_dsq_rcufn);
5102 }
5103 
5104 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn);
5105 
destroy_dsq(struct scx_sched * sch,u64 dsq_id)5106 static void destroy_dsq(struct scx_sched *sch, u64 dsq_id)
5107 {
5108 	struct scx_dispatch_q *dsq;
5109 	unsigned long flags;
5110 
5111 	rcu_read_lock();
5112 
5113 	dsq = find_user_dsq(sch, dsq_id);
5114 	if (!dsq)
5115 		goto out_unlock_rcu;
5116 
5117 	raw_spin_lock_irqsave(&dsq->lock, flags);
5118 
5119 	if (dsq->nr) {
5120 		scx_error(sch, "attempting to destroy in-use dsq 0x%016llx (nr=%u)",
5121 			  dsq->id, dsq->nr);
5122 		goto out_unlock_dsq;
5123 	}
5124 
5125 	if (rhashtable_remove_fast(&sch->dsq_hash, &dsq->hash_node,
5126 				   dsq_hash_params))
5127 		goto out_unlock_dsq;
5128 
5129 	/*
5130 	 * Mark dead by invalidating ->id to prevent scx_dispatch_enqueue() from
5131 	 * queueing more tasks. As this function can be called from anywhere,
5132 	 * freeing is bounced through an irq work to avoid nesting RCU
5133 	 * operations inside scheduler locks.
5134 	 */
5135 	dsq->id = SCX_DSQ_INVALID;
5136 	if (llist_add(&dsq->free_node, &dsqs_to_free))
5137 		irq_work_queue(&free_dsq_irq_work);
5138 
5139 out_unlock_dsq:
5140 	raw_spin_unlock_irqrestore(&dsq->lock, flags);
5141 out_unlock_rcu:
5142 	rcu_read_unlock();
5143 }
5144 
5145 #ifdef CONFIG_EXT_GROUP_SCHED
scx_cgroup_exit(struct scx_sched * sch)5146 static void scx_cgroup_exit(struct scx_sched *sch)
5147 {
5148 	struct cgroup_subsys_state *css;
5149 
5150 	/*
5151 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
5152 	 * cgroups and exit all the inited ones, all online cgroups are exited.
5153 	 */
5154 	css_for_each_descendant_post(css, &root_task_group.css) {
5155 		struct task_group *tg = css_tg(css);
5156 
5157 		/* also clear the sched of tgs whose ops.cgroup_init() failed */
5158 		tg->scx.sched = NULL;
5159 		if (tg->scx.flags & SCX_TG_INITED) {
5160 			tg->scx.flags &= ~SCX_TG_INITED;
5161 			if (sch->ops.cgroup_exit)
5162 				SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup);
5163 		}
5164 	}
5165 }
5166 
scx_cgroup_init(struct scx_sched * sch)5167 static int scx_cgroup_init(struct scx_sched *sch)
5168 {
5169 	struct cgroup_subsys_state *css;
5170 	int ret;
5171 
5172 	/*
5173 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
5174 	 * cgroups and init, all online cgroups are initialized.
5175 	 */
5176 	css_for_each_descendant_pre(css, &root_task_group.css) {
5177 		struct task_group *tg = css_tg(css);
5178 
5179 		if ((tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED)) != SCX_TG_ONLINE)
5180 			continue;
5181 
5182 		if (sch->ops.cgroup_init) {
5183 			struct scx_cgroup_init_args args = {
5184 				.weight = tg->scx.weight,
5185 				.bw_period_us = tg->scx.bw_period_us,
5186 				.bw_quota_us = tg->scx.bw_quota_us,
5187 				.bw_burst_us = tg->scx.bw_burst_us,
5188 			};
5189 
5190 			ret = SCX_CALL_OP_RET(sch, cgroup_init, NULL, css->cgroup, &args);
5191 			if (ret) {
5192 				scx_error(sch, "ops.cgroup_init() failed (%d)", ret);
5193 				return ret;
5194 			}
5195 		}
5196 
5197 		tg->scx.sched = sch;
5198 		tg->scx.flags |= SCX_TG_INITED;
5199 	}
5200 
5201 	return 0;
5202 }
5203 
5204 #else
scx_cgroup_exit(struct scx_sched * sch)5205 static void scx_cgroup_exit(struct scx_sched *sch) {}
scx_cgroup_init(struct scx_sched * sch)5206 static int scx_cgroup_init(struct scx_sched *sch) { return 0; }
5207 #endif
5208 
5209 
5210 /********************************************************************************
5211  * Sysfs interface and ops enable/disable.
5212  */
5213 
5214 #define SCX_ATTR(_name)								\
5215 	static struct kobj_attribute scx_attr_##_name = {			\
5216 		.attr = { .name = __stringify(_name), .mode = 0444 },		\
5217 		.show = scx_attr_##_name##_show,				\
5218 	}
5219 
scx_attr_state_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)5220 static ssize_t scx_attr_state_show(struct kobject *kobj,
5221 				   struct kobj_attribute *ka, char *buf)
5222 {
5223 	return sysfs_emit(buf, "%s\n", scx_enable_state_str[scx_enable_state()]);
5224 }
5225 SCX_ATTR(state);
5226 
scx_attr_switch_all_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)5227 static ssize_t scx_attr_switch_all_show(struct kobject *kobj,
5228 					struct kobj_attribute *ka, char *buf)
5229 {
5230 	return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all));
5231 }
5232 SCX_ATTR(switch_all);
5233 
scx_attr_nr_rejected_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)5234 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj,
5235 					 struct kobj_attribute *ka, char *buf)
5236 {
5237 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected));
5238 }
5239 SCX_ATTR(nr_rejected);
5240 
scx_attr_hotplug_seq_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)5241 static ssize_t scx_attr_hotplug_seq_show(struct kobject *kobj,
5242 					 struct kobj_attribute *ka, char *buf)
5243 {
5244 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_hotplug_seq));
5245 }
5246 SCX_ATTR(hotplug_seq);
5247 
scx_attr_enable_seq_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)5248 static ssize_t scx_attr_enable_seq_show(struct kobject *kobj,
5249 					struct kobj_attribute *ka, char *buf)
5250 {
5251 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_enable_seq));
5252 }
5253 SCX_ATTR(enable_seq);
5254 
5255 static struct attribute *scx_global_attrs[] = {
5256 	&scx_attr_state.attr,
5257 	&scx_attr_switch_all.attr,
5258 	&scx_attr_nr_rejected.attr,
5259 	&scx_attr_hotplug_seq.attr,
5260 	&scx_attr_enable_seq.attr,
5261 	NULL,
5262 };
5263 
5264 static const struct attribute_group scx_global_attr_group = {
5265 	.attrs = scx_global_attrs,
5266 };
5267 
5268 static void free_pnode(struct scx_sched_pnode *pnode);
5269 static void free_exit_info(struct scx_exit_info *ei);
5270 static const char *scx_exit_reason(enum scx_exit_kind kind);
5271 static bool scx_claim_exit(struct scx_sched *sch, enum scx_exit_kind kind);
5272 
scx_set_cmask_scratch_alloc(struct scx_sched * sch)5273 s32 scx_set_cmask_scratch_alloc(struct scx_sched *sch)
5274 {
5275 	size_t size = struct_size_t(struct scx_cmask, bits,
5276 				    SCX_CMASK_NR_WORDS(num_possible_cpus()));
5277 	int cpu;
5278 
5279 	if (!sch->is_cid_type || !sch->arena_pool)
5280 		return 0;
5281 
5282 	sch->set_cmask_scratch = alloc_percpu(struct scx_cmask *);
5283 	if (!sch->set_cmask_scratch)
5284 		return -ENOMEM;
5285 
5286 	for_each_possible_cpu(cpu) {
5287 		struct scx_cmask **slot = per_cpu_ptr(sch->set_cmask_scratch, cpu);
5288 
5289 		*slot = scx_arena_alloc(sch, size);
5290 		if (!*slot)
5291 			return -ENOMEM;
5292 		scx_cmask_init(*slot, 0, num_possible_cpus());
5293 	}
5294 	return 0;
5295 }
5296 
scx_set_cmask_scratch_free(struct scx_sched * sch)5297 static void scx_set_cmask_scratch_free(struct scx_sched *sch)
5298 {
5299 	size_t size = struct_size_t(struct scx_cmask, bits,
5300 				    SCX_CMASK_NR_WORDS(num_possible_cpus()));
5301 	int cpu;
5302 
5303 	if (!sch->set_cmask_scratch)
5304 		return;
5305 
5306 	for_each_possible_cpu(cpu) {
5307 		struct scx_cmask **slot = per_cpu_ptr(sch->set_cmask_scratch, cpu);
5308 
5309 		scx_arena_free(sch, *slot, size);
5310 	}
5311 	free_percpu(sch->set_cmask_scratch);
5312 	sch->set_cmask_scratch = NULL;
5313 }
5314 
scx_sched_free_rcu_work(struct work_struct * work)5315 static void scx_sched_free_rcu_work(struct work_struct *work)
5316 {
5317 	struct rcu_work *rcu_work = to_rcu_work(work);
5318 	struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work);
5319 	struct rhashtable_iter rht_iter;
5320 	struct scx_dispatch_q *dsq;
5321 	int cpu, node;
5322 
5323 	irq_work_sync(&sch->propagate_exit_irq_work);
5324 	irq_work_sync(&sch->disable_irq_work);
5325 	kthread_destroy_worker(sch->helper);
5326 	timer_shutdown_sync(&sch->bypass_lb_timer);
5327 	free_cpumask_var(sch->bypass_lb_donee_cpumask);
5328 	free_cpumask_var(sch->bypass_lb_resched_cpumask);
5329 	free_cpumask_var(sch->stall_cpus);
5330 
5331 #ifdef CONFIG_EXT_SUB_SCHED
5332 	kfree(sch->cgrp_path);
5333 	if (sch_cgroup(sch))
5334 		cgroup_put(sch_cgroup(sch));
5335 	if (sch->sub_kset)
5336 		kobject_put(&sch->sub_kset->kobj);
5337 	if (scx_parent(sch))
5338 		kobject_put(&scx_parent(sch)->kobj);
5339 #endif	/* CONFIG_EXT_SUB_SCHED */
5340 
5341 	for_each_possible_cpu(cpu) {
5342 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
5343 
5344 		/*
5345 		 * $sch would have entered bypass mode before the RCU grace
5346 		 * period. As that blocks new deferrals, all
5347 		 * deferred_reenq_local_node's must be off-list by now.
5348 		 */
5349 		WARN_ON_ONCE(!list_empty(&pcpu->deferred_reenq_local.node));
5350 
5351 		/* remove the queued ecaps sync so the pcpu can be freed */
5352 		scx_discard_ecaps_to_sync(cpu, pcpu);
5353 
5354 		/*
5355 		 * Bypass blocks new kicks. Flush the kick irq_work so this
5356 		 * pcpu's to_kick_node is off the list before it is freed.
5357 		 */
5358 		irq_work_sync(&cpu_rq(cpu)->scx.kick_cpus_irq_work);
5359 		WARN_ON_ONCE(!list_empty(&pcpu->to_kick_node));
5360 		free_cpumask_var(pcpu->cpus_to_kick);
5361 		free_cpumask_var(pcpu->cpus_to_kick_if_idle);
5362 		free_cpumask_var(pcpu->cpus_to_preempt);
5363 		free_cpumask_var(pcpu->cpus_to_wait);
5364 
5365 		exit_dsq(scx_bypass_dsq(sch, cpu));
5366 	}
5367 
5368 	free_percpu(sch->pcpu);
5369 
5370 	for_each_node_state(node, N_POSSIBLE)
5371 		free_pnode(sch->pnode[node]);
5372 	kfree(sch->pnode);
5373 
5374 	scx_free_pshards(sch);
5375 
5376 	rhashtable_walk_enter(&sch->dsq_hash, &rht_iter);
5377 	do {
5378 		rhashtable_walk_start(&rht_iter);
5379 
5380 		while (!IS_ERR_OR_NULL((dsq = rhashtable_walk_next(&rht_iter))))
5381 			destroy_dsq(sch, dsq->id);
5382 
5383 		rhashtable_walk_stop(&rht_iter);
5384 	} while (dsq == ERR_PTR(-EAGAIN));
5385 	rhashtable_walk_exit(&rht_iter);
5386 
5387 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
5388 	free_exit_info(sch->exit_info);
5389 	scx_set_cmask_scratch_free(sch);
5390 	scx_arena_pool_destroy(sch);
5391 	if (sch->arena_map)
5392 		bpf_map_put(sch->arena_map);
5393 
5394 	/* @sch is completely inactive by now */
5395 	scx_dec_has_subs(sch);
5396 
5397 	kfree(sch);
5398 }
5399 
scx_kobj_release(struct kobject * kobj)5400 static void scx_kobj_release(struct kobject *kobj)
5401 {
5402 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
5403 
5404 	INIT_RCU_WORK(&sch->rcu_work, scx_sched_free_rcu_work);
5405 	queue_rcu_work(system_dfl_wq, &sch->rcu_work);
5406 }
5407 
scx_attr_ops_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)5408 static ssize_t scx_attr_ops_show(struct kobject *kobj,
5409 				 struct kobj_attribute *ka, char *buf)
5410 {
5411 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
5412 
5413 	return sysfs_emit(buf, "%s\n", sch->ops.name);
5414 }
5415 SCX_ATTR(ops);
5416 
5417 #define scx_attr_event_show(buf, at, events, kind) ({				\
5418 	sysfs_emit_at(buf, at, "%s %llu\n", #kind, (events)->kind);		\
5419 })
5420 
scx_attr_events_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)5421 static ssize_t scx_attr_events_show(struct kobject *kobj,
5422 				    struct kobj_attribute *ka, char *buf)
5423 {
5424 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
5425 	struct scx_event_stats events;
5426 	int at = 0;
5427 
5428 	scx_read_events(sch, &events);
5429 #define SCX_EVENT(name)	(at += scx_attr_event_show(buf, at, &events, name))
5430 	SCX_EVENTS_LIST(SCX_EVENT);
5431 #undef SCX_EVENT
5432 	return at;
5433 }
5434 SCX_ATTR(events);
5435 
5436 #ifdef CONFIG_EXT_SUB_SCHED
5437 static const char *scx_cap_names[__SCX_NR_CAPS] = {
5438 	[__SCX_CAP_ENQ_IMMED]	= "enq_immed",
5439 	[__SCX_CAP_ENQ]		= "enq",
5440 	[__SCX_CAP_PREEMPT]	= "preempt",
5441 	[__SCX_CAP_PERF]	= "perf",
5442 };
5443 
scx_attr_caps_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)5444 static ssize_t scx_attr_caps_show(struct kobject *kobj,
5445 				  struct kobj_attribute *ka, char *buf)
5446 {
5447 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
5448 	u32 npossible = num_possible_cpus();
5449 	struct scx_cmask *agg __free(kfree) =
5450 		kzalloc(struct_size(agg, bits, SCX_CMASK_NR_WORDS(npossible)), GFP_KERNEL);
5451 	unsigned long *agg_bm __free(bitmap) = bitmap_zalloc(npossible, GFP_KERNEL);
5452 	ssize_t count = 0;
5453 	s32 cap, si;
5454 
5455 	if (!agg || !agg_bm)
5456 		return -ENOMEM;
5457 
5458 	for (cap = 0; cap < __SCX_NR_CAPS; cap++) {
5459 		SCX_CMASK_DEFINE(snap, 0, SCX_CID_SHARD_MAX_CPUS);
5460 
5461 		scx_cmask_init(agg, 0, npossible);
5462 		for (si = 0; si < sch->nr_pshards; si++) {
5463 			struct scx_cmask *cm = &sch->pshard[si]->caps[cap].cmask;
5464 
5465 			scx_cmask_reframe(snap, cm->base, cm->nr_cids);
5466 			scx_cmask_copy(snap, cm);
5467 			scx_cmask_or(agg, snap);
5468 		}
5469 		/* %*pbl takes unsigned long bitmap layout, convert from u64 */
5470 		bitmap_from_arr64(agg_bm, agg->bits, npossible);
5471 		count += sysfs_emit_at(buf, count, "%s: %*pbl\n",
5472 				       scx_cap_names[cap], npossible, agg_bm);
5473 	}
5474 	return count;
5475 }
5476 SCX_ATTR(caps);
5477 #endif	/* CONFIG_EXT_SUB_SCHED */
5478 
5479 static struct attribute *scx_sched_attrs[] = {
5480 	&scx_attr_ops.attr,
5481 	&scx_attr_events.attr,
5482 #ifdef CONFIG_EXT_SUB_SCHED
5483 	&scx_attr_caps.attr,
5484 #endif
5485 	NULL,
5486 };
5487 ATTRIBUTE_GROUPS(scx_sched);
5488 
5489 static const struct kobj_type scx_ktype = {
5490 	.release = scx_kobj_release,
5491 	.sysfs_ops = &kobj_sysfs_ops,
5492 	.default_groups = scx_sched_groups,
5493 };
5494 
scx_uevent(const struct kobject * kobj,struct kobj_uevent_env * env)5495 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
5496 {
5497 	const struct scx_sched *sch;
5498 
5499 	/*
5500 	 * scx_uevent() can be reached by both scx_sched kobjects (scx_ktype)
5501 	 * and sub-scheduler kset kobjects (kset_ktype) through the parent
5502 	 * chain walk. Filter out the latter to avoid invalid casts.
5503 	 */
5504 	if (kobj->ktype != &scx_ktype)
5505 		return 0;
5506 
5507 	sch = container_of(kobj, struct scx_sched, kobj);
5508 
5509 	return add_uevent_var(env, "SCXOPS=%s", sch->ops.name);
5510 }
5511 
5512 static const struct kset_uevent_ops scx_uevent_ops = {
5513 	.uevent = scx_uevent,
5514 };
5515 
5516 /*
5517  * Used by sched_fork() and __setscheduler_prio() to pick the matching
5518  * sched_class. dl/rt are already handled.
5519  */
task_should_scx(int policy)5520 bool task_should_scx(int policy)
5521 {
5522 	/* if disabled, nothing should be on it */
5523 	if (!scx_enabled())
5524 		return false;
5525 
5526 	/* scx is taking over all SCHED_OTHER and SCHED_EXT tasks */
5527 	if (READ_ONCE(scx_switching_all))
5528 		return true;
5529 
5530 	/*
5531 	 * scx is tearing down - keep new SCHED_EXT tasks out.
5532 	 *
5533 	 * Must come after scx_switching_all test, which serves as a proxy
5534 	 * for __scx_switched_all. While __scx_switched_all is set, we must
5535 	 * return true via the branch above: a fork routed to fair would
5536 	 * stall because next_active_class() skips fair.
5537 	 *
5538 	 * This can develop into a deadlock - scx holds scx_enable_mutex across
5539 	 * kthread_create() in scx_alloc_and_add_sched(); if the new kthread is
5540 	 * the stalled task, the disable path can never grab the mutex to clear
5541 	 * scx_switching_all.
5542 	 */
5543 	if (unlikely(scx_enable_state() == SCX_DISABLING))
5544 		return false;
5545 
5546 	return policy == SCHED_EXT;
5547 }
5548 
scx_allow_ttwu_queue(const struct task_struct * p)5549 bool scx_allow_ttwu_queue(const struct task_struct *p)
5550 {
5551 	struct scx_sched *sch;
5552 
5553 	if (!scx_enabled())
5554 		return true;
5555 
5556 	sch = scx_task_sched(p);
5557 	if (unlikely(!sch))
5558 		return true;
5559 
5560 	if (sch->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP)
5561 		return true;
5562 
5563 	if (unlikely(p->sched_class != &ext_sched_class))
5564 		return true;
5565 
5566 	return false;
5567 }
5568 
5569 /**
5570  * handle_lockup - sched_ext common lockup handler
5571  * @exit_cpu: CPU to record in exit_info. Pass the stalled/hung CPU, not current.
5572  * @fmt: format string
5573  *
5574  * Called on system stall or lockup condition and initiates abort of sched_ext
5575  * if enabled, which may resolve the reported lockup.
5576  *
5577  * Returns %true if sched_ext is enabled and abort was initiated, which may
5578  * resolve the lockup. %false if sched_ext is not enabled or abort was already
5579  * initiated by someone else.
5580  */
handle_lockup(int exit_cpu,const char * fmt,...)5581 static __printf(2, 3) bool handle_lockup(int exit_cpu, const char *fmt, ...)
5582 {
5583 	struct scx_sched *sch;
5584 	va_list args;
5585 	bool ret;
5586 
5587 	guard(rcu)();
5588 
5589 	sch = rcu_dereference(scx_root);
5590 	if (unlikely(!sch))
5591 		return false;
5592 
5593 	switch (scx_enable_state()) {
5594 	case SCX_ENABLING:
5595 	case SCX_ENABLED:
5596 		va_start(args, fmt);
5597 		ret = scx_vexit(sch, SCX_EXIT_ERROR, 0, exit_cpu, fmt, args);
5598 		va_end(args);
5599 		return ret;
5600 	default:
5601 		return false;
5602 	}
5603 }
5604 
5605 /**
5606  * scx_rcu_cpu_stall - sched_ext RCU CPU stall handler
5607  * @stalled_mask: bit mask of stalled CPUs
5608  *
5609  * While there are various reasons why RCU CPU stalls can occur on a system
5610  * that may not be caused by the current BPF scheduler, try kicking out the
5611  * current scheduler in an attempt to recover the system to a good state before
5612  * issuing panics.
5613  *
5614  * Returns %true if sched_ext is enabled and abort was initiated, which may
5615  * resolve the reported RCU stall. %false if sched_ext is not enabled or someone
5616  * else already initiated abort.
5617  */
scx_rcu_cpu_stall(const struct cpumask * stalled_mask)5618 bool scx_rcu_cpu_stall(const struct cpumask *stalled_mask)
5619 {
5620 	struct scx_sched *sch;
5621 	struct scx_exit_info *ei;
5622 	int exit_cpu;
5623 
5624 	guard(rcu)();
5625 
5626 	sch = rcu_dereference(scx_root);
5627 	if (unlikely(!sch))
5628 		return false;
5629 
5630 	switch (scx_enable_state()) {
5631 	case SCX_ENABLING:
5632 	case SCX_ENABLED:
5633 		break;
5634 	default:
5635 		return false;
5636 	}
5637 
5638 	exit_cpu = cpumask_empty(stalled_mask) ? -1 : (int)cpumask_first(stalled_mask);
5639 	ei = sch->exit_info;
5640 
5641 	guard(preempt)();
5642 
5643 	if (!scx_claim_exit(sch, SCX_EXIT_ERROR))
5644 		return false;
5645 
5646 #ifdef CONFIG_STACKTRACE
5647 	ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
5648 #endif
5649 	scnprintf(ei->msg, SCX_EXIT_MSG_LEN, "RCU CPU stall on CPUs (%*pbl)",
5650 		  cpumask_pr_args(stalled_mask));
5651 	ei->kind = SCX_EXIT_ERROR;
5652 	ei->reason = scx_exit_reason(SCX_EXIT_ERROR);
5653 	ei->exit_cpu = exit_cpu;
5654 	cpumask_copy(sch->stall_cpus, stalled_mask);
5655 
5656 	irq_work_queue(&sch->disable_irq_work);
5657 	return true;
5658 }
5659 
5660 /**
5661  * scx_softlockup - sched_ext softlockup handler
5662  * @dur_s: number of seconds of CPU stuck due to soft lockup
5663  *
5664  * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can
5665  * live-lock the system by making many CPUs target the same DSQ to the point
5666  * where soft-lockup detection triggers. This function is called from
5667  * soft-lockup watchdog when the triggering point is close and tries to unjam
5668  * the system and aborting the BPF scheduler.
5669  */
scx_softlockup(u32 dur_s)5670 void scx_softlockup(u32 dur_s)
5671 {
5672 	int cpu = smp_processor_id();
5673 
5674 	if (!handle_lockup(cpu, "soft lockup - CPU %d stuck for %us", cpu, dur_s))
5675 		return;
5676 
5677 	printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU %d stuck for %us, disabling BPF scheduler\n",
5678 			cpu, dur_s);
5679 }
5680 
5681 /**
5682  * scx_hardlockup - sched_ext hardlockup handler
5683  * @cpu: the target CPU
5684  *
5685  * A poorly behaving BPF scheduler can trigger hard lockup by e.g. putting
5686  * numerous affinitized tasks in a single queue and directing all CPUs at it.
5687  * Try kicking out the current scheduler in an attempt to recover the system to
5688  * a good state before taking more drastic actions.
5689  *
5690  * Called from NMI. Aborting the scheduler sets ->aborting throughout the
5691  * hierarchy before returning, which is what breaks the dispatch-path live-locks
5692  * that can hard-lock CPUs.
5693  *
5694  * Returns %true if sched_ext is enabled and abort was initiated, which may
5695  * resolve the lockup. %false if sched_ext is not enabled or abort was already
5696  * initiated by someone else.
5697  */
scx_hardlockup(int cpu)5698 bool scx_hardlockup(int cpu)
5699 {
5700 	if (!handle_lockup(cpu, "hard lockup - CPU %d", cpu))
5701 		return false;
5702 
5703 	printk_deferred(KERN_ERR "sched_ext: Hard lockup - CPU %d, disabling BPF scheduler\n",
5704 			cpu);
5705 	return true;
5706 }
5707 
bypass_lb_cpu(struct scx_sched * sch,s32 donor,struct cpumask * donee_mask,struct cpumask * resched_mask,u32 nr_donor_target,u32 nr_donee_target)5708 static u32 bypass_lb_cpu(struct scx_sched *sch, s32 donor,
5709 			 struct cpumask *donee_mask, struct cpumask *resched_mask,
5710 			 u32 nr_donor_target, u32 nr_donee_target)
5711 {
5712 	struct rq *donor_rq = cpu_rq(donor);
5713 	struct scx_dispatch_q *donor_dsq = scx_bypass_dsq(sch, donor);
5714 	struct task_struct *p, *n;
5715 	struct scx_dsq_list_node cursor = INIT_DSQ_LIST_CURSOR(cursor, donor_dsq, 0);
5716 	s32 delta = READ_ONCE(donor_dsq->nr) - nr_donor_target;
5717 	u32 nr_balanced = 0, min_delta_us;
5718 
5719 	/*
5720 	 * All we want to guarantee is reasonable forward progress. No reason to
5721 	 * fine tune. Assuming every task on @donor_dsq runs their full slice,
5722 	 * consider offloading iff the total queued duration is over the
5723 	 * threshold.
5724 	 */
5725 	min_delta_us = READ_ONCE(scx_bypass_lb_intv_us) / SCX_BYPASS_LB_MIN_DELTA_DIV;
5726 	if (delta < DIV_ROUND_UP(min_delta_us, READ_ONCE(scx_slice_bypass_us)))
5727 		return 0;
5728 
5729 	raw_spin_rq_lock_irq(donor_rq);
5730 	raw_spin_lock(&donor_dsq->lock);
5731 	list_add(&cursor.node, &donor_dsq->list);
5732 resume:
5733 	n = container_of(&cursor, struct task_struct, scx.dsq_list);
5734 	n = nldsq_next_task(donor_dsq, n, false);
5735 
5736 	while ((p = n)) {
5737 		struct scx_dispatch_q *donee_dsq;
5738 		int donee;
5739 
5740 		n = nldsq_next_task(donor_dsq, n, false);
5741 
5742 		if (donor_dsq->nr <= nr_donor_target)
5743 			break;
5744 
5745 		if (cpumask_empty(donee_mask))
5746 			break;
5747 
5748 		/*
5749 		 * If an earlier pass placed @p on @donor_dsq from a different
5750 		 * CPU and the donee hasn't consumed it yet, @p is still on the
5751 		 * previous CPU and task_rq(@p) != @donor_rq. @p can't be moved
5752 		 * without its rq locked. Skip.
5753 		 */
5754 		if (task_rq(p) != donor_rq)
5755 			continue;
5756 
5757 		donee = cpumask_any_and_distribute(donee_mask, p->cpus_ptr);
5758 		if (donee >= nr_cpu_ids)
5759 			continue;
5760 
5761 		donee_dsq = scx_bypass_dsq(sch, donee);
5762 
5763 		/*
5764 		 * $p's rq is not locked but $p's DSQ lock protects its
5765 		 * scheduling properties making this test safe.
5766 		 */
5767 		if (!task_can_run_on_remote_rq(sch, p, cpu_rq(donee), false))
5768 			continue;
5769 
5770 		/*
5771 		 * Moving $p from one non-local DSQ to another. The source rq
5772 		 * and DSQ are already locked. Do an abbreviated dequeue and
5773 		 * then perform enqueue without unlocking $donor_dsq.
5774 		 *
5775 		 * We don't want to drop and reacquire the lock on each
5776 		 * iteration as @donor_dsq can be very long and potentially
5777 		 * highly contended. Donee DSQs are less likely to be contended.
5778 		 * The nested locking is safe as only this LB moves tasks
5779 		 * between bypass DSQs.
5780 		 */
5781 		dispatch_dequeue_locked(p, donor_dsq);
5782 		scx_dispatch_enqueue(sch, cpu_rq(donee), donee_dsq, p, 0, 0, SCX_ENQ_NESTED);
5783 
5784 		/*
5785 		 * $donee might have been idle and need to be woken up. No need
5786 		 * to be clever. Kick every CPU that receives tasks.
5787 		 */
5788 		cpumask_set_cpu(donee, resched_mask);
5789 
5790 		if (READ_ONCE(donee_dsq->nr) >= nr_donee_target)
5791 			cpumask_clear_cpu(donee, donee_mask);
5792 
5793 		nr_balanced++;
5794 		if (!(nr_balanced % SCX_BYPASS_LB_BATCH) && n) {
5795 			list_move_tail(&cursor.node, &n->scx.dsq_list.node);
5796 			raw_spin_unlock(&donor_dsq->lock);
5797 			scx_rq_lock_drop(donor_rq);
5798 			raw_spin_rq_unlock_irq(donor_rq);
5799 			cpu_relax();
5800 			raw_spin_rq_lock_irq(donor_rq);
5801 			raw_spin_lock(&donor_dsq->lock);
5802 			goto resume;
5803 		}
5804 	}
5805 
5806 	list_del_init(&cursor.node);
5807 	raw_spin_unlock(&donor_dsq->lock);
5808 	scx_rq_lock_drop(donor_rq);
5809 	raw_spin_rq_unlock_irq(donor_rq);
5810 
5811 	return nr_balanced;
5812 }
5813 
bypass_lb_node(struct scx_sched * sch,int node)5814 static void bypass_lb_node(struct scx_sched *sch, int node)
5815 {
5816 	const struct cpumask *node_mask = cpumask_of_node(node);
5817 	struct cpumask *donee_mask = sch->bypass_lb_donee_cpumask;
5818 	struct cpumask *resched_mask = sch->bypass_lb_resched_cpumask;
5819 	u32 nr_tasks = 0, nr_cpus = 0, nr_balanced = 0;
5820 	u32 nr_target, nr_donor_target;
5821 	u32 before_min = U32_MAX, before_max = 0;
5822 	u32 after_min = U32_MAX, after_max = 0;
5823 	int cpu;
5824 
5825 	/* count the target tasks and CPUs */
5826 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5827 		u32 nr = READ_ONCE(scx_bypass_dsq(sch, cpu)->nr);
5828 
5829 		nr_tasks += nr;
5830 		nr_cpus++;
5831 
5832 		before_min = min(nr, before_min);
5833 		before_max = max(nr, before_max);
5834 	}
5835 
5836 	if (!nr_cpus)
5837 		return;
5838 
5839 	/*
5840 	 * We don't want CPUs to have more than $nr_donor_target tasks and
5841 	 * balancing to fill donee CPUs upto $nr_target. Once targets are
5842 	 * calculated, find the donee CPUs.
5843 	 */
5844 	nr_target = DIV_ROUND_UP(nr_tasks, nr_cpus);
5845 	nr_donor_target = DIV_ROUND_UP(nr_target * SCX_BYPASS_LB_DONOR_PCT, 100);
5846 
5847 	cpumask_clear(donee_mask);
5848 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5849 		if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) < nr_target)
5850 			cpumask_set_cpu(cpu, donee_mask);
5851 	}
5852 
5853 	/* iterate !donee CPUs and see if they should be offloaded */
5854 	cpumask_clear(resched_mask);
5855 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5856 		if (cpumask_empty(donee_mask))
5857 			break;
5858 		if (cpumask_test_cpu(cpu, donee_mask))
5859 			continue;
5860 		if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) <= nr_donor_target)
5861 			continue;
5862 
5863 		nr_balanced += bypass_lb_cpu(sch, cpu, donee_mask, resched_mask,
5864 					     nr_donor_target, nr_target);
5865 	}
5866 
5867 	for_each_cpu(cpu, resched_mask)
5868 		resched_cpu(cpu);
5869 
5870 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5871 		u32 nr = READ_ONCE(scx_bypass_dsq(sch, cpu)->nr);
5872 
5873 		after_min = min(nr, after_min);
5874 		after_max = max(nr, after_max);
5875 
5876 	}
5877 
5878 	trace_sched_ext_bypass_lb(node, nr_cpus, nr_tasks, nr_balanced,
5879 				  before_min, before_max, after_min, after_max);
5880 }
5881 
5882 /*
5883  * In bypass mode, all tasks are put on the per-CPU bypass DSQs. If the machine
5884  * is over-saturated and the BPF scheduler skewed tasks into few CPUs, some
5885  * bypass DSQs can be overloaded. If there are enough tasks to saturate other
5886  * lightly loaded CPUs, such imbalance can lead to very high execution latency
5887  * on the overloaded CPUs and thus to hung tasks and RCU stalls. To avoid such
5888  * outcomes, a simple load balancing mechanism is implemented by the following
5889  * timer which runs periodically while bypass mode is in effect.
5890  */
scx_bypass_lb_timerfn(struct timer_list * timer)5891 static void scx_bypass_lb_timerfn(struct timer_list *timer)
5892 {
5893 	struct scx_sched *sch = container_of(timer, struct scx_sched, bypass_lb_timer);
5894 	int node;
5895 	u32 intv_us;
5896 
5897 	if (!scx_bypass_dsp_enabled(sch))
5898 		return;
5899 
5900 	for_each_node_with_cpus(node)
5901 		bypass_lb_node(sch, node);
5902 
5903 	intv_us = READ_ONCE(scx_bypass_lb_intv_us);
5904 	if (intv_us)
5905 		mod_timer(timer, jiffies + usecs_to_jiffies(intv_us));
5906 }
5907 
inc_bypass_depth(struct scx_sched * sch)5908 static bool inc_bypass_depth(struct scx_sched *sch)
5909 {
5910 	lockdep_assert_held(&scx_bypass_lock);
5911 
5912 	WARN_ON_ONCE(sch->bypass_depth < 0);
5913 	WRITE_ONCE(sch->bypass_depth, sch->bypass_depth + 1);
5914 	if (sch->bypass_depth != 1)
5915 		return false;
5916 
5917 	WRITE_ONCE(sch->slice_dfl, READ_ONCE(scx_slice_bypass_us) * NSEC_PER_USEC);
5918 	sch->bypass_timestamp = ktime_get_ns();
5919 	scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1);
5920 	return true;
5921 }
5922 
dec_bypass_depth(struct scx_sched * sch)5923 static bool dec_bypass_depth(struct scx_sched *sch)
5924 {
5925 	lockdep_assert_held(&scx_bypass_lock);
5926 
5927 	WARN_ON_ONCE(sch->bypass_depth < 1);
5928 	WRITE_ONCE(sch->bypass_depth, sch->bypass_depth - 1);
5929 	if (sch->bypass_depth != 0)
5930 		return false;
5931 
5932 	WRITE_ONCE(sch->slice_dfl, SCX_SLICE_DFL);
5933 	scx_add_event(sch, SCX_EV_BYPASS_DURATION,
5934 		      ktime_get_ns() - sch->bypass_timestamp);
5935 	return true;
5936 }
5937 
enable_bypass_dsp(struct scx_sched * sch)5938 static void enable_bypass_dsp(struct scx_sched *sch)
5939 {
5940 	struct scx_sched *host = scx_parent(sch) ?: sch;
5941 	u32 intv_us = READ_ONCE(scx_bypass_lb_intv_us);
5942 	s32 ret;
5943 
5944 	/*
5945 	 * @sch->bypass_depth transitioning from 0 to 1 triggers enabling.
5946 	 * Shouldn't stagger.
5947 	 */
5948 	if (WARN_ON_ONCE(test_and_set_bit(0, &sch->bypass_dsp_claim)))
5949 		return;
5950 
5951 	/*
5952 	 * When a sub-sched bypasses, its tasks are queued on the bypass DSQs of
5953 	 * the nearest non-bypassing ancestor or root. As enable_bypass_dsp() is
5954 	 * called iff @sch is not already bypassed due to an ancestor bypassing,
5955 	 * we can assume that the parent is not bypassing and thus will be the
5956 	 * host of the bypass DSQs.
5957 	 *
5958 	 * While the situation may change in the future, the following
5959 	 * guarantees that the nearest non-bypassing ancestor or root has bypass
5960 	 * dispatch enabled while a descendant is bypassing, which is all that's
5961 	 * required.
5962 	 *
5963 	 * scx_bypass_dsp_enabled() test is used to determine whether to enter
5964 	 * the bypass dispatch handling path from both bypassing and hosting
5965 	 * scheds. Bump enable depth on both @sch and bypass dispatch host.
5966 	 */
5967 	ret = atomic_inc_return(&sch->bypass_dsp_enable_depth);
5968 	WARN_ON_ONCE(ret <= 0);
5969 
5970 	if (host != sch) {
5971 		ret = atomic_inc_return(&host->bypass_dsp_enable_depth);
5972 		WARN_ON_ONCE(ret <= 0);
5973 	}
5974 
5975 	/*
5976 	 * The LB timer will stop running if bypass dispatch is disabled. Start
5977 	 * after enabling bypass dispatch.
5978 	 */
5979 	if (intv_us && !timer_pending(&host->bypass_lb_timer))
5980 		mod_timer(&host->bypass_lb_timer,
5981 			  jiffies + usecs_to_jiffies(intv_us));
5982 }
5983 
5984 /* may be called without holding scx_bypass_lock */
scx_disable_bypass_dsp(struct scx_sched * sch)5985 void scx_disable_bypass_dsp(struct scx_sched *sch)
5986 {
5987 	s32 ret;
5988 
5989 	if (!test_and_clear_bit(0, &sch->bypass_dsp_claim))
5990 		return;
5991 
5992 	ret = atomic_dec_return(&sch->bypass_dsp_enable_depth);
5993 	WARN_ON_ONCE(ret < 0);
5994 
5995 	if (scx_parent(sch)) {
5996 		ret = atomic_dec_return(&scx_parent(sch)->bypass_dsp_enable_depth);
5997 		WARN_ON_ONCE(ret < 0);
5998 	}
5999 }
6000 
6001 /**
6002  * unbypass_renotify_idle - Arm an idle re-notify for a sched leaving bypass
6003  * @rq: rq of the cpu leaving bypass
6004  * @pos: scheduler that just left bypass on @rq's cpu
6005  * @pcpu: @pos's per-cpu state for @rq's cpu
6006  *
6007  * A sched leaving bypass is owed the ops.update_idle() calls suppressed while
6008  * bypassing. A cpu that goes idle during the bypass window and stays idle won't
6009  * produce a notification. Arm a re-notify that scx_bypass()'s resched flushes
6010  * on the next idle pick.
6011  *
6012  * An acute case is ops.sub_attach(). If the parent grants the child cids while
6013  * attaching, when attach is complete and bypass is lifted, the child may hold
6014  * idle cids it never saw go idle.
6015  *
6016  * The root is no exception as bypass suppresses its notifications the same way.
6017  * However, the root uses a separate per-rq flag so its re-notify keeps working
6018  * even when !CONFIG_EXT_SUB_SCHED.
6019  */
unbypass_renotify_idle(struct rq * rq,struct scx_sched * pos,struct scx_sched_pcpu * pcpu)6020 static void unbypass_renotify_idle(struct rq *rq, struct scx_sched *pos,
6021 				   struct scx_sched_pcpu *pcpu)
6022 {
6023 	if (!pos->level) {
6024 		rq->scx.flags |= SCX_RQ_ROOT_IDLE_RENOTIFY;
6025 		return;
6026 	}
6027 #ifdef CONFIG_EXT_SUB_SCHED
6028 	pcpu->idle_renotify = true;
6029 	rq->scx.flags |= SCX_RQ_SUB_IDLE_RENOTIFY;
6030 #endif
6031 }
6032 
6033 /**
6034  * scx_bypass - [Un]bypass scx_ops and guarantee forward progress
6035  * @sch: sched to bypass
6036  * @bypass: true for bypass, false for unbypass
6037  *
6038  * Bypassing guarantees that all runnable tasks make forward progress without
6039  * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might
6040  * be held by tasks that the BPF scheduler is forgetting to run, which
6041  * unfortunately also excludes toggling the static branches.
6042  *
6043  * Let's work around by overriding a couple ops and modifying behaviors based on
6044  * the DISABLING state and then cycling the queued tasks through dequeue/enqueue
6045  * to force global FIFO scheduling.
6046  *
6047  * - ops.select_cpu() is ignored and the default select_cpu() is used.
6048  *
6049  * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order.
6050  *   %SCX_OPS_ENQ_LAST is also ignored.
6051  *
6052  * - ops.dispatch() is ignored.
6053  *
6054  * - dispatch_one() does not report %SCX_DSP_PREV on non-zero slice as slice
6055  *   can't be trusted. Whenever a tick triggers, the running task is rotated to
6056  *   the tail of the queue.
6057  *
6058  * - pick_next_task() suppresses zero slice warning.
6059  *
6060  * - scx_kick_cpu() is disabled to avoid irq_work malfunction during PM
6061  *   operations.
6062  *
6063  * - scx_prio_less() reverts to the default runnable_at order.
6064  */
scx_bypass(struct scx_sched * sch,bool bypass)6065 void scx_bypass(struct scx_sched *sch, bool bypass)
6066 {
6067 	struct scx_sched *pos;
6068 	unsigned long flags;
6069 	int cpu;
6070 
6071 	raw_spin_lock_irqsave(&scx_bypass_lock, flags);
6072 
6073 	if (bypass) {
6074 		if (!inc_bypass_depth(sch))
6075 			goto unlock;
6076 
6077 		enable_bypass_dsp(sch);
6078 	} else {
6079 		if (!dec_bypass_depth(sch))
6080 			goto unlock;
6081 	}
6082 
6083 	/*
6084 	 * Bypass state is propagated to all descendants - an scx_sched bypasses
6085 	 * if itself or any of its ancestors are in bypass mode.
6086 	 */
6087 	raw_spin_lock(&scx_sched_lock);
6088 	scx_for_each_descendant_pre(pos, sch) {
6089 		if (pos == sch)
6090 			continue;
6091 		if (bypass)
6092 			inc_bypass_depth(pos);
6093 		else
6094 			dec_bypass_depth(pos);
6095 	}
6096 	raw_spin_unlock(&scx_sched_lock);
6097 
6098 	/*
6099 	 * No task property is changing. We just need to make sure all currently
6100 	 * queued tasks are re-queued according to the new scx_bypassing()
6101 	 * state. As an optimization, walk each rq's runnable_list instead of
6102 	 * the scx_tasks list.
6103 	 *
6104 	 * This function can't trust the scheduler and thus can't use
6105 	 * cpus_read_lock(). Walk all possible CPUs instead of online.
6106 	 */
6107 	for_each_possible_cpu(cpu) {
6108 		struct rq *rq = cpu_rq(cpu);
6109 		struct task_struct *p, *n;
6110 
6111 		raw_spin_rq_lock(rq);
6112 		raw_spin_lock(&scx_sched_lock);
6113 
6114 		scx_for_each_descendant_pre(pos, sch) {
6115 			struct scx_sched_pcpu *pcpu = per_cpu_ptr(pos->pcpu, cpu);
6116 			bool was_bypassing = pcpu->flags & SCX_SCHED_PCPU_BYPASSING;
6117 
6118 			if (pos->bypass_depth) {
6119 				pcpu->flags |= SCX_SCHED_PCPU_BYPASSING;
6120 			} else {
6121 				pcpu->flags &= ~SCX_SCHED_PCPU_BYPASSING;
6122 				if (was_bypassing) {
6123 					unbypass_renotify_idle(rq, pos, pcpu);
6124 					scx_unbypass_replay_ecaps(rq, pos);
6125 				}
6126 			}
6127 		}
6128 
6129 		raw_spin_unlock(&scx_sched_lock);
6130 
6131 		/*
6132 		 * We need to guarantee that no tasks are on the BPF scheduler
6133 		 * while bypassing. Either we see enabled or the enable path
6134 		 * sees scx_bypassing() before moving tasks to SCX.
6135 		 */
6136 		if (!scx_enabled()) {
6137 			scx_rq_lock_drop(rq);
6138 			raw_spin_rq_unlock(rq);
6139 			continue;
6140 		}
6141 
6142 		/*
6143 		 * The use of list_for_each_entry_safe_reverse() is required
6144 		 * because each task is going to be removed from and added back
6145 		 * to the runnable_list during iteration. Because they're added
6146 		 * to the tail of the list, safe reverse iteration can still
6147 		 * visit all nodes.
6148 		 */
6149 		list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list,
6150 						 scx.runnable_node) {
6151 			if (!scx_is_descendant(scx_task_sched(p), sch))
6152 				continue;
6153 
6154 			/*
6155 			 * Bypass trumps protection. Cycling clears for queued
6156 			 * tasks but current task needs explicit stripping.
6157 			 */
6158 			if (bypass && task_current(rq, p))
6159 				scx_task_slice_ended(rq, p);
6160 
6161 			/* cycling deq/enq is enough, see the function comment */
6162 			scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
6163 				/* nothing */ ;
6164 			}
6165 		}
6166 
6167 		/* resched to restore ticks and idle state */
6168 		if (cpu_online(cpu) || cpu == smp_processor_id())
6169 			resched_curr(rq);
6170 
6171 		scx_rq_lock_drop(rq);
6172 		raw_spin_rq_unlock(rq);
6173 	}
6174 
6175 	/* disarming must come after moving all tasks out of the bypass DSQs */
6176 	if (!bypass)
6177 		scx_disable_bypass_dsp(sch);
6178 unlock:
6179 	raw_spin_unlock_irqrestore(&scx_bypass_lock, flags);
6180 }
6181 
free_exit_info(struct scx_exit_info * ei)6182 static void free_exit_info(struct scx_exit_info *ei)
6183 {
6184 	kvfree(ei->dump);
6185 	kfree(ei->msg);
6186 	kfree(ei->bt);
6187 	kfree(ei);
6188 }
6189 
alloc_exit_info(size_t exit_dump_len)6190 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
6191 {
6192 	struct scx_exit_info *ei;
6193 
6194 	ei = kzalloc_obj(*ei);
6195 	if (!ei)
6196 		return NULL;
6197 
6198 	ei->exit_cpu = -1;
6199 	ei->bt = kzalloc_objs(ei->bt[0], SCX_EXIT_BT_LEN);
6200 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
6201 	ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL);
6202 
6203 	if (!ei->bt || !ei->msg || !ei->dump) {
6204 		free_exit_info(ei);
6205 		return NULL;
6206 	}
6207 
6208 	return ei;
6209 }
6210 
scx_exit_reason(enum scx_exit_kind kind)6211 static const char *scx_exit_reason(enum scx_exit_kind kind)
6212 {
6213 	switch (kind) {
6214 	case SCX_EXIT_UNREG:
6215 		return "unregistered from user space";
6216 	case SCX_EXIT_UNREG_BPF:
6217 		return "unregistered from BPF";
6218 	case SCX_EXIT_UNREG_KERN:
6219 		return "unregistered from the main kernel";
6220 	case SCX_EXIT_SYSRQ:
6221 		return "disabled by sysrq-S";
6222 	case SCX_EXIT_PARENT:
6223 		return "parent exiting";
6224 	case SCX_EXIT_PARENT_KILL:
6225 		return "killed by parent scheduler";
6226 	case SCX_EXIT_ERROR:
6227 		return "runtime error";
6228 	case SCX_EXIT_ERROR_BPF:
6229 		return "scx_bpf_error";
6230 	case SCX_EXIT_ERROR_STALL:
6231 		return "runnable task stall";
6232 	case SCX_EXIT_ERROR_REENQ:
6233 		return "reenqueue limit";
6234 	case SCX_EXIT_ERROR_RESCUE:
6235 		return "rescue bandwidth overload";
6236 	default:
6237 		return "<UNKNOWN>";
6238 	}
6239 }
6240 
free_kick_syncs(void)6241 static void free_kick_syncs(void)
6242 {
6243 	int cpu;
6244 
6245 	for_each_possible_cpu(cpu) {
6246 		struct scx_kick_syncs __rcu **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
6247 		struct scx_kick_syncs *to_free;
6248 
6249 		/* flush the pending kick before freeing @ksyncs */
6250 		irq_work_sync(&cpu_rq(cpu)->scx.kick_cpus_irq_work);
6251 		to_free = rcu_replace_pointer(*ksyncs, NULL, true);
6252 		if (to_free)
6253 			kvfree_rcu(to_free, rcu);
6254 	}
6255 }
6256 
refresh_watchdog(void)6257 static void refresh_watchdog(void)
6258 {
6259 	struct scx_sched *sch;
6260 	unsigned long intv = ULONG_MAX;
6261 
6262 	/* take the shortest timeout and use its half for watchdog interval */
6263 	rcu_read_lock();
6264 	list_for_each_entry_rcu(sch, &scx_sched_all, all)
6265 		intv = max(min(intv, sch->watchdog_timeout / 2), 1);
6266 	rcu_read_unlock();
6267 
6268 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
6269 	WRITE_ONCE(scx_watchdog_interval, intv);
6270 
6271 	if (intv < ULONG_MAX)
6272 		mod_delayed_work(system_dfl_wq, &scx_watchdog_work, intv);
6273 	else
6274 		cancel_delayed_work_sync(&scx_watchdog_work);
6275 }
6276 
scx_link_sched(struct scx_sched * sch)6277 s32 scx_link_sched(struct scx_sched *sch)
6278 {
6279 	scoped_guard(raw_spinlock_irqsave, &scx_bypass_lock)	/* for the parent bypass check */
6280 	scoped_guard(raw_spinlock, &scx_sched_lock) {
6281 #ifdef CONFIG_EXT_SUB_SCHED
6282 		struct scx_sched *parent = scx_parent(sch);
6283 
6284 		if (parent) {
6285 			s32 ret;
6286 
6287 			/*
6288 			 * Bypass state is spread across per-cpu flags and a
6289 			 * depth count, so inheriting it is tricky and has no
6290 			 * valid use case. Refuse it.
6291 			 */
6292 			if (READ_ONCE(parent->bypass_depth)) {
6293 				scx_error(sch, "parent bypassing (%d)", -EBUSY);
6294 				return -EBUSY;
6295 			}
6296 
6297 			ret = rhashtable_lookup_insert_fast(&scx_sched_hash,
6298 					&sch->hash_node, scx_sched_hash_params);
6299 			if (ret) {
6300 				scx_error(sch, "failed to insert into scx_sched_hash (%d)",
6301 					  ret);
6302 				return ret;
6303 			}
6304 
6305 			list_add_tail_rcu(&sch->sibling, &parent->children);
6306 
6307 			/*
6308 			 * Pairs with the mb after the ->aborting assertion in
6309 			 * scx_claim_exit(). Either we see ->aborting and back
6310 			 * out, or the exit path sees us and exits us.
6311 			 */
6312 			smp_mb();
6313 			if (unlikely(READ_ONCE(parent->aborting))) {
6314 				rhashtable_remove_fast(&scx_sched_hash, &sch->hash_node,
6315 						       scx_sched_hash_params);
6316 				list_del_rcu(&sch->sibling);
6317 				scx_error(sch, "parent disabled (%d)", -ENOENT);
6318 				return -ENOENT;
6319 			}
6320 
6321 			sch->linked = true;
6322 		}
6323 #endif	/* CONFIG_EXT_SUB_SCHED */
6324 
6325 		list_add_tail_rcu(&sch->all, &scx_sched_all);
6326 	}
6327 
6328 	refresh_watchdog();
6329 	return 0;
6330 }
6331 
scx_unlink_sched(struct scx_sched * sch)6332 void scx_unlink_sched(struct scx_sched *sch)
6333 {
6334 	scoped_guard(raw_spinlock_irq, &scx_sched_lock) {
6335 #ifdef CONFIG_EXT_SUB_SCHED
6336 		if (sch->linked) {
6337 			rhashtable_remove_fast(&scx_sched_hash, &sch->hash_node,
6338 					       scx_sched_hash_params);
6339 			list_del_rcu(&sch->sibling);
6340 			sch->linked = false;
6341 		}
6342 #endif	/* CONFIG_EXT_SUB_SCHED */
6343 		list_del_rcu(&sch->all);
6344 	}
6345 
6346 	refresh_watchdog();
6347 }
6348 
6349 /*
6350  * Called to disable future dumps and wait for in-progress one while disabling
6351  * @sch. Once @sch becomes empty during disable, there's no point in dumping it.
6352  * This prevents calling dump ops on a dead sch.
6353  */
scx_disable_dump(struct scx_sched * sch)6354 void scx_disable_dump(struct scx_sched *sch)
6355 {
6356 	guard(raw_spinlock_irqsave)(&scx_dump_lock);
6357 	sch->dump_disabled = true;
6358 }
6359 
scx_log_sched_disable(struct scx_sched * sch)6360 void scx_log_sched_disable(struct scx_sched *sch)
6361 {
6362 	struct scx_exit_info *ei = sch->exit_info;
6363 	const char *type = scx_parent(sch) ? "sub-scheduler" : "scheduler";
6364 
6365 	if (ei->kind >= SCX_EXIT_ERROR) {
6366 		pr_err("sched_ext: BPF %s \"%s\" disabled (%s)\n", type,
6367 		       sch->ops.name, ei->reason);
6368 
6369 		if (ei->msg[0] != '\0')
6370 			pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg);
6371 #ifdef CONFIG_STACKTRACE
6372 		stack_trace_print(ei->bt, ei->bt_len, 2);
6373 #endif
6374 	} else {
6375 		pr_info("sched_ext: BPF %s \"%s\" disabled (%s)\n", type,
6376 			sch->ops.name, ei->reason);
6377 	}
6378 }
6379 
scx_root_disable(struct scx_sched * sch)6380 static void scx_root_disable(struct scx_sched *sch)
6381 {
6382 	struct scx_task_iter sti;
6383 	struct task_struct *p;
6384 	bool was_switched_all;
6385 	int cpu;
6386 
6387 	/* guarantee forward progress and wait for descendants to be disabled */
6388 	scx_bypass(sch, true);
6389 	drain_descendants(sch);
6390 
6391 	switch (scx_set_enable_state(SCX_DISABLING)) {
6392 	case SCX_DISABLING:
6393 		WARN_ONCE(true, "sched_ext: duplicate disabling instance?");
6394 		break;
6395 	case SCX_DISABLED:
6396 		pr_warn("sched_ext: ops error detected without ops (%s)\n",
6397 			sch->exit_info->msg);
6398 		WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
6399 		goto done;
6400 	default:
6401 		break;
6402 	}
6403 
6404 	/*
6405 	 * Here, every runnable task is guaranteed to make forward progress and
6406 	 * we can safely use blocking synchronization constructs. Actually
6407 	 * disable ops.
6408 	 */
6409 	mutex_lock(&scx_enable_mutex);
6410 
6411 	was_switched_all = scx_switched_all();
6412 
6413 	static_branch_disable(&__scx_switched_all);
6414 	WRITE_ONCE(scx_switching_all, false);
6415 
6416 	/*
6417 	 * Shut down cgroup support before tasks so that the cgroup attach and
6418 	 * migration paths don't race against scx_disable_and_exit_task().
6419 	 */
6420 	scx_cgroup_lock();
6421 	scx_cgroup_enabled = false;
6422 	scx_cgroup_exit(sch);
6423 	scx_cgroup_unlock();
6424 
6425 	/*
6426 	 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones
6427 	 * must be switched out and exited synchronously.
6428 	 */
6429 	percpu_down_write(&scx_fork_rwsem);
6430 
6431 	scx_init_task_enabled = false;
6432 
6433 	scx_task_iter_start(&sti, NULL);
6434 	while ((p = scx_task_iter_next_locked(&sti))) {
6435 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
6436 		const struct sched_class *old_class = p->sched_class;
6437 		const struct sched_class *new_class = scx_setscheduler_class(p);
6438 
6439 		update_rq_clock(task_rq(p));
6440 
6441 		if (old_class != new_class)
6442 			queue_flags |= DEQUEUE_CLASS;
6443 
6444 		scoped_guard (sched_change, p, queue_flags) {
6445 			p->sched_class = new_class;
6446 		}
6447 
6448 		scx_disable_and_exit_task(scx_task_sched(p), p);
6449 	}
6450 	scx_task_iter_stop(&sti);
6451 
6452 	scx_disable_dump(sch);
6453 
6454 	scx_cgroup_lock();
6455 	set_cgroup_sched(sch_cgroup(sch), NULL);
6456 	scx_cgroup_unlock();
6457 
6458 	percpu_up_write(&scx_fork_rwsem);
6459 
6460 	/*
6461 	 * Re-balance the dl_server bandwidth reservations: detach ext_server
6462 	 * (no more sched_ext tasks) and reinstate fair_server if it was
6463 	 * previously detached because we were running in full mode.
6464 	 *
6465 	 * Unlike the enable path, this runs on a recovery path that cannot
6466 	 * fail, so we use dl_server_swap_bw() to atomically free ext_server's
6467 	 * bandwidth and reclaim it for fair_server under the same dl_b lock.
6468 	 *
6469 	 * The swap can still fail with -EBUSY if someone bumped ext_server's
6470 	 * runtime via debugfs between enable and disable; in that narrow case
6471 	 * both servers end up detached and we just WARN.
6472 	 */
6473 	for_each_possible_cpu(cpu) {
6474 		struct rq *rq = cpu_rq(cpu);
6475 
6476 		scoped_guard(rq_lock_irqsave, rq) {
6477 			update_rq_clock(rq);
6478 			if (was_switched_all) {
6479 				if (WARN_ON_ONCE(dl_server_swap_bw(&rq->ext_server,
6480 								   &rq->fair_server)))
6481 					pr_warn("failed to re-attach fair_server on CPU %d\n", cpu);
6482 			} else {
6483 				dl_server_detach_bw(&rq->ext_server);
6484 			}
6485 		}
6486 	}
6487 
6488 	/* no task is on scx, turn off all the switches and flush in-progress calls */
6489 	static_branch_disable(&__scx_enabled);
6490 	static_branch_disable(&__scx_is_cid_type);
6491 	if (sch->ops.flags & SCX_OPS_TID_TO_TASK)
6492 		static_branch_disable(&__scx_tid_to_task_enabled);
6493 	bitmap_zero(sch->has_op, SCX_OPI_END);
6494 	scx_idle_disable();
6495 	synchronize_rcu();
6496 	if (sch->ops.flags & SCX_OPS_TID_TO_TASK)
6497 		rhashtable_free_and_destroy(&scx_tid_hash, NULL, NULL);
6498 
6499 	scx_log_sched_disable(sch);
6500 
6501 	if (sch->ops.exit)
6502 		SCX_CALL_OP(sch, exit, NULL, sch->exit_info);
6503 
6504 	/*
6505 	 * @sch's non-ops programs such as timers and tracers can fire after
6506 	 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from
6507 	 * resolving to @sch and drain in-flight resolvers.
6508 	 */
6509 	WRITE_ONCE(sch->dead, true);
6510 	synchronize_rcu();
6511 
6512 	scx_unlink_sched(sch);
6513 
6514 	/*
6515 	 * scx_root clearing and cid table retirement must be inside
6516 	 * cpus_read_lock(). See handle_hotplug().
6517 	 */
6518 	cpus_read_lock();
6519 	RCU_INIT_POINTER(scx_root, NULL);
6520 	scx_cid_retire_tables();
6521 	cpus_read_unlock();
6522 
6523 	/*
6524 	 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs
6525 	 * could observe an object of the same name still in the hierarchy when
6526 	 * the next scheduler is loaded.
6527 	 */
6528 #ifdef CONFIG_EXT_SUB_SCHED
6529 	if (sch->sub_kset)
6530 		kobject_del(&sch->sub_kset->kobj);
6531 #endif
6532 	/* not added if enable failed before scx_sched_sysfs_add() */
6533 	if (sch->kobj.state_in_sysfs)
6534 		kobject_del(&sch->kobj);
6535 
6536 	free_kick_syncs();
6537 
6538 	mutex_unlock(&scx_enable_mutex);
6539 
6540 	WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
6541 done:
6542 	scx_bypass(sch, false);
6543 }
6544 
6545 /**
6546  * scx_propagate_exit_irq_workfn - Claim SCX_EXIT_PARENT on the exiting subtree
6547  * @irq_work: &scx_sched.propagate_exit_irq_work
6548  *
6549  * Queued by scx_claim_exit() after a non-PARENT claim. Claims SCX_EXIT_PARENT
6550  * on each descendant, giving every one its own disable work - most of disabling
6551  * is serialized but ops.exit() can take arbitrarily long and running them in
6552  * separate helper kthreads parallelizes it. No recursion as only non-PARENT
6553  * claims propagate.
6554  */
scx_propagate_exit_irq_workfn(struct irq_work * irq_work)6555 static void scx_propagate_exit_irq_workfn(struct irq_work *irq_work)
6556 {
6557 	struct scx_sched *sch = container_of(irq_work, struct scx_sched,
6558 					     propagate_exit_irq_work);
6559 	struct scx_sched *pos;
6560 
6561 	scoped_guard (raw_spinlock_irqsave, &scx_sched_lock) {
6562 		scx_for_each_descendant_pre(pos, sch)
6563 			scx_disable(pos, SCX_EXIT_PARENT);
6564 	}
6565 }
6566 
6567 /*
6568  * Claim the exit on @sch. The caller must ensure that the helper kthread work
6569  * is kicked before the current task can be preempted. Once exit_kind is
6570  * claimed, scx_error() can no longer trigger, so if the current task gets
6571  * preempted and the BPF scheduler fails to schedule it back, the helper work
6572  * will never be kicked and the whole system can wedge.
6573  *
6574  * Lock-free and safe to call from any context including NMI.
6575  */
scx_claim_exit(struct scx_sched * sch,enum scx_exit_kind kind)6576 static bool scx_claim_exit(struct scx_sched *sch, enum scx_exit_kind kind)
6577 {
6578 	int none = SCX_EXIT_NONE;
6579 
6580 	lockdep_assert_preemption_disabled();
6581 
6582 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
6583 		kind = SCX_EXIT_ERROR;
6584 
6585 	if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind))
6586 		return false;
6587 
6588 	if (kind == SCX_EXIT_PARENT) {
6589 		/* an ancestor is already sweeping the subtree */
6590 		WRITE_ONCE(sch->aborting, true);
6591 	} else {
6592 		struct scx_sched *pos;
6593 
6594 		/*
6595 		 * CPUs may be live-locked in the dispatch paths of @sch or its
6596 		 * descendants, which ->aborting breaks. Sweep the subtree
6597 		 * locklessly so that this works from NMI. smp_store_mb() orders
6598 		 * each node's ->aborting store before its children are walked -
6599 		 * either we see a racing scx_link_sched() on ->children or it
6600 		 * sees ->aborting.
6601 		 */
6602 		scoped_guard (rcu) {
6603 			scx_for_each_descendant_pre(pos, sch)
6604 				smp_store_mb(pos->aborting, true);
6605 		}
6606 
6607 		irq_work_queue(&sch->propagate_exit_irq_work);
6608 	}
6609 
6610 	/* fired after ->aborting is set so callbacks can't delay recovery */
6611 	trace_sched_ext_exit(sch, kind);
6612 
6613 	return true;
6614 }
6615 
scx_disable_workfn(struct kthread_work * work)6616 static void scx_disable_workfn(struct kthread_work *work)
6617 {
6618 	struct scx_sched *sch = container_of(work, struct scx_sched, disable_work);
6619 	struct scx_exit_info *ei = sch->exit_info;
6620 	int kind;
6621 
6622 	kind = atomic_read(&sch->exit_kind);
6623 	while (true) {
6624 		if (kind == SCX_EXIT_DONE)	/* already disabled? */
6625 			return;
6626 		WARN_ON_ONCE(kind == SCX_EXIT_NONE);
6627 		if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE))
6628 			break;
6629 	}
6630 	ei->kind = kind;
6631 	ei->reason = scx_exit_reason(ei->kind);
6632 
6633 	if (scx_parent(sch))
6634 		scx_sub_disable(sch);
6635 	else
6636 		scx_root_disable(sch);
6637 }
6638 
scx_disable(struct scx_sched * sch,enum scx_exit_kind kind)6639 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind)
6640 {
6641 	guard(preempt)();
6642 	if (scx_claim_exit(sch, kind))
6643 		irq_work_queue(&sch->disable_irq_work);
6644 }
6645 
6646 /**
6647  * scx_flush_disable_work - flush the disable work and wait for it to finish
6648  * @sch: the scheduler
6649  *
6650  * sch->disable_work might still not queued, causing kthread_flush_work()
6651  * as a noop. Syncing the irq_work first is required to guarantee the
6652  * kthread work has been queued before waiting for it.
6653  */
scx_flush_disable_work(struct scx_sched * sch)6654 void scx_flush_disable_work(struct scx_sched *sch)
6655 {
6656 	int kind;
6657 
6658 	do {
6659 		irq_work_sync(&sch->disable_irq_work);
6660 		kthread_flush_work(&sch->disable_work);
6661 		kind = atomic_read(&sch->exit_kind);
6662 	} while (kind != SCX_EXIT_NONE && kind != SCX_EXIT_DONE);
6663 }
6664 
dump_newline(struct seq_buf * s)6665 static void dump_newline(struct seq_buf *s)
6666 {
6667 	trace_sched_ext_dump("");
6668 
6669 	/* @s may be zero sized and seq_buf triggers WARN if so */
6670 	if (s->size)
6671 		seq_buf_putc(s, '\n');
6672 }
6673 
scx_dump_line(struct seq_buf * s,const char * fmt,...)6674 __printf(2, 3) void scx_dump_line(struct seq_buf *s, const char *fmt, ...)
6675 {
6676 	va_list args;
6677 
6678 #ifdef CONFIG_TRACEPOINTS
6679 	if (trace_sched_ext_dump_enabled()) {
6680 		/* protected by scx_dump_lock */
6681 		static char line_buf[SCX_EXIT_MSG_LEN];
6682 
6683 		va_start(args, fmt);
6684 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
6685 		va_end(args);
6686 
6687 		trace_call__sched_ext_dump(line_buf);
6688 	}
6689 #endif
6690 	/* @s may be zero sized and seq_buf triggers WARN if so */
6691 	if (s->size) {
6692 		va_start(args, fmt);
6693 		seq_buf_vprintf(s, fmt, args);
6694 		va_end(args);
6695 
6696 		seq_buf_putc(s, '\n');
6697 	}
6698 }
6699 
dump_stack_trace(struct seq_buf * s,const char * prefix,const unsigned long * bt,unsigned int len)6700 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
6701 			     const unsigned long *bt, unsigned int len)
6702 {
6703 	unsigned int i;
6704 
6705 	for (i = 0; i < len; i++)
6706 		scx_dump_line(s, "%s%pS", prefix, (void *)bt[i]);
6707 }
6708 
ops_dump_init(struct seq_buf * s,const char * prefix)6709 static void ops_dump_init(struct seq_buf *s, const char *prefix)
6710 {
6711 	struct scx_dump_data *dd = &scx_dump_data;
6712 
6713 	lockdep_assert_irqs_disabled();
6714 
6715 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
6716 	dd->first = true;
6717 	dd->cursor = 0;
6718 	dd->s = s;
6719 	dd->prefix = prefix;
6720 }
6721 
ops_dump_flush(void)6722 static void ops_dump_flush(void)
6723 {
6724 	struct scx_dump_data *dd = &scx_dump_data;
6725 	char *line = dd->buf.line;
6726 
6727 	if (!dd->cursor)
6728 		return;
6729 
6730 	/*
6731 	 * There's something to flush and this is the first line. Insert a blank
6732 	 * line to distinguish ops dump.
6733 	 */
6734 	if (dd->first) {
6735 		dump_newline(dd->s);
6736 		dd->first = false;
6737 	}
6738 
6739 	/*
6740 	 * There may be multiple lines in $line. Scan and emit each line
6741 	 * separately.
6742 	 */
6743 	while (true) {
6744 		char *end = line;
6745 		char c;
6746 
6747 		while (*end != '\n' && *end != '\0')
6748 			end++;
6749 
6750 		/*
6751 		 * If $line overflowed, it may not have newline at the end.
6752 		 * Always emit with a newline.
6753 		 */
6754 		c = *end;
6755 		*end = '\0';
6756 		scx_dump_line(dd->s, "%s%s", dd->prefix, line);
6757 		if (c == '\0')
6758 			break;
6759 
6760 		/* move to the next line */
6761 		end++;
6762 		if (*end == '\0')
6763 			break;
6764 		line = end;
6765 	}
6766 
6767 	dd->cursor = 0;
6768 }
6769 
ops_dump_exit(void)6770 static void ops_dump_exit(void)
6771 {
6772 	ops_dump_flush();
6773 	scx_dump_data.cpu = -1;
6774 }
6775 
scx_dump_task(struct scx_sched * sch,struct seq_buf * s,struct scx_dump_ctx * dctx,struct rq * rq,struct task_struct * p,char marker)6776 static void scx_dump_task(struct scx_sched *sch, struct seq_buf *s, struct scx_dump_ctx *dctx,
6777 			  struct rq *rq, struct task_struct *p, char marker)
6778 {
6779 	static unsigned long bt[SCX_EXIT_BT_LEN];
6780 	struct scx_sched *task_sch = scx_task_sched(p);
6781 	const char *own_marker;
6782 	char sch_id_buf[32];
6783 	char dsq_id_buf[19] = "(n/a)";
6784 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
6785 	unsigned int bt_len = 0;
6786 
6787 	own_marker = task_sch == sch ? "*" : "";
6788 
6789 	if (task_sch->level == 0)
6790 		scnprintf(sch_id_buf, sizeof(sch_id_buf), "root");
6791 	else
6792 		scnprintf(sch_id_buf, sizeof(sch_id_buf), "sub%d-%llu",
6793 			  task_sch->level, task_sch->ops.sub_cgroup_id);
6794 
6795 	if (p->scx.dsq)
6796 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
6797 			  (unsigned long long)p->scx.dsq->id);
6798 
6799 	dump_newline(s);
6800 	scx_dump_line(s, " %c%c %s[%d] %s%s %+ldms",
6801 		      marker, task_state_to_char(p), p->comm, p->pid, own_marker, sch_id_buf,
6802 		      jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
6803 	scx_dump_line(s, "      scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu",
6804 		      scx_get_task_state(p) >> SCX_TASK_STATE_SHIFT,
6805 		      p->scx.flags & ~SCX_TASK_STATE_MASK, p->scx.dsq_flags,
6806 		      ops_state & SCX_OPSS_STATE_MASK, ops_state >> SCX_OPSS_QSEQ_SHIFT);
6807 	scx_dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
6808 		      p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
6809 	scx_dump_line(s, "      dsq_vtime=%llu slice=%llu weight=%u",
6810 		      p->scx.dsq_vtime, p->scx.slice, p->scx.weight);
6811 	scx_dump_line(s, "      cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr),
6812 		      p->migration_disabled);
6813 
6814 	if (SCX_HAS_OP(sch, dump_task)) {
6815 		ops_dump_init(s, "    ");
6816 		SCX_CALL_OP(sch, dump_task, rq, dctx, p);
6817 		ops_dump_exit();
6818 	}
6819 
6820 #ifdef CONFIG_STACKTRACE
6821 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
6822 #endif
6823 	if (bt_len) {
6824 		dump_newline(s);
6825 		dump_stack_trace(s, "    ", bt, bt_len);
6826 	}
6827 }
6828 
scx_dump_cpu(struct scx_sched * sch,struct seq_buf * s,struct scx_dump_ctx * dctx,int cpu,bool dump_all_tasks)6829 static void scx_dump_cpu(struct scx_sched *sch, struct seq_buf *s,
6830 			 struct scx_dump_ctx *dctx, int cpu,
6831 			 bool dump_all_tasks)
6832 {
6833 	struct rq *rq = cpu_rq(cpu);
6834 	struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
6835 	struct rq_flags rf;
6836 	struct task_struct *p;
6837 	struct seq_buf ns;
6838 	size_t avail, used;
6839 	char *buf;
6840 	bool idle;
6841 
6842 	rq_lock_irqsave(rq, &rf);
6843 
6844 	idle = list_empty(&rq->scx.runnable_list) &&
6845 		rq->curr->sched_class == &idle_sched_class;
6846 
6847 	if (idle && !SCX_HAS_OP(sch, dump_cpu))
6848 		goto next;
6849 
6850 	/*
6851 	 * We don't yet know whether ops.dump_cpu() will produce output
6852 	 * and we may want to skip the default CPU dump if it doesn't.
6853 	 * Use a nested seq_buf to generate the standard dump so that we
6854 	 * can decide whether to commit later.
6855 	 */
6856 	avail = seq_buf_get_buf(s, &buf);
6857 	seq_buf_init(&ns, buf, avail);
6858 
6859 	dump_newline(&ns);
6860 	scx_dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu ksync=%lu",
6861 		      cpu, rq->scx.nr_running, rq->scx.flags, rq->scx.cpu_released,
6862 		      rq->scx.ops_qseq, rq->scx.kick_sync);
6863 	scx_rescue_dump(&ns, rq);
6864 	scx_dump_line(&ns, "          curr=%s[%d] class=%ps",
6865 		      rq->curr->comm, rq->curr->pid, rq->curr->sched_class);
6866 	if (!cpumask_empty(pcpu->cpus_to_kick))
6867 		scx_dump_line(&ns, "  cpus_to_kick   : %*pb",
6868 			      cpumask_pr_args(pcpu->cpus_to_kick));
6869 	if (!cpumask_empty(pcpu->cpus_to_kick_if_idle))
6870 		scx_dump_line(&ns, "  idle_to_kick   : %*pb",
6871 			      cpumask_pr_args(pcpu->cpus_to_kick_if_idle));
6872 	if (!cpumask_empty(pcpu->cpus_to_preempt))
6873 		scx_dump_line(&ns, "  cpus_to_preempt: %*pb",
6874 			      cpumask_pr_args(pcpu->cpus_to_preempt));
6875 	if (!cpumask_empty(pcpu->cpus_to_wait))
6876 		scx_dump_line(&ns, "  cpus_to_wait   : %*pb",
6877 			      cpumask_pr_args(pcpu->cpus_to_wait));
6878 	if (!cpumask_empty(rq->scx.cpus_to_sync))
6879 		scx_dump_line(&ns, "  cpus_to_sync   : %*pb",
6880 			      cpumask_pr_args(rq->scx.cpus_to_sync));
6881 
6882 	used = seq_buf_used(&ns);
6883 	if (SCX_HAS_OP(sch, dump_cpu)) {
6884 		ops_dump_init(&ns, "  ");
6885 		SCX_CALL_OP(sch, dump_cpu, rq, dctx, scx_cpu_arg(cpu), idle);
6886 		ops_dump_exit();
6887 	}
6888 
6889 	/*
6890 	 * If idle && nothing generated by ops.dump_cpu(), there's
6891 	 * nothing interesting. Skip.
6892 	 */
6893 	if (idle && used == seq_buf_used(&ns))
6894 		goto next;
6895 
6896 	/*
6897 	 * $s may already have overflowed when $ns was created. If so,
6898 	 * calling commit on it will trigger BUG.
6899 	 */
6900 	if (avail) {
6901 		seq_buf_commit(s, seq_buf_used(&ns));
6902 		if (seq_buf_has_overflowed(&ns))
6903 			seq_buf_set_overflow(s);
6904 	}
6905 
6906 	if (rq->curr->sched_class == &ext_sched_class &&
6907 	    (dump_all_tasks || scx_task_on_sched(sch, rq->curr)))
6908 		scx_dump_task(sch, s, dctx, rq, rq->curr, '*');
6909 
6910 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
6911 		if (dump_all_tasks || scx_task_on_sched(sch, p))
6912 			scx_dump_task(sch, s, dctx, rq, p, ' ');
6913 next:
6914 	rq_unlock_irqrestore(rq, &rf);
6915 }
6916 
6917 /*
6918  * Dump scheduler state. If @dump_all_tasks is true, dump all tasks regardless
6919  * of which scheduler they belong to. If false, only dump tasks owned by @sch.
6920  * For SysRq-D dumps, @dump_all_tasks=false since all schedulers are dumped
6921  * separately. For error dumps, @dump_all_tasks=true since only the failing
6922  * scheduler is dumped.
6923  */
scx_dump_state(struct scx_sched * sch,struct scx_exit_info * ei,size_t dump_len,bool dump_all_tasks)6924 static void scx_dump_state(struct scx_sched *sch, struct scx_exit_info *ei,
6925 			   size_t dump_len, bool dump_all_tasks)
6926 {
6927 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
6928 	struct scx_dump_ctx dctx = {
6929 		.kind = ei->kind,
6930 		.exit_code = ei->exit_code,
6931 		.reason = ei->reason,
6932 		.at_ns = ktime_get_ns(),
6933 		.at_jiffies = jiffies,
6934 	};
6935 	struct seq_buf s;
6936 	struct scx_event_stats events;
6937 	int cpu;
6938 
6939 	guard(raw_spinlock_irqsave)(&scx_dump_lock);
6940 
6941 	if (sch->dump_disabled)
6942 		return;
6943 
6944 	seq_buf_init(&s, ei->dump, dump_len);
6945 
6946 #ifdef CONFIG_EXT_SUB_SCHED
6947 	if (sch->level == 0)
6948 		scx_dump_line(&s, "%s: root", sch->ops.name);
6949 	else
6950 		scx_dump_line(&s, "%s: sub%d-%llu %s",
6951 			      sch->ops.name, sch->level, sch->ops.sub_cgroup_id,
6952 			      sch->cgrp_path);
6953 #endif
6954 	if (ei->kind == SCX_EXIT_NONE) {
6955 		scx_dump_line(&s, "Debug dump triggered by %s", ei->reason);
6956 	} else {
6957 		if (ei->exit_cpu >= 0)
6958 			scx_dump_line(&s, "%s[%d] triggered exit kind %d on CPU %d:",
6959 				      current->comm, current->pid, ei->kind,
6960 				      ei->exit_cpu);
6961 		else
6962 			scx_dump_line(&s, "%s[%d] triggered exit kind %d:",
6963 				      current->comm, current->pid, ei->kind);
6964 		scx_dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
6965 		dump_newline(&s);
6966 		scx_dump_line(&s, "Backtrace:");
6967 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
6968 	}
6969 
6970 	if (SCX_HAS_OP(sch, dump)) {
6971 		ops_dump_init(&s, "");
6972 		SCX_CALL_OP(sch, dump, NULL, &dctx);
6973 		ops_dump_exit();
6974 	}
6975 
6976 	dump_newline(&s);
6977 	scx_dump_line(&s, "CPU states");
6978 	scx_dump_line(&s, "----------");
6979 
6980 	/*
6981 	 * Dump stalled CPUs first so they aren't lost to dump truncation, then
6982 	 * walk the rest in order. Fall back to exit_cpu if no stall mask set.
6983 	 */
6984 	if (!cpumask_empty(sch->stall_cpus)) {
6985 		for_each_cpu(cpu, sch->stall_cpus)
6986 			scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks);
6987 		for_each_possible_cpu(cpu) {
6988 			if (!cpumask_test_cpu(cpu, sch->stall_cpus))
6989 				scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks);
6990 		}
6991 	} else {
6992 		if (ei->exit_cpu >= 0)
6993 			scx_dump_cpu(sch, &s, &dctx, ei->exit_cpu, dump_all_tasks);
6994 		for_each_possible_cpu(cpu) {
6995 			if (cpu != ei->exit_cpu)
6996 				scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks);
6997 		}
6998 	}
6999 
7000 	dump_newline(&s);
7001 	scx_dump_line(&s, "Event counters");
7002 	scx_dump_line(&s, "--------------");
7003 
7004 	scx_read_events(sch, &events);
7005 #define SCX_EVENT(name)	scx_dump_event(s, &events, name)
7006 	SCX_EVENTS_LIST(SCX_EVENT);
7007 #undef SCX_EVENT
7008 
7009 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
7010 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
7011 		       trunc_marker, sizeof(trunc_marker));
7012 }
7013 
scx_disable_irq_workfn(struct irq_work * irq_work)7014 static void scx_disable_irq_workfn(struct irq_work *irq_work)
7015 {
7016 	struct scx_sched *sch = container_of(irq_work, struct scx_sched, disable_irq_work);
7017 	struct scx_exit_info *ei = sch->exit_info;
7018 
7019 	if (ei->kind >= SCX_EXIT_ERROR)
7020 		scx_dump_state(sch, ei, sch->ops.exit_dump_len, true);
7021 
7022 	kthread_queue_work(sch->helper, &sch->disable_work);
7023 }
7024 
7025 /* finish exit_info and kick the disable work, ei->msg must already be set */
scx_finish_exit(struct scx_sched * sch,enum scx_exit_kind kind,s64 exit_code,s32 exit_cpu)7026 static void scx_finish_exit(struct scx_sched *sch, enum scx_exit_kind kind,
7027 			    s64 exit_code, s32 exit_cpu)
7028 {
7029 	struct scx_exit_info *ei = sch->exit_info;
7030 
7031 	ei->exit_code = exit_code;
7032 #ifdef CONFIG_STACKTRACE
7033 	/*
7034 	 * stack_trace_save()'s NMI-safety is arch-dependent and undocumented.
7035 	 * Skip the backtrace when exiting from NMI.
7036 	 */
7037 	if (kind >= SCX_EXIT_ERROR && !in_nmi())
7038 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
7039 #endif
7040 	/*
7041 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
7042 	 * in scx_disable_workfn().
7043 	 */
7044 	ei->kind = kind;
7045 	ei->reason = scx_exit_reason(ei->kind);
7046 	ei->exit_cpu = exit_cpu;
7047 
7048 	irq_work_queue(&sch->disable_irq_work);
7049 }
7050 
scx_vexit(struct scx_sched * sch,enum scx_exit_kind kind,s64 exit_code,s32 exit_cpu,const char * fmt,va_list args)7051 bool scx_vexit(struct scx_sched *sch,
7052 	       enum scx_exit_kind kind, s64 exit_code, s32 exit_cpu,
7053 	       const char *fmt, va_list args)
7054 {
7055 	struct scx_exit_info *ei = sch->exit_info;
7056 
7057 	guard(preempt)();
7058 
7059 	if (!scx_claim_exit(sch, kind))
7060 		return false;
7061 
7062 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
7063 
7064 	scx_finish_exit(sch, kind, exit_code, exit_cpu);
7065 	return true;
7066 }
7067 
alloc_kick_syncs(void)7068 static int alloc_kick_syncs(void)
7069 {
7070 	int cpu;
7071 
7072 	/*
7073 	 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size
7074 	 * can exceed percpu allocator limits on large machines.
7075 	 */
7076 	for_each_possible_cpu(cpu) {
7077 		struct scx_kick_syncs __rcu **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
7078 		struct scx_kick_syncs *new_ksyncs;
7079 
7080 		WARN_ON_ONCE(rcu_access_pointer(*ksyncs));
7081 
7082 		new_ksyncs = kvzalloc_node(struct_size(new_ksyncs, syncs, nr_cpu_ids),
7083 					   GFP_KERNEL, cpu_to_node(cpu));
7084 		if (!new_ksyncs) {
7085 			free_kick_syncs();
7086 			return -ENOMEM;
7087 		}
7088 
7089 		rcu_assign_pointer(*ksyncs, new_ksyncs);
7090 	}
7091 
7092 	return 0;
7093 }
7094 
free_pnode(struct scx_sched_pnode * pnode)7095 static void free_pnode(struct scx_sched_pnode *pnode)
7096 {
7097 	if (!pnode)
7098 		return;
7099 	exit_dsq(&pnode->global_dsq);
7100 	kfree(pnode);
7101 }
7102 
alloc_pnode(struct scx_sched * sch,int node)7103 static struct scx_sched_pnode *alloc_pnode(struct scx_sched *sch, int node)
7104 {
7105 	struct scx_sched_pnode *pnode;
7106 
7107 	pnode = kzalloc_node(sizeof(*pnode), GFP_KERNEL, node);
7108 	if (!pnode)
7109 		return NULL;
7110 
7111 	if (scx_init_dsq(&pnode->global_dsq, SCX_DSQ_GLOBAL, sch)) {
7112 		kfree(pnode);
7113 		return NULL;
7114 	}
7115 
7116 	return pnode;
7117 }
7118 
7119 /*
7120  * Allocate and initialize a new scx_sched. @cgrp's reference is always
7121  * consumed whether the function succeeds or fails.
7122  */
scx_alloc_and_add_sched(struct scx_enable_cmd * cmd,struct cgroup * cgrp,struct scx_sched * parent)7123 struct scx_sched *scx_alloc_and_add_sched(struct scx_enable_cmd *cmd,
7124 					  struct cgroup *cgrp,
7125 					  struct scx_sched *parent)
7126 {
7127 	struct sched_ext_ops *ops = cmd->ops;
7128 	struct scx_sched *sch;
7129 	s32 level = parent ? parent->level + 1 : 0;
7130 	s32 node, cpu, ret, bypass_fail_cpu = nr_cpu_ids;
7131 
7132 	sch = kzalloc_flex(*sch, ancestors, level + 1);
7133 	if (!sch) {
7134 		ret = -ENOMEM;
7135 		goto err_put_cgrp;
7136 	}
7137 
7138 	sch->exit_info = alloc_exit_info(ops->exit_dump_len);
7139 	if (!sch->exit_info) {
7140 		ret = -ENOMEM;
7141 		goto err_free_sch;
7142 	}
7143 
7144 	ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params);
7145 	if (ret < 0)
7146 		goto err_free_ei;
7147 
7148 	sch->pnode = kzalloc_objs(sch->pnode[0], nr_node_ids);
7149 	if (!sch->pnode) {
7150 		ret = -ENOMEM;
7151 		goto err_free_hash;
7152 	}
7153 
7154 	for_each_node_state(node, N_POSSIBLE) {
7155 		sch->pnode[node] = alloc_pnode(sch, node);
7156 		if (!sch->pnode[node]) {
7157 			ret = -ENOMEM;
7158 			goto err_free_pnode;
7159 		}
7160 	}
7161 
7162 	sch->dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
7163 	sch->pcpu = __alloc_percpu(struct_size_t(struct scx_sched_pcpu,
7164 						 dsp_ctx.buf, sch->dsp_max_batch),
7165 				   __alignof__(struct scx_sched_pcpu));
7166 	if (!sch->pcpu) {
7167 		ret = -ENOMEM;
7168 		goto err_free_pnode;
7169 	}
7170 
7171 	for_each_possible_cpu(cpu) {
7172 		ret = scx_init_dsq(scx_bypass_dsq(sch, cpu), SCX_DSQ_BYPASS, sch);
7173 		if (ret) {
7174 			bypass_fail_cpu = cpu;
7175 			goto err_free_pcpu;
7176 		}
7177 	}
7178 
7179 	for_each_possible_cpu(cpu) {
7180 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
7181 
7182 		node = cpu_to_node(cpu);
7183 		pcpu->sch = sch;
7184 		INIT_LIST_HEAD(&pcpu->deferred_reenq_local.node);
7185 #ifdef CONFIG_EXT_SUB_SCHED
7186 		init_llist_node(&pcpu->ecaps_to_sync_node);
7187 #endif
7188 		INIT_LIST_HEAD(&pcpu->to_kick_node);
7189 		if (!zalloc_cpumask_var_node(&pcpu->cpus_to_kick, GFP_KERNEL, node) ||
7190 		    !zalloc_cpumask_var_node(&pcpu->cpus_to_kick_if_idle, GFP_KERNEL, node) ||
7191 		    !zalloc_cpumask_var_node(&pcpu->cpus_to_preempt, GFP_KERNEL, node) ||
7192 		    !zalloc_cpumask_var_node(&pcpu->cpus_to_wait, GFP_KERNEL, node)) {
7193 			ret = -ENOMEM;
7194 			goto err_free_pcpu;
7195 		}
7196 	}
7197 
7198 	sch->helper = kthread_run_worker(0, "sched_ext_helper");
7199 	if (IS_ERR(sch->helper)) {
7200 		ret = PTR_ERR(sch->helper);
7201 		goto err_free_pcpu;
7202 	}
7203 
7204 	sched_set_fifo(sch->helper->task);
7205 
7206 	if (parent)
7207 		memcpy(sch->ancestors, parent->ancestors,
7208 		       level * sizeof(parent->ancestors[0]));
7209 	sch->ancestors[level] = sch;
7210 	sch->level = level;
7211 	sch->id = atomic64_inc_return(&scx_sched_id_cursor);
7212 
7213 	if (ops->timeout_ms)
7214 		sch->watchdog_timeout = msecs_to_jiffies(ops->timeout_ms);
7215 	else
7216 		sch->watchdog_timeout = SCX_WATCHDOG_MAX_TIMEOUT;
7217 
7218 	sch->slice_dfl = SCX_SLICE_DFL;
7219 	atomic_set(&sch->exit_kind, SCX_EXIT_NONE);
7220 	sch->disable_irq_work = IRQ_WORK_INIT_HARD(scx_disable_irq_workfn);
7221 	sch->propagate_exit_irq_work = IRQ_WORK_INIT_HARD(scx_propagate_exit_irq_workfn);
7222 	kthread_init_work(&sch->disable_work, scx_disable_workfn);
7223 	timer_setup(&sch->bypass_lb_timer, scx_bypass_lb_timerfn, 0);
7224 
7225 	if (!alloc_cpumask_var(&sch->bypass_lb_donee_cpumask, GFP_KERNEL)) {
7226 		ret = -ENOMEM;
7227 		goto err_stop_helper;
7228 	}
7229 	if (!alloc_cpumask_var(&sch->bypass_lb_resched_cpumask, GFP_KERNEL)) {
7230 		ret = -ENOMEM;
7231 		goto err_free_lb_cpumask;
7232 	}
7233 	if (!zalloc_cpumask_var(&sch->stall_cpus, GFP_KERNEL)) {
7234 		ret = -ENOMEM;
7235 		goto err_free_lb_resched_cpumask;
7236 	}
7237 	/*
7238 	 * Copy ops through the right union view. For cid-form the source is
7239 	 * struct sched_ext_ops_cid which lacks the trailing cpu_acquire/
7240 	 * cpu_release; those stay zero from kzalloc.
7241 	 */
7242 	if (cmd->is_cid_type) {
7243 		sch->ops_cid = *cmd->ops_cid;
7244 		sch->is_cid_type = true;
7245 	} else {
7246 		sch->ops = *cmd->ops;
7247 	}
7248 
7249 #ifdef CONFIG_EXT_SUB_SCHED
7250 	char *buf = kzalloc(PATH_MAX, GFP_KERNEL);
7251 	if (!buf) {
7252 		ret = -ENOMEM;
7253 		goto err_free_lb_resched;
7254 	}
7255 	cgroup_path(cgrp, buf, PATH_MAX);
7256 	sch->cgrp_path = kstrdup(buf, GFP_KERNEL);
7257 	kfree(buf);
7258 	if (!sch->cgrp_path) {
7259 		ret = -ENOMEM;
7260 		goto err_free_lb_resched;
7261 	}
7262 
7263 	sch->cgrp = cgrp;
7264 	INIT_LIST_HEAD(&sch->children);
7265 	INIT_LIST_HEAD(&sch->sibling);
7266 #endif	/* CONFIG_EXT_SUB_SCHED */
7267 
7268 	/*
7269 	 * Publishing makes @sch visible to scx_prog_sched() readers. Failure
7270 	 * paths after this point must free @sch through kobject_put() whose
7271 	 * release path defers the actual freeing by an RCU grace period.
7272 	 */
7273 	rcu_assign_pointer(ops->priv, sch);
7274 
7275 	sch->kobj.kset = scx_kset;
7276 	INIT_LIST_HEAD(&sch->all);
7277 
7278 #ifdef CONFIG_EXT_SUB_SCHED
7279 	if (parent) {
7280 		/*
7281 		 * Pin @parent for @sch's lifetime. The kobject hierarchy pins
7282 		 * it only via @parent->sub_kset, which is dropped during
7283 		 * disable. Released in scx_sched_free_rcu_work().
7284 		 */
7285 		kobject_get(&parent->kobj);
7286 	}
7287 #endif	/* CONFIG_EXT_SUB_SCHED */
7288 
7289 	/*
7290 	 * Init the kobj but don't add to sysfs yet. The enable path calls
7291 	 * scx_sched_sysfs_add() once @sch's sysfs-visible state is initialized.
7292 	 */
7293 	kobject_init(&sch->kobj, &scx_ktype);
7294 
7295 	/*
7296 	 * Consume the arena_map ref bpf_scx_reg_cid() took. Defer to here so
7297 	 * earlier failure paths leave cmd->arena_map set and bpf_scx_reg_cid
7298 	 * drops the ref. After this point, sch owns the ref and any cleanup
7299 	 * runs through scx_sched_free_rcu_work() which puts it.
7300 	 */
7301 	sch->arena_map = cmd->arena_map;
7302 	/* BPF arena is only available on MMU && 64BIT */
7303 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
7304 	if (sch->arena_map)
7305 		sch->arena_kern_base = bpf_arena_map_kern_vm_start(sch->arena_map);
7306 #endif
7307 	cmd->arena_map = NULL;
7308 	return sch;
7309 
7310 #ifdef CONFIG_EXT_SUB_SCHED
7311 err_free_lb_resched:
7312 	free_cpumask_var(sch->stall_cpus);
7313 #endif
7314 err_free_lb_resched_cpumask:
7315 	free_cpumask_var(sch->bypass_lb_resched_cpumask);
7316 err_free_lb_cpumask:
7317 	free_cpumask_var(sch->bypass_lb_donee_cpumask);
7318 err_stop_helper:
7319 	kthread_destroy_worker(sch->helper);
7320 err_free_pcpu:
7321 	for_each_possible_cpu(cpu) {
7322 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
7323 
7324 		free_cpumask_var(pcpu->cpus_to_kick);
7325 		free_cpumask_var(pcpu->cpus_to_kick_if_idle);
7326 		free_cpumask_var(pcpu->cpus_to_preempt);
7327 		free_cpumask_var(pcpu->cpus_to_wait);
7328 	}
7329 	for_each_possible_cpu(cpu) {
7330 		if (cpu == bypass_fail_cpu)
7331 			break;
7332 		exit_dsq(scx_bypass_dsq(sch, cpu));
7333 	}
7334 	free_percpu(sch->pcpu);
7335 err_free_pnode:
7336 	for_each_node_state(node, N_POSSIBLE)
7337 		free_pnode(sch->pnode[node]);
7338 	kfree(sch->pnode);
7339 err_free_hash:
7340 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
7341 err_free_ei:
7342 	free_exit_info(sch->exit_info);
7343 err_free_sch:
7344 	kfree(sch);
7345 err_put_cgrp:
7346 #ifdef CONFIG_EXT_SUB_SCHED
7347 	cgroup_put(cgrp);
7348 #endif
7349 	return ERR_PTR(ret);
7350 }
7351 
7352 /*
7353  * Add @sch's kobject to sysfs, and create its sub_kset if the scheduler
7354  * implements ops.sub_attach. Called by the enable workfns once @sch's
7355  * sysfs-visible state is initialized.
7356  */
scx_sched_sysfs_add(struct scx_sched * sch)7357 int scx_sched_sysfs_add(struct scx_sched *sch)
7358 {
7359 #ifdef CONFIG_EXT_SUB_SCHED
7360 	struct scx_sched *parent = scx_parent(sch);
7361 	int ret;
7362 
7363 	if (parent)
7364 		ret = kobject_add(&sch->kobj, &parent->sub_kset->kobj,
7365 				  "sub-%llu", cgroup_id(sch_cgroup(sch)));
7366 	else
7367 		ret = kobject_add(&sch->kobj, NULL, "root");
7368 	if (ret < 0)
7369 		return ret;
7370 
7371 	if (sch->ops.sub_attach) {
7372 		sch->sub_kset = kset_create_and_add("sub", NULL, &sch->kobj);
7373 		if (!sch->sub_kset)
7374 			return -ENOMEM;
7375 	}
7376 	return 0;
7377 #else
7378 	return kobject_add(&sch->kobj, NULL, "root");
7379 #endif
7380 }
7381 
check_hotplug_seq(struct scx_sched * sch,const struct sched_ext_ops * ops)7382 static int check_hotplug_seq(struct scx_sched *sch,
7383 			      const struct sched_ext_ops *ops)
7384 {
7385 	unsigned long long global_hotplug_seq;
7386 
7387 	/*
7388 	 * If a hotplug event has occurred between when a scheduler was
7389 	 * initialized, and when we were able to attach, exit and notify user
7390 	 * space about it.
7391 	 */
7392 	if (ops->hotplug_seq) {
7393 		global_hotplug_seq = atomic_long_read(&scx_hotplug_seq);
7394 		if (ops->hotplug_seq != global_hotplug_seq) {
7395 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
7396 				 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
7397 				 "expected hotplug seq %llu did not match actual %llu",
7398 				 ops->hotplug_seq, global_hotplug_seq);
7399 			return -EBUSY;
7400 		}
7401 	}
7402 
7403 	return 0;
7404 }
7405 
scx_validate_ops(struct scx_sched * sch,const struct sched_ext_ops * ops)7406 int scx_validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
7407 {
7408 	/*
7409 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
7410 	 * ops.enqueue() callback isn't implemented.
7411 	 */
7412 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
7413 		scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
7414 		return -EINVAL;
7415 	}
7416 
7417 	/*
7418 	 * SCX_OPS_TID_TO_TASK is enabled by the root scheduler. A sub-sched
7419 	 * may set it to declare a dependency; reject if the root hasn't
7420 	 * enabled it.
7421 	 */
7422 	if ((ops->flags & SCX_OPS_TID_TO_TASK) && scx_parent(sch) &&
7423 	    !(sch->ancestors[0]->ops.flags & SCX_OPS_TID_TO_TASK)) {
7424 		scx_error(sch, "SCX_OPS_TID_TO_TASK requires root scheduler to enable it");
7425 		return -EINVAL;
7426 	}
7427 
7428 	/*
7429 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle
7430 	 * selection policy to be enabled.
7431 	 */
7432 	if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) &&
7433 	    (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) {
7434 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled");
7435 		return -EINVAL;
7436 	}
7437 
7438 	/*
7439 	 * cid-form's struct is shorter and doesn't include the cpu_acquire /
7440 	 * cpu_release tail; reading those fields off a cid-form @ops would
7441 	 * run past the BPF allocation. Skip for cid-form.
7442 	 */
7443 	if (!sch->is_cid_type && (ops->cpu_acquire || ops->cpu_release))
7444 		pr_warn_ratelimited("ops->cpu_acquire/release() are deprecated, use sched_switch TP instead\n");
7445 
7446 	/*
7447 	 * Sub-scheduler support is tied to the cid-form struct_ops. A sub-sched
7448 	 * attaches through a cid-form-only interface (sub_attach/sub_detach),
7449 	 * and a root that accepts sub-scheds must expose cid-form state to
7450 	 * them. Reject cpu-form schedulers on either side.
7451 	 */
7452 	if (!sch->is_cid_type) {
7453 		if (scx_parent(sch)) {
7454 			scx_error(sch, "sub-sched requires cid-form struct_ops");
7455 			return -EINVAL;
7456 		}
7457 		if (ops->sub_attach || ops->sub_detach) {
7458 			scx_error(sch, "sub_attach/sub_detach requires cid-form struct_ops");
7459 			return -EINVAL;
7460 		}
7461 	}
7462 
7463 	return 0;
7464 }
7465 
scx_root_enable_workfn(struct kthread_work * work)7466 static void scx_root_enable_workfn(struct kthread_work *work)
7467 {
7468 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
7469 	struct sched_ext_ops *ops = cmd->ops;
7470 	struct cgroup *cgrp = root_cgroup();
7471 	struct scx_sched *sch;
7472 	struct scx_task_iter sti;
7473 	struct task_struct *p;
7474 	int i, cpu, ret;
7475 
7476 	mutex_lock(&scx_enable_mutex);
7477 
7478 	if (scx_enable_state() != SCX_DISABLED) {
7479 		ret = -EBUSY;
7480 		goto err_unlock;
7481 	}
7482 
7483 	/*
7484 	 * @ops->priv binds @ops to its scx_sched instance. It is set here by
7485 	 * scx_alloc_and_add_sched() and cleared at the tail of bpf_scx_unreg(),
7486 	 * which runs after scx_root_disable() has dropped scx_enable_mutex. If
7487 	 * it's still non-NULL here, a previous attachment on @ops has not
7488 	 * finished tearing down; proceeding would let the in-flight unreg's
7489 	 * RCU_INIT_POINTER(NULL) clobber the @ops->priv we are about to assign.
7490 	 */
7491 	if (rcu_access_pointer(ops->priv)) {
7492 		ret = -EBUSY;
7493 		goto err_unlock;
7494 	}
7495 
7496 	ret = alloc_kick_syncs();
7497 	if (ret)
7498 		goto err_unlock;
7499 
7500 	if (ops->flags & SCX_OPS_TID_TO_TASK) {
7501 		ret = rhashtable_init(&scx_tid_hash, &scx_tid_hash_params);
7502 		if (ret)
7503 			goto err_free_ksyncs;
7504 	}
7505 
7506 #ifdef CONFIG_EXT_SUB_SCHED
7507 	cgroup_get(cgrp);
7508 #endif
7509 	sch = scx_alloc_and_add_sched(cmd, cgrp, NULL);
7510 	if (IS_ERR(sch)) {
7511 		ret = PTR_ERR(sch);
7512 		goto err_free_tid_hash;
7513 	}
7514 
7515 	if (sch->is_cid_type)
7516 		static_branch_enable(&__scx_is_cid_type);
7517 
7518 	/*
7519 	 * Transition to ENABLING and clear exit info to arm the disable path.
7520 	 * Failure triggers full disabling from here on.
7521 	 */
7522 	WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED);
7523 	WARN_ON_ONCE(scx_root);
7524 
7525 	atomic_long_set(&scx_nr_rejected, 0);
7526 
7527 	for_each_possible_cpu(cpu) {
7528 		struct rq *rq = cpu_rq(cpu);
7529 
7530 		rq->scx.local_dsq.sched = sch;
7531 		rq->scx.cpuperf_target = SCX_CPUPERF_ONE;
7532 	}
7533 
7534 	scx_discard_stale_ecaps_syncs();
7535 	scx_rescue_set_knobs(sch);
7536 
7537 	/*
7538 	 * Keep CPUs stable during enable so that the BPF scheduler can track
7539 	 * online CPUs by watching ->on/offline_cpu() after ->init().
7540 	 */
7541 	cpus_read_lock();
7542 
7543 	/*
7544 	 * Build the cid mapping into a private under-construction set. It
7545 	 * becomes visible to readers only through scx_cid_publish_tables() once
7546 	 * ops.init_cids() has finalized the layout.
7547 	 */
7548 	ret = scx_cid_init(sch);
7549 	if (ret) {
7550 		cpus_read_unlock();
7551 		goto err_disable;
7552 	}
7553 
7554 	/*
7555 	 * Make the scheduler instance visible. Must be inside cpus_read_lock().
7556 	 * See handle_hotplug().
7557 	 */
7558 	rcu_assign_pointer(scx_root, sch);
7559 
7560 	ret = scx_link_sched(sch);
7561 	if (ret) {
7562 		cpus_read_unlock();
7563 		goto err_disable;
7564 	}
7565 
7566 	scx_idle_enable(ops);
7567 
7568 	/*
7569 	 * A cid-form scheduler finalizes its cid layout in ops.init_cids(),
7570 	 * which may call scx_bpf_cid_override(). Run it before the caps and
7571 	 * shard state are built so the final layout is in effect.
7572 	 */
7573 	if (sch->is_cid_type && sch->ops_cid.init_cids) {
7574 		ret = SCX_CALL_OP_RET(sch, init_cids, NULL);
7575 		if (ret) {
7576 			ret = scx_ops_sanitize_err(sch, "init_cids", ret);
7577 			cpus_read_unlock();
7578 			scx_error(sch, "ops.init_cids() failed (%d)", ret);
7579 			goto err_disable;
7580 		}
7581 	}
7582 
7583 	/* the cid layout is final, expose it to readers */
7584 	scx_cid_publish_tables();
7585 
7586 	ret = scx_arena_pool_init(sch);
7587 	if (ret) {
7588 		cpus_read_unlock();
7589 		goto err_disable;
7590 	}
7591 
7592 	ret = scx_set_cmask_scratch_alloc(sch);
7593 	if (ret) {
7594 		cpus_read_unlock();
7595 		goto err_disable;
7596 	}
7597 
7598 	ret = scx_alloc_pshards(sch);
7599 	if (ret) {
7600 		cpus_read_unlock();
7601 		goto err_disable;
7602 	}
7603 
7604 	scx_init_root_caps(sch);
7605 
7606 	/* the cid caps and shards are live now, so ops.init() can query them */
7607 	if (sch->ops.init) {
7608 		ret = SCX_CALL_OP_RET(sch, init, NULL);
7609 		if (ret) {
7610 			ret = scx_ops_sanitize_err(sch, "init", ret);
7611 			cpus_read_unlock();
7612 			scx_error(sch, "ops.init() failed (%d)", ret);
7613 			goto err_disable;
7614 		}
7615 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
7616 	}
7617 
7618 	ret = scx_sched_sysfs_add(sch);
7619 	if (ret) {
7620 		cpus_read_unlock();
7621 		goto err_disable;
7622 	}
7623 
7624 	for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++)
7625 		if (((void (**)(void))ops)[i])
7626 			set_bit(i, sch->has_op);
7627 
7628 	ret = check_hotplug_seq(sch, ops);
7629 	if (ret) {
7630 		cpus_read_unlock();
7631 		goto err_disable;
7632 	}
7633 	scx_idle_update_selcpu_topology(ops);
7634 
7635 	cpus_read_unlock();
7636 
7637 	ret = scx_validate_ops(sch, ops);
7638 	if (ret)
7639 		goto err_disable;
7640 
7641 	/*
7642 	 * Attach the ext_server bandwidth reservation before anything is
7643 	 * committed so that we can fail the enable if the root domain cannot
7644 	 * accommodate it. The matching fair_server detach is deferred to the
7645 	 * tail of this function, after the switch is fully committed and can no
7646 	 * longer fail.
7647 	 *
7648 	 * On failure, err_disable funnels into scx_root_disable() which
7649 	 * detaches ext_server, so partially-attached state is cleaned up
7650 	 * automatically.
7651 	 */
7652 	for_each_possible_cpu(cpu) {
7653 		struct rq *rq = cpu_rq(cpu);
7654 
7655 		scoped_guard(rq_lock_irqsave, rq) {
7656 			update_rq_clock(rq);
7657 			ret = dl_server_attach_bw(&rq->ext_server);
7658 		}
7659 		if (ret) {
7660 			pr_warn("sched_ext: failed to attach ext_server on CPU %d (%d)\n",
7661 				cpu, ret);
7662 			goto err_disable;
7663 		}
7664 	}
7665 
7666 	/*
7667 	 * Once __scx_enabled is set, %current can be switched to SCX anytime.
7668 	 * This can lead to stalls as some BPF schedulers (e.g. userspace
7669 	 * scheduling) may not function correctly before all tasks are switched.
7670 	 * Init in bypass mode to guarantee forward progress.
7671 	 */
7672 	scx_bypass(sch, true);
7673 
7674 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
7675 		if (((void (**)(void))ops)[i])
7676 			set_bit(i, sch->has_op);
7677 
7678 	if (sch->ops.cpu_acquire || sch->ops.cpu_release)
7679 		sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT;
7680 
7681 	/*
7682 	 * Lock out forks, cgroup on/offlining and moves before opening the
7683 	 * floodgate so that they don't wander into the operations prematurely.
7684 	 */
7685 	percpu_down_write(&scx_fork_rwsem);
7686 
7687 	WARN_ON_ONCE(scx_init_task_enabled);
7688 	scx_init_task_enabled = true;
7689 
7690 	/* flip under fork_rwsem; the iter below covers existing tasks */
7691 	if (ops->flags & SCX_OPS_TID_TO_TASK)
7692 		static_branch_enable(&__scx_tid_to_task_enabled);
7693 
7694 	/*
7695 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
7696 	 * preventing new tasks from being added. No need to exclude tasks
7697 	 * leaving as sched_ext_free() can handle both prepped and enabled
7698 	 * tasks. Prep all tasks first and then enable them with preemption
7699 	 * disabled.
7700 	 *
7701 	 * All cgroups should be initialized before scx_init_task() so that the
7702 	 * BPF scheduler can reliably track each task's cgroup membership from
7703 	 * scx_init_task(). Lock out cgroup on/offlining and task migrations
7704 	 * while tasks are being initialized so that scx_cgroup_can_attach()
7705 	 * never sees uninitialized tasks.
7706 	 */
7707 	scx_cgroup_lock();
7708 	set_cgroup_sched(sch_cgroup(sch), sch);
7709 	ret = scx_cgroup_init(sch);
7710 	if (ret)
7711 		goto err_disable_unlock_all;
7712 
7713 	WARN_ON_ONCE(scx_cgroup_enabled);
7714 	scx_cgroup_enabled = true;
7715 
7716 	scx_task_iter_start(&sti, NULL);
7717 	while ((p = scx_task_iter_next_locked(&sti))) {
7718 		/*
7719 		 * @p is in scx_tasks under scx_tasks_lock, and SCX_TASK_DEAD
7720 		 * tasks are filtered by scx_task_iter_next_locked().
7721 		 * sched_ext_dead() removes @p from scx_tasks under the same
7722 		 * lock before put_task_struct_rcu_user() runs, so @p->usage
7723 		 * is guaranteed > 0 here.
7724 		 */
7725 		get_task_struct(p);
7726 
7727 		/*
7728 		 * Set %INIT_BEGIN under the iter's rq lock so that a concurrent
7729 		 * sched_ext_dead() does not call ops.exit_task() on @p while
7730 		 * ops.init_task() is running. If sched_ext_dead() runs before
7731 		 * this store, it has already removed @p from scx_tasks and the
7732 		 * iter won't visit @p; if it runs after, it observes
7733 		 * %INIT_BEGIN and transitions to %DEAD without calling ops,
7734 		 * leaving the post-init recheck below to unwind.
7735 		 */
7736 		scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
7737 		scx_task_iter_unlock(&sti);
7738 
7739 		ret = __scx_init_task(sch, p, NULL, false);
7740 
7741 		scx_task_iter_relock(&sti, p);
7742 
7743 		if (unlikely(ret)) {
7744 			if (scx_get_task_state(p) != SCX_TASK_DEAD)
7745 				scx_set_task_state(p, SCX_TASK_NONE);
7746 			scx_task_iter_stop(&sti);
7747 			scx_error(sch, "ops.init_task() failed (%d) for %s[%d]",
7748 				  ret, p->comm, p->pid);
7749 			put_task_struct(p);
7750 			goto err_disable_unlock_all;
7751 		}
7752 
7753 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
7754 			/*
7755 			 * sched_ext_dead() observed %INIT_BEGIN and set %DEAD.
7756 			 * ops.exit_task() is owed to the sched __scx_init_task()
7757 			 * ran against; call it now.
7758 			 */
7759 			scx_sub_init_cancel_task(sch, p);
7760 		} else {
7761 			scx_set_task_state(p, SCX_TASK_INIT);
7762 			scx_set_task_sched(p, sch);
7763 			scx_set_task_state(p, SCX_TASK_READY);
7764 		}
7765 
7766 		/*
7767 		 * Insert into the tid hash. scx_tasks_lock is held by the iter;
7768 		 * list_empty() guards against sched_ext_dead() having taken @p
7769 		 * off the list while init ran unlocked.
7770 		 */
7771 		if (scx_tid_to_task_enabled() && !list_empty(&p->scx.tasks_node))
7772 			scx_tid_hash_insert(p);
7773 
7774 		put_task_struct(p);
7775 	}
7776 	scx_task_iter_stop(&sti);
7777 	scx_cgroup_unlock();
7778 	percpu_up_write(&scx_fork_rwsem);
7779 
7780 	/*
7781 	 * All tasks are READY. It's safe to turn on scx_enabled() and switch
7782 	 * all eligible tasks.
7783 	 */
7784 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
7785 	static_branch_enable(&__scx_enabled);
7786 
7787 	/*
7788 	 * We're fully committed and can't fail. The task READY -> ENABLED
7789 	 * transitions here are synchronized against sched_ext_free() through
7790 	 * scx_tasks_lock.
7791 	 */
7792 	percpu_down_write(&scx_fork_rwsem);
7793 	scx_task_iter_start(&sti, NULL);
7794 	while ((p = scx_task_iter_next_locked(&sti))) {
7795 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
7796 		const struct sched_class *old_class = p->sched_class;
7797 		const struct sched_class *new_class = scx_setscheduler_class(p);
7798 
7799 		if (scx_get_task_state(p) != SCX_TASK_READY)
7800 			continue;
7801 
7802 		if (old_class != new_class)
7803 			queue_flags |= DEQUEUE_CLASS;
7804 
7805 		scoped_guard (sched_change, p, queue_flags) {
7806 			scx_set_task_slice(p, READ_ONCE(sch->slice_dfl));
7807 			p->sched_class = new_class;
7808 		}
7809 	}
7810 	scx_task_iter_stop(&sti);
7811 	percpu_up_write(&scx_fork_rwsem);
7812 
7813 	scx_bypass(sch, false);
7814 
7815 	if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) {
7816 		WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE);
7817 		ret = -EBUSY;
7818 		goto err_disable;
7819 	}
7820 
7821 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
7822 		static_branch_enable(&__scx_switched_all);
7823 
7824 	/*
7825 	 * Detach the fair_server bandwidth reservation now that the switch
7826 	 * is fully committed. In full mode (!SCX_OPS_SWITCH_PARTIAL) no
7827 	 * task will ever run in the fair class, so give that bandwidth
7828 	 * back to the RT class. The matching ext_server attach already
7829 	 * happened earlier; this only releases bandwidth and cannot fail.
7830 	 *
7831 	 * In partial mode keep fair_server attached.
7832 	 */
7833 	if (scx_switched_all()) {
7834 		for_each_possible_cpu(cpu) {
7835 			struct rq *rq = cpu_rq(cpu);
7836 
7837 			guard(rq_lock_irqsave)(rq);
7838 			update_rq_clock(rq);
7839 			dl_server_detach_bw(&rq->fair_server);
7840 		}
7841 	}
7842 
7843 	pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n",
7844 		sch->ops.name, scx_switched_all() ? "" : " (partial)");
7845 	kobject_uevent(&sch->kobj, KOBJ_ADD);
7846 	mutex_unlock(&scx_enable_mutex);
7847 
7848 	atomic_long_inc(&scx_enable_seq);
7849 
7850 	cmd->ret = 0;
7851 	return;
7852 
7853 err_free_tid_hash:
7854 	if (ops->flags & SCX_OPS_TID_TO_TASK)
7855 		rhashtable_free_and_destroy(&scx_tid_hash, NULL, NULL);
7856 err_free_ksyncs:
7857 	free_kick_syncs();
7858 err_unlock:
7859 	mutex_unlock(&scx_enable_mutex);
7860 	cmd->ret = ret;
7861 	return;
7862 
7863 err_disable_unlock_all:
7864 	scx_cgroup_unlock();
7865 	percpu_up_write(&scx_fork_rwsem);
7866 	/* we'll soon enter disable path, keep bypass on */
7867 err_disable:
7868 	mutex_unlock(&scx_enable_mutex);
7869 	/*
7870 	 * Returning an error code here would not pass all the error information
7871 	 * to userspace. Record errno using scx_error() for cases scx_error()
7872 	 * wasn't already invoked and exit indicating success so that the error
7873 	 * is notified through ops.exit() with all the details.
7874 	 *
7875 	 * Flush scx_disable_work to ensure that error is reported before init
7876 	 * completion. sch's base reference will be put by bpf_scx_unreg().
7877 	 */
7878 	scx_error(sch, "scx_root_enable() failed (%d)", ret);
7879 	scx_flush_disable_work(sch);
7880 	cmd->ret = 0;
7881 }
7882 
scx_enable(struct scx_enable_cmd * cmd,struct bpf_link * link)7883 static s32 scx_enable(struct scx_enable_cmd *cmd, struct bpf_link *link)
7884 {
7885 	static struct kthread_worker *helper;
7886 	static DEFINE_MUTEX(helper_mutex);
7887 
7888 	if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT)) {
7889 		pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n");
7890 		return -EINVAL;
7891 	}
7892 
7893 	if (!READ_ONCE(helper)) {
7894 		mutex_lock(&helper_mutex);
7895 		if (!helper) {
7896 			struct kthread_worker *w =
7897 				kthread_run_worker(0, "scx_enable_helper");
7898 			if (IS_ERR_OR_NULL(w)) {
7899 				mutex_unlock(&helper_mutex);
7900 				return -ENOMEM;
7901 			}
7902 			sched_set_fifo(w->task);
7903 			WRITE_ONCE(helper, w);
7904 		}
7905 		mutex_unlock(&helper_mutex);
7906 	}
7907 
7908 #ifdef CONFIG_EXT_SUB_SCHED
7909 	if (cmd->ops->sub_cgroup_id > 1)
7910 		kthread_init_work(&cmd->work, scx_sub_enable_workfn);
7911 	else
7912 #endif	/* CONFIG_EXT_SUB_SCHED */
7913 		kthread_init_work(&cmd->work, scx_root_enable_workfn);
7914 
7915 	kthread_queue_work(READ_ONCE(helper), &cmd->work);
7916 	kthread_flush_work(&cmd->work);
7917 	return cmd->ret;
7918 }
7919 
7920 
7921 /********************************************************************************
7922  * bpf_struct_ops plumbing.
7923  */
7924 #include <linux/bpf_verifier.h>
7925 #include <linux/bpf.h>
7926 #include <linux/btf.h>
7927 
7928 static const struct btf_type *task_struct_type;
7929 
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)7930 static bool bpf_scx_is_valid_access(int off, int size,
7931 				    enum bpf_access_type type,
7932 				    const struct bpf_prog *prog,
7933 				    struct bpf_insn_access_aux *info)
7934 {
7935 	if (type != BPF_READ)
7936 		return false;
7937 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
7938 		return false;
7939 	if (off % size != 0)
7940 		return false;
7941 
7942 	return btf_ctx_access(off, size, type, prog, info);
7943 }
7944 
7945 /* common to both forms: only scx.disallow is writable */
bpf_scx_btf_struct_access_common(const struct bpf_reg_state * reg,int off,int size)7946 static int bpf_scx_btf_struct_access_common(const struct bpf_reg_state *reg,
7947 					    int off, int size)
7948 {
7949 	const struct btf_type *t;
7950 
7951 	t = btf_type_by_id(reg->btf, reg->btf_id);
7952 	if (t == task_struct_type &&
7953 	    off >= offsetof(struct task_struct, scx.disallow) &&
7954 	    off + size <= offsetofend(struct task_struct, scx.disallow))
7955 		return SCALAR_VALUE;
7956 
7957 	return -EACCES;
7958 }
7959 
bpf_scx_btf_struct_access(struct bpf_verifier_log * log,const struct bpf_reg_state * reg,int off,int size)7960 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
7961 				     const struct bpf_reg_state *reg, int off,
7962 				     int size)
7963 {
7964 	const struct btf_type *t;
7965 
7966 	t = btf_type_by_id(reg->btf, reg->btf_id);
7967 	if (t == task_struct_type) {
7968 		if ((off >= offsetof(struct task_struct, scx.slice) &&
7969 		     off + size <= offsetofend(struct task_struct, scx.slice)) ||
7970 		    (off >= offsetof(struct task_struct, scx.dsq_vtime) &&
7971 		     off + size <= offsetofend(struct task_struct, scx.dsq_vtime)))
7972 			return SCALAR_VALUE;
7973 	}
7974 
7975 	return bpf_scx_btf_struct_access_common(reg, off, size);
7976 }
7977 
7978 /* cid-form rejects direct slice and dsq_vtime writes in favor of the kfuncs */
bpf_scx_cid_btf_struct_access(struct bpf_verifier_log * log,const struct bpf_reg_state * reg,int off,int size)7979 static int bpf_scx_cid_btf_struct_access(struct bpf_verifier_log *log,
7980 					 const struct bpf_reg_state *reg, int off,
7981 					 int size)
7982 {
7983 	return bpf_scx_btf_struct_access_common(reg, off, size);
7984 }
7985 
7986 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
7987 	.get_func_proto = bpf_base_func_proto,
7988 	.is_valid_access = bpf_scx_is_valid_access,
7989 	.btf_struct_access = bpf_scx_btf_struct_access,
7990 };
7991 
7992 static const struct bpf_verifier_ops bpf_scx_cid_verifier_ops = {
7993 	.get_func_proto = bpf_base_func_proto,
7994 	.is_valid_access = bpf_scx_is_valid_access,
7995 	.btf_struct_access = bpf_scx_cid_btf_struct_access,
7996 };
7997 
bpf_scx_init_member(const struct btf_type * t,const struct btf_member * member,void * kdata,const void * udata)7998 static int bpf_scx_init_member(const struct btf_type *t,
7999 			       const struct btf_member *member,
8000 			       void *kdata, const void *udata)
8001 {
8002 	const struct sched_ext_ops *uops = udata;
8003 	struct sched_ext_ops *ops = kdata;
8004 	u32 moff = __btf_member_bit_offset(t, member) / 8;
8005 	int ret;
8006 
8007 	switch (moff) {
8008 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
8009 		if (*(u32 *)(udata + moff) > INT_MAX)
8010 			return -E2BIG;
8011 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
8012 		return 1;
8013 	case offsetof(struct sched_ext_ops, flags):
8014 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
8015 			return -EINVAL;
8016 		ops->flags = *(u64 *)(udata + moff);
8017 		return 1;
8018 	case offsetof(struct sched_ext_ops, name):
8019 		ret = bpf_obj_name_cpy(ops->name, uops->name,
8020 				       sizeof(ops->name));
8021 		if (ret < 0)
8022 			return ret;
8023 		if (ret == 0)
8024 			return -EINVAL;
8025 		return 1;
8026 	case offsetof(struct sched_ext_ops, timeout_ms):
8027 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
8028 		    SCX_WATCHDOG_MAX_TIMEOUT)
8029 			return -E2BIG;
8030 		ops->timeout_ms = *(u32 *)(udata + moff);
8031 		return 1;
8032 	case offsetof(struct sched_ext_ops, exit_dump_len):
8033 		ops->exit_dump_len =
8034 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
8035 		return 1;
8036 	case offsetof(struct sched_ext_ops, hotplug_seq):
8037 		ops->hotplug_seq = *(u64 *)(udata + moff);
8038 		return 1;
8039 	case offsetof(struct sched_ext_ops, cid_shard_size):
8040 		ops->cid_shard_size = *(u32 *)(udata + moff);
8041 		return 1;
8042 	case offsetof(struct sched_ext_ops, rescue_bandwidth_ppt): {
8043 		u32 bw_ppt = *(u32 *)(udata + moff);
8044 
8045 		if (bw_ppt > SCX_RESCUE_MAX_BW_PPT && bw_ppt != SCX_RESCUE_DISABLE)
8046 			return -E2BIG;
8047 		ops->rescue_bandwidth_ppt = bw_ppt;
8048 		return 1;
8049 	}
8050 	case offsetof(struct sched_ext_ops, rescue_quantum_us): {
8051 		u32 quantum_us = *(u32 *)(udata + moff);
8052 
8053 		if (quantum_us > SCX_RESCUE_MAX_QUANTUM_US)
8054 			return -E2BIG;
8055 		if (quantum_us && quantum_us < SCX_RESCUE_MIN_QUANTUM_US)
8056 			return -EINVAL;
8057 		ops->rescue_quantum_us = quantum_us;
8058 		return 1;
8059 	}
8060 #ifdef CONFIG_EXT_SUB_SCHED
8061 	case offsetof(struct sched_ext_ops, sub_cgroup_id):
8062 		ops->sub_cgroup_id = *(u64 *)(udata + moff);
8063 		return 1;
8064 #endif	/* CONFIG_EXT_SUB_SCHED */
8065 	}
8066 
8067 	return 0;
8068 }
8069 
bpf_scx_check_member(const struct btf_type * t,const struct btf_member * member,const struct bpf_prog * prog)8070 static int bpf_scx_check_member(const struct btf_type *t,
8071 				const struct btf_member *member,
8072 				const struct bpf_prog *prog)
8073 {
8074 	u32 moff = __btf_member_bit_offset(t, member) / 8;
8075 
8076 	switch (moff) {
8077 	case offsetof(struct sched_ext_ops, init_task):
8078 #ifdef CONFIG_EXT_GROUP_SCHED
8079 	case offsetof(struct sched_ext_ops, cgroup_init):
8080 	case offsetof(struct sched_ext_ops, cgroup_exit):
8081 	case offsetof(struct sched_ext_ops, cgroup_prep_move):
8082 #endif
8083 	case offsetof(struct sched_ext_ops, cpu_online):
8084 	case offsetof(struct sched_ext_ops, cpu_offline):
8085 	case offsetof(struct sched_ext_ops, init_cids):
8086 	case offsetof(struct sched_ext_ops, init):
8087 	case offsetof(struct sched_ext_ops, exit):
8088 	case offsetof(struct sched_ext_ops, sub_attach):
8089 	case offsetof(struct sched_ext_ops, sub_detach):
8090 		break;
8091 	default:
8092 		if (prog->sleepable)
8093 			return -EINVAL;
8094 	}
8095 
8096 #ifdef CONFIG_EXT_SUB_SCHED
8097 	/*
8098 	 * Enable private stack for operations that can nest along the
8099 	 * hierarchy.
8100 	 *
8101 	 * XXX - Ideally, we should only do this for scheds that allow
8102 	 * sub-scheds and sub-scheds themselves but I don't know how to access
8103 	 * struct_ops from here.
8104 	 */
8105 	switch (moff) {
8106 	case offsetof(struct sched_ext_ops, dispatch):
8107 		prog->aux->priv_stack_requested = true;
8108 		prog->aux->recursion_detected = scx_pstack_recursion_on_dispatch;
8109 		break;
8110 	case offsetof(struct sched_ext_ops, sub_caps_updated):
8111 		prog->aux->priv_stack_requested = true;
8112 		prog->aux->recursion_detected = scx_pstack_recursion_on_caps_updated;
8113 		break;
8114 	}
8115 #endif	/* CONFIG_EXT_SUB_SCHED */
8116 
8117 	return 0;
8118 }
8119 
bpf_scx_reg(void * kdata,struct bpf_link * link)8120 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
8121 {
8122 	struct scx_enable_cmd cmd = { .ops = kdata };
8123 
8124 	return scx_enable(&cmd, link);
8125 }
8126 
8127 struct scx_arena_scan {
8128 	struct bpf_map	*arena;
8129 	int		err;
8130 };
8131 
8132 /*
8133  * The verifier enforces one arena per BPF program, so each struct_ops
8134  * member prog contributes at most one arena via bpf_prog_arena().
8135  * Require all non-NULL contributions to match.
8136  */
scx_arena_scan_prog(struct bpf_prog * prog,void * data)8137 static int scx_arena_scan_prog(struct bpf_prog *prog, void *data)
8138 {
8139 	struct scx_arena_scan *s = data;
8140 	struct bpf_map *arena = NULL;
8141 
8142 	/* arena.o, which defines these, is built only on MMU && 64BIT */
8143 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
8144 	arena = bpf_prog_arena(prog);
8145 #endif
8146 	if (!arena)
8147 		return 0;
8148 	if (s->arena && s->arena != arena) {
8149 		s->err = -EINVAL;
8150 		return 1;
8151 	}
8152 	s->arena = arena;
8153 	return 0;
8154 }
8155 
bpf_scx_reg_cid(void * kdata,struct bpf_link * link)8156 static int bpf_scx_reg_cid(void *kdata, struct bpf_link *link)
8157 {
8158 	struct scx_enable_cmd cmd = { .ops_cid = kdata, .is_cid_type = true };
8159 	struct scx_arena_scan scan = {};
8160 	int ret;
8161 
8162 	bpf_struct_ops_for_each_prog(kdata, scx_arena_scan_prog, &scan);
8163 	if (scan.err) {
8164 		pr_err("sched_ext: cid-form scheduler uses multiple arena maps\n");
8165 		return scan.err;
8166 	}
8167 	if (!scan.arena) {
8168 		pr_err("sched_ext: cid-form scheduler must use a BPF arena map\n");
8169 		return -EINVAL;
8170 	}
8171 
8172 	bpf_map_inc(scan.arena);
8173 	cmd.arena_map = scan.arena;
8174 	ret = scx_enable(&cmd, link);
8175 	if (cmd.arena_map)		/* not consumed by scx_alloc_and_add_sched() */
8176 		bpf_map_put(cmd.arena_map);
8177 	return ret;
8178 }
8179 
bpf_scx_unreg(void * kdata,struct bpf_link * link)8180 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
8181 {
8182 	struct sched_ext_ops *ops = kdata;
8183 	struct scx_sched *sch = rcu_dereference_protected(ops->priv, true);
8184 
8185 	scx_disable(sch, SCX_EXIT_UNREG);
8186 	scx_flush_disable_work(sch);
8187 	RCU_INIT_POINTER(ops->priv, NULL);
8188 	kobject_put(&sch->kobj);
8189 }
8190 
bpf_scx_init(struct btf * btf)8191 static int bpf_scx_init(struct btf *btf)
8192 {
8193 	task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]);
8194 
8195 	return 0;
8196 }
8197 
bpf_scx_update(void * kdata,void * old_kdata,struct bpf_link * link)8198 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
8199 {
8200 	/*
8201 	 * sched_ext does not support updating the actively-loaded BPF
8202 	 * scheduler, as registering a BPF scheduler can always fail if the
8203 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
8204 	 * etc. Similarly, we can always race with unregistration happening
8205 	 * elsewhere, such as with sysrq.
8206 	 */
8207 	return -EOPNOTSUPP;
8208 }
8209 
bpf_scx_validate(void * kdata)8210 static int bpf_scx_validate(void *kdata)
8211 {
8212 	return 0;
8213 }
8214 
sched_ext_ops__select_cpu(struct task_struct * p,s32 prev_cpu,u64 wake_flags)8215 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
sched_ext_ops__enqueue(struct task_struct * p,u64 enq_flags)8216 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
sched_ext_ops__dequeue(struct task_struct * p,u64 enq_flags)8217 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
sched_ext_ops__dispatch(s32 prev_cpu,struct task_struct * prev__nullable)8218 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {}
sched_ext_ops__tick(struct task_struct * p)8219 static void sched_ext_ops__tick(struct task_struct *p) {}
sched_ext_ops__runnable(struct task_struct * p,u64 enq_flags)8220 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {}
sched_ext_ops__running(struct task_struct * p)8221 static void sched_ext_ops__running(struct task_struct *p) {}
sched_ext_ops__stopping(struct task_struct * p,bool runnable)8222 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {}
sched_ext_ops__quiescent(struct task_struct * p,u64 deq_flags)8223 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {}
sched_ext_ops__yield(struct task_struct * from,struct task_struct * to__nullable)8224 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; }
sched_ext_ops__core_sched_before(struct task_struct * a,struct task_struct * b)8225 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; }
sched_ext_ops__set_weight(struct task_struct * p,u32 weight)8226 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {}
sched_ext_ops__set_cpumask(struct task_struct * p,const struct cpumask * mask)8227 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {}
sched_ext_ops__update_idle(s32 cpu,bool idle)8228 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {}
sched_ext_ops__cpu_acquire(s32 cpu,struct scx_cpu_acquire_args * args)8229 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {}
sched_ext_ops__cpu_release(s32 cpu,struct scx_cpu_release_args * args)8230 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {}
sched_ext_ops__init_task(struct task_struct * p,struct scx_init_task_args * args)8231 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
sched_ext_ops__exit_task(struct task_struct * p,struct scx_exit_task_args * args)8232 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {}
sched_ext_ops__enable(struct task_struct * p)8233 static void sched_ext_ops__enable(struct task_struct *p) {}
sched_ext_ops__disable(struct task_struct * p)8234 static void sched_ext_ops__disable(struct task_struct *p) {}
8235 #ifdef CONFIG_EXT_GROUP_SCHED
sched_ext_ops__cgroup_init(struct cgroup * cgrp,struct scx_cgroup_init_args * args)8236 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; }
sched_ext_ops__cgroup_exit(struct cgroup * cgrp)8237 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {}
sched_ext_ops__cgroup_prep_move(struct task_struct * p,struct cgroup * from,struct cgroup * to)8238 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; }
sched_ext_ops__cgroup_move(struct task_struct * p,struct cgroup * from,struct cgroup * to)8239 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
sched_ext_ops__cgroup_cancel_move(struct task_struct * p,struct cgroup * from,struct cgroup * to)8240 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
sched_ext_ops__cgroup_set_weight(struct cgroup * cgrp,u32 weight)8241 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
sched_ext_ops__cgroup_set_bandwidth(struct cgroup * cgrp,u64 period_us,u64 quota_us,u64 burst_us)8242 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
sched_ext_ops__cgroup_set_idle(struct cgroup * cgrp,bool idle)8243 static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}
8244 #endif	/* CONFIG_EXT_GROUP_SCHED */
sched_ext_ops__sub_attach(struct scx_sub_attach_args * args)8245 static s32 sched_ext_ops__sub_attach(struct scx_sub_attach_args *args) { return -EINVAL; }
sched_ext_ops__sub_detach(struct scx_sub_detach_args * args)8246 static void sched_ext_ops__sub_detach(struct scx_sub_detach_args *args) {}
sched_ext_ops__cpu_online(s32 cpu)8247 static void sched_ext_ops__cpu_online(s32 cpu) {}
sched_ext_ops__cpu_offline(s32 cpu)8248 static void sched_ext_ops__cpu_offline(s32 cpu) {}
sched_ext_ops__init_cids(void)8249 static s32 sched_ext_ops__init_cids(void) { return -EINVAL; }
sched_ext_ops__init(void)8250 static s32 sched_ext_ops__init(void) { return -EINVAL; }
sched_ext_ops__exit(struct scx_exit_info * info)8251 static void sched_ext_ops__exit(struct scx_exit_info *info) {}
sched_ext_ops__dump(struct scx_dump_ctx * ctx)8252 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {}
sched_ext_ops__dump_cpu(struct scx_dump_ctx * ctx,s32 cpu,bool idle)8253 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {}
sched_ext_ops__dump_task(struct scx_dump_ctx * ctx,struct task_struct * p)8254 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {}
8255 
8256 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
8257 	.select_cpu		= sched_ext_ops__select_cpu,
8258 	.enqueue		= sched_ext_ops__enqueue,
8259 	.dequeue		= sched_ext_ops__dequeue,
8260 	.dispatch		= sched_ext_ops__dispatch,
8261 	.tick			= sched_ext_ops__tick,
8262 	.runnable		= sched_ext_ops__runnable,
8263 	.running		= sched_ext_ops__running,
8264 	.stopping		= sched_ext_ops__stopping,
8265 	.quiescent		= sched_ext_ops__quiescent,
8266 	.yield			= sched_ext_ops__yield,
8267 	.core_sched_before	= sched_ext_ops__core_sched_before,
8268 	.set_weight		= sched_ext_ops__set_weight,
8269 	.set_cpumask		= sched_ext_ops__set_cpumask,
8270 	.update_idle		= sched_ext_ops__update_idle,
8271 	.cpu_acquire		= sched_ext_ops__cpu_acquire,
8272 	.cpu_release		= sched_ext_ops__cpu_release,
8273 	.init_task		= sched_ext_ops__init_task,
8274 	.exit_task		= sched_ext_ops__exit_task,
8275 	.enable			= sched_ext_ops__enable,
8276 	.disable		= sched_ext_ops__disable,
8277 #ifdef CONFIG_EXT_GROUP_SCHED
8278 	.cgroup_init		= sched_ext_ops__cgroup_init,
8279 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
8280 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
8281 	.cgroup_move		= sched_ext_ops__cgroup_move,
8282 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
8283 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
8284 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
8285 	.cgroup_set_idle	= sched_ext_ops__cgroup_set_idle,
8286 #endif
8287 	.sub_attach		= sched_ext_ops__sub_attach,
8288 	.sub_detach		= sched_ext_ops__sub_detach,
8289 	.cpu_online		= sched_ext_ops__cpu_online,
8290 	.cpu_offline		= sched_ext_ops__cpu_offline,
8291 	.init_cids		= sched_ext_ops__init_cids,
8292 	.init			= sched_ext_ops__init,
8293 	.exit			= sched_ext_ops__exit,
8294 	.dump			= sched_ext_ops__dump,
8295 	.dump_cpu		= sched_ext_ops__dump_cpu,
8296 	.dump_task		= sched_ext_ops__dump_task,
8297 };
8298 
8299 static struct bpf_struct_ops bpf_sched_ext_ops = {
8300 	.verifier_ops = &bpf_scx_verifier_ops,
8301 	.reg = bpf_scx_reg,
8302 	.unreg = bpf_scx_unreg,
8303 	.check_member = bpf_scx_check_member,
8304 	.init_member = bpf_scx_init_member,
8305 	.init = bpf_scx_init,
8306 	.update = bpf_scx_update,
8307 	.validate = bpf_scx_validate,
8308 	.name = "sched_ext_ops",
8309 	.owner = THIS_MODULE,
8310 	.cfi_stubs = &__bpf_ops_sched_ext_ops
8311 };
8312 
8313 /*
8314  * cid-form cfi stubs. Stubs whose signatures match the cpu-form (param types
8315  * identical, only param names differ across structs) are reused. Some need
8316  * fresh stubs, set_cmask due to an argument type difference and the sub-sched
8317  * notifiers because no cpu-form stub exists to reuse.
8318  */
sched_ext_ops_cid__set_cmask(struct task_struct * p,const struct scx_cmask * cmask__arena)8319 static void sched_ext_ops_cid__set_cmask(struct task_struct *p, const struct scx_cmask *cmask__arena) {}
sched_ext_ops__sub_caps_updated(const struct scx_cmask * cmask__arena,u64 caps)8320 static void sched_ext_ops__sub_caps_updated(const struct scx_cmask *cmask__arena, u64 caps) {}
sched_ext_ops__sub_ecaps_updated(s32 cid,u64 before,u64 after)8321 static void sched_ext_ops__sub_ecaps_updated(s32 cid, u64 before, u64 after) {}
8322 
8323 static struct sched_ext_ops_cid __bpf_ops_sched_ext_ops_cid = {
8324 	.select_cid		= sched_ext_ops__select_cpu,
8325 	.enqueue		= sched_ext_ops__enqueue,
8326 	.dequeue		= sched_ext_ops__dequeue,
8327 	.dispatch		= sched_ext_ops__dispatch,
8328 	.tick			= sched_ext_ops__tick,
8329 	.runnable		= sched_ext_ops__runnable,
8330 	.running		= sched_ext_ops__running,
8331 	.stopping		= sched_ext_ops__stopping,
8332 	.quiescent		= sched_ext_ops__quiescent,
8333 	.yield			= sched_ext_ops__yield,
8334 	.core_sched_before	= sched_ext_ops__core_sched_before,
8335 	.set_weight		= sched_ext_ops__set_weight,
8336 	.set_cmask		= sched_ext_ops_cid__set_cmask,
8337 	.update_idle		= sched_ext_ops__update_idle,
8338 	.init_task		= sched_ext_ops__init_task,
8339 	.exit_task		= sched_ext_ops__exit_task,
8340 	.enable			= sched_ext_ops__enable,
8341 	.disable		= sched_ext_ops__disable,
8342 #ifdef CONFIG_EXT_GROUP_SCHED
8343 	.cpuctl_init		= sched_ext_ops__cgroup_init,
8344 	.cpuctl_exit		= sched_ext_ops__cgroup_exit,
8345 	.cpuctl_prep_move	= sched_ext_ops__cgroup_prep_move,
8346 	.cpuctl_move		= sched_ext_ops__cgroup_move,
8347 	.cpuctl_cancel_move	= sched_ext_ops__cgroup_cancel_move,
8348 	.cpuctl_set_weight	= sched_ext_ops__cgroup_set_weight,
8349 	.cpuctl_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
8350 	.cpuctl_set_idle	= sched_ext_ops__cgroup_set_idle,
8351 #endif
8352 	.sub_attach		= sched_ext_ops__sub_attach,
8353 	.sub_detach		= sched_ext_ops__sub_detach,
8354 	.sub_caps_updated	= sched_ext_ops__sub_caps_updated,
8355 	.sub_ecaps_updated	= sched_ext_ops__sub_ecaps_updated,
8356 	.cid_online		= sched_ext_ops__cpu_online,
8357 	.cid_offline		= sched_ext_ops__cpu_offline,
8358 	.init_cids		= sched_ext_ops__init_cids,
8359 	.init			= sched_ext_ops__init,
8360 	.exit			= sched_ext_ops__exit,
8361 	.dump			= sched_ext_ops__dump,
8362 	.dump_cid		= sched_ext_ops__dump_cpu,
8363 	.dump_task		= sched_ext_ops__dump_task,
8364 };
8365 
8366 /*
8367  * The cid-form struct_ops shares all bpf_struct_ops hooks with the cpu form.
8368  * init_member, check_member, reg, unreg, etc. process kdata as the byte block
8369  * verified to match by the BUILD_BUG_ON checks in scx_init().
8370  */
8371 static struct bpf_struct_ops bpf_sched_ext_ops_cid = {
8372 	.verifier_ops = &bpf_scx_cid_verifier_ops,
8373 	.reg = bpf_scx_reg_cid,
8374 	.unreg = bpf_scx_unreg,
8375 	.check_member = bpf_scx_check_member,
8376 	.init_member = bpf_scx_init_member,
8377 	.init = bpf_scx_init,
8378 	.update = bpf_scx_update,
8379 	.validate = bpf_scx_validate,
8380 	.name = "sched_ext_ops_cid",
8381 	.owner = THIS_MODULE,
8382 	.cfi_stubs = &__bpf_ops_sched_ext_ops_cid
8383 };
8384 
8385 
8386 /********************************************************************************
8387  * System integration and init.
8388  */
8389 
sysrq_handle_sched_ext_reset(u8 key)8390 static void sysrq_handle_sched_ext_reset(u8 key)
8391 {
8392 	struct scx_sched *sch;
8393 
8394 	sch = rcu_dereference(scx_root);
8395 	if (likely(sch))
8396 		scx_disable(sch, SCX_EXIT_SYSRQ);
8397 	else
8398 		pr_info("sched_ext: BPF schedulers not loaded\n");
8399 }
8400 
8401 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
8402 	.handler	= sysrq_handle_sched_ext_reset,
8403 	.help_msg	= "reset-sched-ext(S)",
8404 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
8405 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
8406 };
8407 
sysrq_handle_sched_ext_dump(u8 key)8408 static void sysrq_handle_sched_ext_dump(u8 key)
8409 {
8410 	struct scx_exit_info ei = {
8411 		.kind		= SCX_EXIT_NONE,
8412 		.exit_cpu	= -1,
8413 		.reason		= "SysRq-D",
8414 	};
8415 	struct scx_sched *sch;
8416 
8417 	list_for_each_entry_rcu(sch, &scx_sched_all, all)
8418 		scx_dump_state(sch, &ei, 0, false);
8419 }
8420 
8421 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
8422 	.handler	= sysrq_handle_sched_ext_dump,
8423 	.help_msg	= "dump-sched-ext(D)",
8424 	.action_msg	= "Trigger sched_ext debug dump",
8425 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
8426 };
8427 
can_skip_idle_kick(struct rq * rq)8428 static bool can_skip_idle_kick(struct rq *rq)
8429 {
8430 	lockdep_assert_rq_held(rq);
8431 
8432 	/*
8433 	 * We can skip idle kicking if @rq is going to go through at least one
8434 	 * full SCX scheduling cycle before going idle. Just checking whether
8435 	 * curr is not idle is insufficient because we could be racing
8436 	 * dispatch_one() trying to pull the next task from a remote rq, which
8437 	 * may fail, and @rq may become idle afterwards.
8438 	 *
8439 	 * The race window is small and we don't and can't guarantee that @rq is
8440 	 * only kicked while idle anyway. Skip only when sure.
8441 	 */
8442 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_DISPATCH);
8443 }
8444 
kick_one_cpu(s32 cpu,struct scx_sched_pcpu * pcpu,struct rq * this_rq,unsigned long * ksyncs)8445 static bool kick_one_cpu(s32 cpu, struct scx_sched_pcpu *pcpu, struct rq *this_rq,
8446 			 unsigned long *ksyncs)
8447 {
8448 	struct rq *rq = cpu_rq(cpu);
8449 	struct scx_rq *this_scx = &this_rq->scx;
8450 	const struct sched_class *cur_class;
8451 	bool should_wait = false;
8452 	bool kickable;
8453 	unsigned long flags;
8454 
8455 	raw_spin_rq_lock_irqsave(rq, flags);
8456 	cur_class = rq->curr->sched_class;
8457 
8458 	/*
8459 	 * During CPU hotplug, a CPU may depend on kicking itself to make
8460 	 * forward progress. Allow kicking self regardless of online state. If
8461 	 * @cpu is running a higher class task, we have no control over @cpu.
8462 	 * Skip kicking. A sub-sched lacking baseline access on @cid has no
8463 	 * business forcing a reschedule there - skip. This is the authoritative
8464 	 * cap check: ecaps is read here under @rq's lock.
8465 	 */
8466 	kickable = (cpu_online(cpu) || cpu == cpu_of(this_rq)) &&
8467 		   !sched_class_above(cur_class, &ext_sched_class);
8468 
8469 	if (kickable && !scx_missing_caps(pcpu->sch, cpu, SCX_CAP_BASE)) {
8470 		if (cpumask_test_cpu(cpu, pcpu->cpus_to_preempt)) {
8471 			if (cur_class == &ext_sched_class) {
8472 				u64 caps = scx_caps_for_preempt(pcpu->sch, rq, 0);
8473 
8474 				if (unlikely(scx_missing_caps(pcpu->sch, cpu, caps)))
8475 					__scx_add_event(pcpu->sch, SCX_EV_SUB_PREEMPT_DENIED, 1);
8476 				else if (unlikely(!scx_set_task_slice(rq->curr, 0)))
8477 					__scx_add_event(pcpu->sch, SCX_EV_SLICE_DENIED, 1);
8478 			}
8479 			cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt);
8480 		}
8481 
8482 		if (cpumask_test_cpu(cpu, pcpu->cpus_to_wait)) {
8483 			if (cur_class == &ext_sched_class) {
8484 				cpumask_set_cpu(cpu, this_scx->cpus_to_sync);
8485 				ksyncs[cpu] = rq->scx.kick_sync;
8486 				should_wait = true;
8487 			}
8488 			cpumask_clear_cpu(cpu, pcpu->cpus_to_wait);
8489 		}
8490 
8491 		resched_curr(rq);
8492 	} else {
8493 		/* a kickable cpu was skipped solely for the missing caps */
8494 		if (kickable)
8495 			__scx_add_event(pcpu->sch, SCX_EV_SUB_KICK_DENIED, 1);
8496 		cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt);
8497 		cpumask_clear_cpu(cpu, pcpu->cpus_to_wait);
8498 	}
8499 
8500 	scx_rq_lock_drop(rq);
8501 	raw_spin_rq_unlock_irqrestore(rq, flags);
8502 
8503 	return should_wait;
8504 }
8505 
kick_one_cpu_if_idle(s32 cpu,struct scx_sched_pcpu * pcpu,struct rq * this_rq)8506 static void kick_one_cpu_if_idle(s32 cpu, struct scx_sched_pcpu *pcpu,
8507 				 struct rq *this_rq)
8508 {
8509 	struct rq *rq = cpu_rq(cpu);
8510 	unsigned long flags;
8511 
8512 	raw_spin_rq_lock_irqsave(rq, flags);
8513 
8514 	/* idle kicks need baseline access too, see kick_one_cpu() */
8515 	if (!can_skip_idle_kick(rq) &&
8516 	    (cpu_online(cpu) || cpu == cpu_of(this_rq))) {
8517 		if (likely(!scx_missing_caps(pcpu->sch, cpu, SCX_CAP_BASE)))
8518 			resched_curr(rq);
8519 		else
8520 			__scx_add_event(pcpu->sch, SCX_EV_SUB_KICK_DENIED, 1);
8521 	}
8522 
8523 	scx_rq_lock_drop(rq);
8524 	raw_spin_rq_unlock_irqrestore(rq, flags);
8525 }
8526 
kick_cpus_irq_workfn(struct irq_work * irq_work)8527 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
8528 {
8529 	struct rq *this_rq = this_rq();
8530 	struct scx_rq *this_scx = &this_rq->scx;
8531 	struct scx_kick_syncs __rcu *ksyncs_pcpu = __this_cpu_read(scx_kick_syncs);
8532 	struct scx_sched_pcpu *pcpu, *tmp;
8533 	bool should_wait = false;
8534 	unsigned long *ksyncs;
8535 	s32 cpu;
8536 
8537 	/* can race with free_kick_syncs() during scheduler disable */
8538 	if (unlikely(!ksyncs_pcpu))
8539 		return;
8540 
8541 	ksyncs = rcu_dereference_bh(ksyncs_pcpu)->syncs;
8542 
8543 	/*
8544 	 * Walk scheds with pending kicks on this cpu. scx_kick_cpu() adds to
8545 	 * the list under local_irq_save() and only this irq_work consumes it.
8546 	 * A plain list without locking is sufficient.
8547 	 */
8548 	list_for_each_entry_safe(pcpu, tmp, &this_scx->sched_pcpus_to_kick, to_kick_node) {
8549 		list_del_init(&pcpu->to_kick_node);
8550 
8551 		for_each_cpu(cpu, pcpu->cpus_to_kick) {
8552 			should_wait |= kick_one_cpu(cpu, pcpu, this_rq, ksyncs);
8553 			cpumask_clear_cpu(cpu, pcpu->cpus_to_kick);
8554 			cpumask_clear_cpu(cpu, pcpu->cpus_to_kick_if_idle);
8555 		}
8556 
8557 		for_each_cpu(cpu, pcpu->cpus_to_kick_if_idle) {
8558 			kick_one_cpu_if_idle(cpu, pcpu, this_rq);
8559 			cpumask_clear_cpu(cpu, pcpu->cpus_to_kick_if_idle);
8560 		}
8561 	}
8562 
8563 	/*
8564 	 * Can't wait in hardirq — kick_sync can't advance, deadlocking if
8565 	 * CPUs wait for each other. Defer to kick_sync_wait_bal_cb().
8566 	 */
8567 	if (should_wait) {
8568 		raw_spin_rq_lock(this_rq);
8569 		this_scx->kick_sync_pending = true;
8570 		resched_curr(this_rq);
8571 		scx_rq_lock_drop(this_rq);
8572 		raw_spin_rq_unlock(this_rq);
8573 	}
8574 }
8575 
8576 /**
8577  * print_scx_info - print out sched_ext scheduler state
8578  * @log_lvl: the log level to use when printing
8579  * @p: target task
8580  *
8581  * If a sched_ext scheduler is enabled, print the name and state of the
8582  * scheduler. If @p is on sched_ext, print further information about the task.
8583  *
8584  * This function can be safely called on any task as long as the task_struct
8585  * itself is accessible. While safe, this function isn't synchronized and may
8586  * print out mixups or garbages of limited length.
8587  */
print_scx_info(const char * log_lvl,struct task_struct * p)8588 void print_scx_info(const char *log_lvl, struct task_struct *p)
8589 {
8590 	struct scx_sched *sch;
8591 	enum scx_enable_state state = scx_enable_state();
8592 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
8593 	char runnable_at_buf[22] = "?";
8594 	struct sched_class *class;
8595 	unsigned long runnable_at;
8596 
8597 	guard(rcu)();
8598 
8599 	sch = scx_task_sched_rcu(p);
8600 
8601 	if (!sch)
8602 		return;
8603 
8604 	/*
8605 	 * Carefully check if the task was running on sched_ext, and then
8606 	 * carefully copy the time it's been runnable, and its state.
8607 	 */
8608 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
8609 	    class != &ext_sched_class) {
8610 		printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name,
8611 		       scx_enable_state_str[state], all);
8612 		return;
8613 	}
8614 
8615 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
8616 				      sizeof(runnable_at)))
8617 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
8618 			  jiffies_delta_msecs(runnable_at, jiffies));
8619 
8620 	/* print everything onto one line to conserve console space */
8621 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
8622 	       log_lvl, sch->ops.name, scx_enable_state_str[state], all,
8623 	       runnable_at_buf);
8624 }
8625 
scx_pm_handler(struct notifier_block * nb,unsigned long event,void * ptr)8626 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr)
8627 {
8628 	struct scx_sched *sch;
8629 
8630 	guard(rcu)();
8631 
8632 	sch = rcu_dereference(scx_root);
8633 	if (!sch)
8634 		return NOTIFY_OK;
8635 
8636 	/*
8637 	 * SCX schedulers often have userspace components which are sometimes
8638 	 * involved in critial scheduling paths. PM operations involve freezing
8639 	 * userspace which can lead to scheduling misbehaviors including stalls.
8640 	 * Let's bypass while PM operations are in progress.
8641 	 */
8642 	switch (event) {
8643 	case PM_HIBERNATION_PREPARE:
8644 	case PM_SUSPEND_PREPARE:
8645 	case PM_RESTORE_PREPARE:
8646 		scx_bypass(sch, true);
8647 		break;
8648 	case PM_POST_HIBERNATION:
8649 	case PM_POST_SUSPEND:
8650 	case PM_POST_RESTORE:
8651 		scx_bypass(sch, false);
8652 		break;
8653 	}
8654 
8655 	return NOTIFY_OK;
8656 }
8657 
8658 static struct notifier_block scx_pm_notifier = {
8659 	.notifier_call = scx_pm_handler,
8660 };
8661 
init_sched_ext_class(void)8662 void __init init_sched_ext_class(void)
8663 {
8664 	s32 cpu, v;
8665 
8666 	/*
8667 	 * The following is to prevent the compiler from optimizing out the enum
8668 	 * definitions so that BPF scheduler implementations can use them
8669 	 * through the generated vmlinux.h.
8670 	 */
8671 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT |
8672 		   SCX_TG_ONLINE);
8673 
8674 	scx_idle_init_masks();
8675 
8676 	for_each_possible_cpu(cpu) {
8677 		struct rq *rq = cpu_rq(cpu);
8678 		int  n = cpu_to_node(cpu);
8679 
8680 		/* local_dsq's sch will be set during scx_root_enable() */
8681 		BUG_ON(scx_init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL, NULL));
8682 #ifdef CONFIG_EXT_SUB_SCHED
8683 		BUG_ON(scx_init_dsq(&rq->scx.reject_dsq, SCX_DSQ_REJECT, NULL));
8684 		scx_rescue_init(rq);
8685 #endif
8686 
8687 		INIT_LIST_HEAD(&rq->scx.runnable_list);
8688 		INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals);
8689 
8690 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_sync, GFP_KERNEL, n));
8691 		INIT_LIST_HEAD(&rq->scx.sched_pcpus_to_kick);
8692 		raw_spin_lock_init(&rq->scx.deferred_reenq_lock);
8693 		INIT_LIST_HEAD(&rq->scx.deferred_reenq_locals);
8694 		INIT_LIST_HEAD(&rq->scx.deferred_reenq_users);
8695 		rq->scx.deferred_irq_work = IRQ_WORK_INIT_HARD(deferred_irq_workfn);
8696 		rq->scx.kick_cpus_irq_work = IRQ_WORK_INIT_HARD(kick_cpus_irq_workfn);
8697 
8698 		if (cpu_online(cpu))
8699 			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
8700 	}
8701 
8702 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
8703 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
8704 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
8705 
8706 #ifdef CONFIG_EXT_SUB_SCHED
8707 	BUG_ON(rhashtable_init(&scx_sched_hash, &scx_sched_hash_params));
8708 #endif	/* CONFIG_EXT_SUB_SCHED */
8709 }
8710 
8711 
8712 /********************************************************************************
8713  * Helpers that can be called from the BPF scheduler.
8714  */
scx_vet_enq_flags(struct scx_sched * sch,u64 dsq_id,u64 * enq_flags)8715 static bool scx_vet_enq_flags(struct scx_sched *sch, u64 dsq_id, u64 *enq_flags)
8716 {
8717 	bool is_local = dsq_id == SCX_DSQ_LOCAL ||
8718 		(dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON;
8719 
8720 	if (unlikely(*enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
8721 		scx_error(sch, "invalid enq_flags 0x%llx", *enq_flags);
8722 		return false;
8723 	}
8724 
8725 	if (*enq_flags & SCX_ENQ_IMMED) {
8726 		if (unlikely(!is_local)) {
8727 			scx_error(sch, "SCX_ENQ_IMMED on a non-local DSQ 0x%llx", dsq_id);
8728 			return false;
8729 		}
8730 	} else if ((sch->ops.flags & SCX_OPS_ALWAYS_ENQ_IMMED) && is_local) {
8731 		*enq_flags |= SCX_ENQ_IMMED;
8732 	}
8733 
8734 	if (unlikely((*enq_flags & SCX_ENQ_RESCUE) && !is_local)) {
8735 		scx_error(sch, "SCX_ENQ_RESCUE on a non-local DSQ 0x%llx", dsq_id);
8736 		return false;
8737 	}
8738 
8739 	return true;
8740 }
8741 
scx_dsq_insert_preamble(struct scx_sched * sch,struct task_struct * p,u64 dsq_id,u64 * enq_flags)8742 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p,
8743 				    u64 dsq_id, u64 *enq_flags)
8744 {
8745 	lockdep_assert_irqs_disabled();
8746 
8747 	if (unlikely(!p)) {
8748 		scx_error(sch, "called with NULL task");
8749 		return false;
8750 	}
8751 
8752 	/* see SCX_EV_INSERT_NOT_OWNED definition */
8753 	if (unlikely(!scx_task_on_sched(sch, p))) {
8754 		__scx_add_event(sch, SCX_EV_INSERT_NOT_OWNED, 1);
8755 		return false;
8756 	}
8757 
8758 	if (!scx_vet_enq_flags(sch, dsq_id, enq_flags))
8759 		return false;
8760 
8761 	return true;
8762 }
8763 
scx_dsq_insert_commit(struct scx_sched * sch,struct task_struct * p,u64 dsq_id,u64 slice,u64 vtime,u64 enq_flags)8764 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p,
8765 				  u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
8766 {
8767 	struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
8768 	struct task_struct *ddsp_task;
8769 
8770 	ddsp_task = __this_cpu_read(direct_dispatch_task);
8771 	if (ddsp_task) {
8772 		mark_direct_dispatch(sch, ddsp_task, p, dsq_id, slice, vtime, enq_flags);
8773 		return;
8774 	}
8775 
8776 	if (unlikely(dspc->cursor >= sch->dsp_max_batch)) {
8777 		scx_error(sch, "dispatch buffer overflow");
8778 		return;
8779 	}
8780 
8781 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
8782 		.task = p,
8783 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
8784 		.dsq_id = dsq_id,
8785 		.slice = slice,
8786 		.vtime = vtime,
8787 		.enq_flags = enq_flags,
8788 	};
8789 }
8790 
8791 __bpf_kfunc_start_defs();
8792 
8793 /**
8794  * scx_bpf_dsq_insert___v2 - Insert a task into the FIFO queue of a DSQ
8795  * @p: task_struct to insert
8796  * @dsq_id: DSQ to insert into
8797  * @slice: duration @p can run for in nsecs, 0 to keep the current value
8798  * @enq_flags: SCX_ENQ_*
8799  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8800  *
8801  * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to
8802  * call this function spuriously. Can be called from ops.enqueue(),
8803  * ops.select_cpu(), and ops.dispatch().
8804  *
8805  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
8806  * and @p must match the task being enqueued.
8807  *
8808  * When called from ops.select_cpu(), @enq_flags and @dsq_id are stored, and @p
8809  * will be directly inserted into the corresponding dispatch queue after
8810  * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be
8811  * inserted into the local DSQ of the CPU returned by ops.select_cpu().
8812  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
8813  * task is inserted.
8814  *
8815  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
8816  * and this function can be called upto ops.dispatch_max_batch times to insert
8817  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
8818  * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the
8819  * counter.
8820  *
8821  * This function doesn't have any locking restrictions and may be called under
8822  * BPF locks (in the future when BPF introduces more flexible locking).
8823  *
8824  * @p is allowed to run for @slice. The scheduling path is triggered on slice
8825  * exhaustion. If zero, the current residual slice is maintained. If
8826  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
8827  * scx_bpf_kick_cpu() to trigger scheduling.
8828  *
8829  * Returns %true on successful insertion, %false on failure. On the root
8830  * scheduler, %false return triggers scheduler abort and the caller doesn't need
8831  * to check the return value.
8832  */
scx_bpf_dsq_insert___v2(struct task_struct * p,u64 dsq_id,u64 slice,u64 enq_flags,const struct bpf_prog_aux * aux)8833 __bpf_kfunc bool scx_bpf_dsq_insert___v2(struct task_struct *p, u64 dsq_id,
8834 					 u64 slice, u64 enq_flags,
8835 					 const struct bpf_prog_aux *aux)
8836 {
8837 	struct scx_sched *sch;
8838 
8839 	guard(rcu)();
8840 	sch = scx_prog_sched(aux);
8841 	if (unlikely(!sch))
8842 		return false;
8843 
8844 	if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags))
8845 		return false;
8846 
8847 	scx_dsq_insert_commit(sch, p, dsq_id, slice, 0, enq_flags);
8848 
8849 	return true;
8850 }
8851 
8852 /*
8853  * COMPAT: Will be removed in v6.23 along with the ___v2 suffix.
8854  */
scx_bpf_dsq_insert(struct task_struct * p,u64 dsq_id,u64 slice,u64 enq_flags,const struct bpf_prog_aux * aux)8855 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id,
8856 				    u64 slice, u64 enq_flags,
8857 				    const struct bpf_prog_aux *aux)
8858 {
8859 	scx_bpf_dsq_insert___v2(p, dsq_id, slice, enq_flags, aux);
8860 }
8861 
scx_dsq_insert_vtime(struct scx_sched * sch,struct task_struct * p,u64 dsq_id,u64 slice,u64 vtime,u64 enq_flags)8862 static bool scx_dsq_insert_vtime(struct scx_sched *sch, struct task_struct *p,
8863 				 u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
8864 {
8865 	if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags))
8866 		return false;
8867 
8868 	scx_dsq_insert_commit(sch, p, dsq_id, slice, vtime, enq_flags | SCX_ENQ_DSQ_PRIQ);
8869 
8870 	return true;
8871 }
8872 
8873 struct scx_bpf_dsq_insert_vtime_args {
8874 	/* @p can't be packed together as KF_RCU is not transitive */
8875 	u64			dsq_id;
8876 	u64			slice;
8877 	u64			vtime;
8878 	u64			enq_flags;
8879 };
8880 
8881 /**
8882  * __scx_bpf_dsq_insert_vtime - Arg-wrapped vtime DSQ insertion
8883  * @p: task_struct to insert
8884  * @args: struct containing the rest of the arguments
8885  *       @args->dsq_id: DSQ to insert into
8886  *       @args->slice: duration @p can run for in nsecs, 0 to keep the current value
8887  *       @args->vtime: @p's ordering inside the vtime-sorted queue of the target DSQ
8888  *       @args->enq_flags: SCX_ENQ_*
8889  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8890  *
8891  * Wrapper kfunc that takes arguments via struct to work around BPF's 5 argument
8892  * limit. BPF programs should use scx_bpf_dsq_insert_vtime() which is provided
8893  * as an inline wrapper in common.bpf.h.
8894  *
8895  * Insert @p into the vtime priority queue of the DSQ identified by
8896  * @args->dsq_id. Tasks queued into the priority queue are ordered by
8897  * @args->vtime. All other aspects are identical to scx_bpf_dsq_insert().
8898  *
8899  * @args->vtime ordering is according to time_before64() which considers
8900  * wrapping. A numerically larger vtime may indicate an earlier position in the
8901  * ordering and vice-versa.
8902  *
8903  * A DSQ can only be used as a FIFO or priority queue at any given time and this
8904  * function must not be called on a DSQ which already has one or more FIFO tasks
8905  * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and
8906  * SCX_DSQ_GLOBAL) cannot be used as priority queues.
8907  *
8908  * Returns %true on successful insertion, %false on failure. On the root
8909  * scheduler, %false return triggers scheduler abort and the caller doesn't need
8910  * to check the return value.
8911  */
8912 __bpf_kfunc bool
__scx_bpf_dsq_insert_vtime(struct task_struct * p,struct scx_bpf_dsq_insert_vtime_args * args,const struct bpf_prog_aux * aux)8913 __scx_bpf_dsq_insert_vtime(struct task_struct *p,
8914 			   struct scx_bpf_dsq_insert_vtime_args *args,
8915 			   const struct bpf_prog_aux *aux)
8916 {
8917 	struct scx_sched *sch;
8918 
8919 	guard(rcu)();
8920 
8921 	sch = scx_prog_sched(aux);
8922 	if (unlikely(!sch))
8923 		return false;
8924 
8925 	return scx_dsq_insert_vtime(sch, p, args->dsq_id, args->slice,
8926 				    args->vtime, args->enq_flags);
8927 }
8928 
8929 /*
8930  * COMPAT: Will be removed in v6.23.
8931  */
scx_bpf_dsq_insert_vtime(struct task_struct * p,u64 dsq_id,u64 slice,u64 vtime,u64 enq_flags)8932 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id,
8933 					  u64 slice, u64 vtime, u64 enq_flags)
8934 {
8935 	struct scx_sched *sch;
8936 
8937 	guard(rcu)();
8938 
8939 	sch = rcu_dereference(scx_root);
8940 	if (unlikely(!sch))
8941 		return;
8942 
8943 #ifdef CONFIG_EXT_SUB_SCHED
8944 	/*
8945 	 * Disallow if any sub-scheds are attached. There is no way to tell
8946 	 * which scheduler called us, just error out @p's scheduler.
8947 	 */
8948 	if (unlikely(!list_empty(&sch->children))) {
8949 		scx_error(scx_task_sched(p), "__scx_bpf_dsq_insert_vtime() must be used");
8950 		return;
8951 	}
8952 #endif
8953 
8954 	scx_dsq_insert_vtime(sch, p, dsq_id, slice, vtime, enq_flags);
8955 }
8956 
8957 __bpf_kfunc_end_defs();
8958 
8959 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
8960 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_IMPLICIT_ARGS | KF_RCU)
8961 BTF_ID_FLAGS(func, scx_bpf_dsq_insert___v2, KF_IMPLICIT_ARGS | KF_RCU)
8962 BTF_ID_FLAGS(func, __scx_bpf_dsq_insert_vtime, KF_IMPLICIT_ARGS | KF_RCU)
8963 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU)
8964 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
8965 
8966 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
8967 	.owner			= THIS_MODULE,
8968 	.set			= &scx_kfunc_ids_enqueue_dispatch,
8969 	.filter			= scx_kfunc_context_filter,
8970 };
8971 
scx_dsq_move(struct bpf_iter_scx_dsq_kern * kit,struct task_struct * p,u64 dsq_id,u64 enq_flags,bool priq)8972 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit,
8973 			 struct task_struct *p, u64 dsq_id, u64 enq_flags,
8974 			 bool priq)
8975 {
8976 	struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq;
8977 	struct scx_sched *sch;
8978 	struct rq *p_rq, *src_rq, *locked_rq;
8979 	bool dispatched = false;
8980 	unsigned long flags;
8981 
8982 	/*
8983 	 * The verifier considers an iterator slot initialized on any
8984 	 * KF_ITER_NEW return, so a BPF program may legally reach here after
8985 	 * bpf_iter_scx_dsq_new() failed and left @kit->dsq NULL.
8986 	 */
8987 	if (unlikely(!src_dsq))
8988 		return false;
8989 
8990 	sch = src_dsq->sched;
8991 
8992 	if (!scx_vet_enq_flags(sch, dsq_id, &enq_flags))
8993 		return false;
8994 
8995 	/* internal bit, can only go in after @enq_flags is vetted */
8996 	if (priq)
8997 		enq_flags |= SCX_ENQ_DSQ_PRIQ;
8998 
8999 	/*
9000 	 * If the BPF scheduler keeps calling this function repeatedly, it can
9001 	 * cause similar live-lock conditions as scx_consume_dispatch_q().
9002 	 */
9003 	if (unlikely(READ_ONCE(sch->aborting)))
9004 		return false;
9005 
9006 	if (unlikely(!scx_task_on_sched(sch, p))) {
9007 		scx_error(sch, "scx_bpf_dsq_move[_vtime]() on %s[%d] but the task belongs to a different scheduler",
9008 			  p->comm, p->pid);
9009 		return false;
9010 	}
9011 
9012 	/*
9013 	 * Can be called from either ops.dispatch() holding the dispatched rq's
9014 	 * lock or any context where no rq lock is held. If latter, lock @p's
9015 	 * task_rq which we'll likely need anyway.
9016 	 */
9017 	src_rq = task_rq(p);
9018 
9019 	local_irq_save(flags);
9020 
9021 	/*
9022 	 * Under core scheduling, dispatch can run for a sibling rq, so the
9023 	 * locked rq is not necessarily this CPU's.
9024 	 */
9025 	locked_rq = scx_locked_rq();
9026 
9027 	if (locked_rq) {
9028 		if (locked_rq != src_rq)
9029 			switch_rq_lock(locked_rq, src_rq);
9030 	} else {
9031 		raw_spin_rq_lock(src_rq);
9032 	}
9033 
9034 	p_rq = src_rq;
9035 	raw_spin_lock(&src_dsq->lock);
9036 
9037 	/* did someone else get to it while we dropped the locks? */
9038 	if (nldsq_cursor_lost_task(&kit->cursor, src_rq, src_dsq, p)) {
9039 		raw_spin_unlock(&src_dsq->lock);
9040 		goto out;
9041 	}
9042 
9043 	/* @p is still on $src_dsq and stable, determine the destination */
9044 	dst_dsq = find_dsq_for_dispatch(sch, locked_rq ?: this_rq(), dsq_id, task_cpu(p));
9045 
9046 	/*
9047 	 * Apply vtime and slice updates before moving. @p is still on $src_dsq
9048 	 * with both $src_dsq and its task_rq locked, satisfying the write
9049 	 * rules, and the PRIQ insertion into $dst_dsq reads the new vtime.
9050 	 */
9051 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME)
9052 		p->scx.dsq_vtime = kit->vtime;
9053 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE)
9054 		scx_set_task_slice(p, kit->slice);
9055 
9056 	/* execute move */
9057 	p_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq);
9058 	dispatched = true;
9059 out:
9060 	if (locked_rq) {
9061 		if (locked_rq != p_rq)
9062 			switch_rq_lock(p_rq, locked_rq);
9063 	} else {
9064 		scx_rq_lock_drop(p_rq);
9065 		raw_spin_rq_unlock_irqrestore(p_rq, flags);
9066 	}
9067 
9068 	kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE |
9069 			       __SCX_DSQ_ITER_HAS_VTIME);
9070 	return dispatched;
9071 }
9072 
9073 __bpf_kfunc_start_defs();
9074 
9075 /**
9076  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
9077  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9078  *
9079  * Can only be called from ops.dispatch().
9080  */
scx_bpf_dispatch_nr_slots(const struct bpf_prog_aux * aux)9081 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(const struct bpf_prog_aux *aux)
9082 {
9083 	struct scx_sched *sch;
9084 
9085 	guard(rcu)();
9086 
9087 	sch = scx_prog_sched(aux);
9088 	if (unlikely(!sch))
9089 		return 0;
9090 
9091 	return sch->dsp_max_batch - __this_cpu_read(sch->pcpu->dsp_ctx.cursor);
9092 }
9093 
9094 /**
9095  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
9096  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9097  *
9098  * Cancel the latest dispatch. Can be called multiple times to cancel further
9099  * dispatches. Can only be called from ops.dispatch().
9100  */
scx_bpf_dispatch_cancel(const struct bpf_prog_aux * aux)9101 __bpf_kfunc void scx_bpf_dispatch_cancel(const struct bpf_prog_aux *aux)
9102 {
9103 	struct scx_sched *sch;
9104 	struct scx_dsp_ctx *dspc;
9105 
9106 	guard(rcu)();
9107 
9108 	sch = scx_prog_sched(aux);
9109 	if (unlikely(!sch))
9110 		return;
9111 
9112 	dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
9113 
9114 	if (dspc->cursor > 0)
9115 		dspc->cursor--;
9116 	else
9117 		scx_error(sch, "dispatch buffer underflow");
9118 }
9119 
9120 /**
9121  * scx_bpf_dsq_move_to_local___v2 - move a task from a DSQ to the current CPU's local DSQ
9122  * @dsq_id: DSQ to move task from. Must be a user-created DSQ
9123  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9124  * @enq_flags: %SCX_ENQ_*
9125  *
9126  * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's
9127  * local DSQ for execution with @enq_flags applied. Can only be called from
9128  * ops.dispatch().
9129  *
9130  * Built-in DSQs (%SCX_DSQ_GLOBAL and %SCX_DSQ_LOCAL*) are not supported as
9131  * sources. Local DSQs support reenqueueing (a task can be picked up for
9132  * execution, dequeued for property changes, or reenqueued), but the BPF
9133  * scheduler cannot directly iterate or move tasks from them. %SCX_DSQ_GLOBAL
9134  * is similar but also doesn't support reenqueueing, as it maps to multiple
9135  * per-node DSQs making the scope difficult to define; this may change in the
9136  * future.
9137  *
9138  * This function flushes the in-flight dispatches from scx_bpf_dsq_insert()
9139  * before trying to move from the specified DSQ. It may also grab rq locks and
9140  * thus can't be called under any BPF locks.
9141  *
9142  * Returns %true if a task has been moved, %false if there isn't any task to
9143  * move.
9144  */
scx_bpf_dsq_move_to_local___v2(u64 dsq_id,u64 enq_flags,const struct bpf_prog_aux * aux)9145 __bpf_kfunc bool scx_bpf_dsq_move_to_local___v2(u64 dsq_id, u64 enq_flags,
9146 						const struct bpf_prog_aux *aux)
9147 {
9148 	struct scx_dispatch_q *dsq;
9149 	struct scx_sched *sch;
9150 	struct scx_dsp_ctx *dspc;
9151 
9152 	guard(rcu)();
9153 
9154 	sch = scx_prog_sched(aux);
9155 	if (unlikely(!sch))
9156 		return false;
9157 
9158 	if (!scx_vet_enq_flags(sch, SCX_DSQ_LOCAL, &enq_flags))
9159 		return false;
9160 
9161 	dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
9162 
9163 	scx_flush_dispatch_buf(sch, dspc->rq);
9164 
9165 	dsq = find_user_dsq(sch, dsq_id);
9166 	if (unlikely(!dsq)) {
9167 		scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id);
9168 		return false;
9169 	}
9170 
9171 	if (scx_consume_dispatch_q(sch, dspc->rq, dsq, enq_flags)) {
9172 		/*
9173 		 * A successfully consumed task can be dequeued before it starts
9174 		 * running while the CPU is trying to migrate other dispatched
9175 		 * tasks. Bump nr_tasks to tell dispatch_one() to retry on empty
9176 		 * local DSQ.
9177 		 */
9178 		dspc->nr_tasks++;
9179 		return true;
9180 	} else {
9181 		return false;
9182 	}
9183 }
9184 
9185 /*
9186  * COMPAT: ___v2 was introduced in v7.1. Remove this and ___v2 tag in the future.
9187  */
scx_bpf_dsq_move_to_local(u64 dsq_id,const struct bpf_prog_aux * aux)9188 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id, const struct bpf_prog_aux *aux)
9189 {
9190 	return scx_bpf_dsq_move_to_local___v2(dsq_id, 0, aux);
9191 }
9192 
9193 /**
9194  * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs
9195  * @it__iter: DSQ iterator in progress
9196  * @slice: duration the moved task can run for in nsecs
9197  *
9198  * Override the slice of the next task that will be moved from @it__iter using
9199  * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous
9200  * slice duration is kept.
9201  */
scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq * it__iter,u64 slice)9202 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter,
9203 					    u64 slice)
9204 {
9205 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
9206 
9207 	kit->slice = slice;
9208 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE;
9209 }
9210 
9211 /**
9212  * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs
9213  * @it__iter: DSQ iterator in progress
9214  * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ
9215  *
9216  * Override the vtime of the next task that will be moved from @it__iter using
9217  * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice
9218  * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the
9219  * override is ignored and cleared.
9220  */
scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq * it__iter,u64 vtime)9221 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter,
9222 					    u64 vtime)
9223 {
9224 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
9225 
9226 	kit->vtime = vtime;
9227 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME;
9228 }
9229 
9230 /**
9231  * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ
9232  * @it__iter: DSQ iterator in progress
9233  * @p: task to transfer
9234  * @dsq_id: DSQ to move @p to
9235  * @enq_flags: SCX_ENQ_*
9236  *
9237  * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ
9238  * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can
9239  * be the destination.
9240  *
9241  * For the transfer to be successful, @p must still be on the DSQ and have been
9242  * queued before the DSQ iteration started. This function doesn't care whether
9243  * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have
9244  * been queued before the iteration started.
9245  *
9246  * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update.
9247  *
9248  * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq
9249  * lock (e.g. BPF timers or SYSCALL programs).
9250  *
9251  * Returns %true if @p has been consumed, %false if @p had already been
9252  * consumed, dequeued, or, for sub-scheds, @dsq_id points to a disallowed local
9253  * DSQ.
9254  */
scx_bpf_dsq_move(struct bpf_iter_scx_dsq * it__iter,struct task_struct * p,u64 dsq_id,u64 enq_flags)9255 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter,
9256 				  struct task_struct *p, u64 dsq_id,
9257 				  u64 enq_flags)
9258 {
9259 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
9260 			    p, dsq_id, enq_flags, false);
9261 }
9262 
9263 /**
9264  * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ
9265  * @it__iter: DSQ iterator in progress
9266  * @p: task to transfer
9267  * @dsq_id: DSQ to move @p to
9268  * @enq_flags: SCX_ENQ_*
9269  *
9270  * Transfer @p which is on the DSQ currently iterated by @it__iter to the
9271  * priority queue of the DSQ specified by @dsq_id. The destination must be a
9272  * user DSQ as only user DSQs support priority queue.
9273  *
9274  * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice()
9275  * and scx_bpf_dsq_move_set_vtime() to update.
9276  *
9277  * All other aspects are identical to scx_bpf_dsq_move(). See
9278  * scx_bpf_dsq_insert_vtime() for more information on @vtime.
9279  */
scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq * it__iter,struct task_struct * p,u64 dsq_id,u64 enq_flags)9280 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter,
9281 					struct task_struct *p, u64 dsq_id,
9282 					u64 enq_flags)
9283 {
9284 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
9285 			    p, dsq_id, enq_flags, true);
9286 }
9287 
9288 __bpf_kfunc_end_defs();
9289 
9290 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
9291 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots, KF_IMPLICIT_ARGS)
9292 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel, KF_IMPLICIT_ARGS)
9293 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local, KF_IMPLICIT_ARGS)
9294 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local___v2, KF_IMPLICIT_ARGS)
9295 /* scx_bpf_dsq_move*() also in scx_kfunc_ids_unlocked: callable from unlocked contexts */
9296 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
9297 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
9298 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
9299 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
9300 #ifdef CONFIG_EXT_SUB_SCHED
9301 BTF_ID_FLAGS(func, scx_bpf_sub_dispatch, KF_IMPLICIT_ARGS)
9302 #endif
9303 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
9304 
9305 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
9306 	.owner			= THIS_MODULE,
9307 	.set			= &scx_kfunc_ids_dispatch,
9308 	.filter			= scx_kfunc_context_filter,
9309 };
9310 
9311 __bpf_kfunc_start_defs();
9312 
9313 /**
9314  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
9315  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9316  *
9317  * Iterate over all of the tasks currently enqueued on the local DSQ of the
9318  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
9319  * processed tasks. Can only be called from ops.cpu_release().
9320  */
scx_bpf_reenqueue_local(const struct bpf_prog_aux * aux)9321 __bpf_kfunc u32 scx_bpf_reenqueue_local(const struct bpf_prog_aux *aux)
9322 {
9323 	struct scx_sched *sch;
9324 	struct rq *rq;
9325 
9326 	guard(rcu)();
9327 	sch = scx_prog_sched(aux);
9328 	if (unlikely(!sch))
9329 		return 0;
9330 
9331 	rq = cpu_rq(smp_processor_id());
9332 	lockdep_assert_rq_held(rq);
9333 
9334 	return reenq_local(sch, rq, SCX_REENQ_ANY);
9335 }
9336 
9337 __bpf_kfunc_end_defs();
9338 
9339 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
9340 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local, KF_IMPLICIT_ARGS)
9341 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
9342 
9343 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
9344 	.owner			= THIS_MODULE,
9345 	.set			= &scx_kfunc_ids_cpu_release,
9346 	.filter			= scx_kfunc_context_filter,
9347 };
9348 
9349 __bpf_kfunc_start_defs();
9350 
9351 /**
9352  * scx_bpf_create_dsq - Create a custom DSQ
9353  * @dsq_id: DSQ to create
9354  * @node: NUMA node to allocate from
9355  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9356  *
9357  * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable
9358  * scx callback, and any BPF_PROG_TYPE_SYSCALL prog.
9359  */
scx_bpf_create_dsq(u64 dsq_id,s32 node,const struct bpf_prog_aux * aux)9360 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node, const struct bpf_prog_aux *aux)
9361 {
9362 	struct scx_dispatch_q *dsq;
9363 	struct scx_sched *sch;
9364 	s32 ret;
9365 
9366 	if (unlikely(node >= (int)nr_node_ids ||
9367 		     (node < 0 && node != NUMA_NO_NODE)))
9368 		return -EINVAL;
9369 
9370 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN))
9371 		return -EINVAL;
9372 
9373 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
9374 	if (!dsq)
9375 		return -ENOMEM;
9376 
9377 	/*
9378 	 * scx_init_dsq() must be called in GFP_KERNEL context. Init it with
9379 	 * NULL @sch and update afterwards.
9380 	 */
9381 	ret = scx_init_dsq(dsq, dsq_id, NULL);
9382 	if (ret) {
9383 		kfree(dsq);
9384 		return ret;
9385 	}
9386 
9387 	rcu_read_lock();
9388 
9389 	sch = scx_prog_sched(aux);
9390 	if (sch) {
9391 		dsq->sched = sch;
9392 		ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node,
9393 						    dsq_hash_params);
9394 	} else {
9395 		ret = -ENODEV;
9396 	}
9397 
9398 	rcu_read_unlock();
9399 	if (ret) {
9400 		exit_dsq(dsq);
9401 		kfree(dsq);
9402 	}
9403 	return ret;
9404 }
9405 
9406 __bpf_kfunc_end_defs();
9407 
9408 BTF_KFUNCS_START(scx_kfunc_ids_unlocked)
9409 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_IMPLICIT_ARGS | KF_SLEEPABLE)
9410 /* also in scx_kfunc_ids_dispatch: also callable from ops.dispatch() */
9411 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
9412 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
9413 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
9414 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
9415 /* also in scx_kfunc_ids_select_cpu: also callable from ops.select_cpu()/ops.enqueue() */
9416 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU)
9417 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU)
9418 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU)
9419 BTF_KFUNCS_END(scx_kfunc_ids_unlocked)
9420 
9421 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = {
9422 	.owner			= THIS_MODULE,
9423 	.set			= &scx_kfunc_ids_unlocked,
9424 	.filter			= scx_kfunc_context_filter,
9425 };
9426 
9427 __bpf_kfunc_start_defs();
9428 
9429 /**
9430  * scx_bpf_task_set_slice - Set task's time slice
9431  * @p: task of interest
9432  * @slice: time slice to set in nsecs
9433  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9434  *
9435  * Set @p's time slice. @p must be on the calling scheduler. The value is
9436  * applied whether or not the caller holds @p's rq lock - see the slice write
9437  * rules above for the ownership model.
9438  *
9439  * Raising the slice is honored only while the scheduler holds %SCX_CAP_BASE on
9440  * @p's cpu, otherwise it is counted in %SCX_EV_SLICE_DENIED. Shortening is
9441  * always allowed. On the stashed path the slice is packed into an atomic64_t
9442  * with the scheduler id and a flag bit, so a slice too large to fit is clamped
9443  * and counted in %SCX_EV_SLICE_CLAMPED. %SCX_SLICE_INF is preserved.
9444  *
9445  * Return %true on success, %false if @p is not on the calling scheduler.
9446  */
scx_bpf_task_set_slice(struct task_struct * p,u64 slice,const struct bpf_prog_aux * aux)9447 __bpf_kfunc bool scx_bpf_task_set_slice(struct task_struct *p, u64 slice,
9448 					const struct bpf_prog_aux *aux)
9449 {
9450 	struct scx_sched *sch;
9451 	struct rq *locked_rq;
9452 
9453 	guard(rcu)();
9454 	sch = scx_prog_sched(aux);
9455 	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
9456 		return false;
9457 
9458 	/*
9459 	 * Directly write only when we hold the lock of the rq @p is queued or
9460 	 * running on. See the write rules above.
9461 	 *
9462 	 * While @p is queued on a user DSQ or in the BPF scheduler,
9463 	 * synchronization is the scheduler's responsibility. This write can
9464 	 * race a concurrent dispatch's commit, see apply_slice_vtime().
9465 	 *
9466 	 * Making this kfunc always go through the oob stash would leave the
9467 	 * commit as the only direct writer and close the race, but that would
9468 	 * require two more oob application points - the dispatch keep-prev test
9469 	 * and the tick-time expiry check.
9470 	 */
9471 	locked_rq = scx_locked_rq();
9472 	if (!locked_rq ||
9473 	    (READ_ONCE(p->scx.runnable_cpu) != cpu_of(locked_rq) &&
9474 	     !task_current(locked_rq, p))) {
9475 		set_task_slice_oob(sch, p, slice);
9476 		return true;
9477 	}
9478 
9479 	/* under the rq lock: apply now, extensions gated on baseline access */
9480 	if (slice > p->scx.slice &&
9481 	    unlikely(scx_missing_caps(sch, cpu_of(locked_rq), SCX_CAP_BASE))) {
9482 		__scx_add_event(sch, SCX_EV_SLICE_DENIED, 1);
9483 		return true;
9484 	}
9485 
9486 	if (unlikely(!scx_set_task_slice(p, slice)))
9487 		__scx_add_event(sch, SCX_EV_SLICE_DENIED, 1);
9488 
9489 	return true;
9490 }
9491 
9492 /**
9493  * scx_bpf_task_set_dsq_vtime - Set task's virtual time for DSQ ordering
9494  * @p: task of interest
9495  * @vtime: virtual time to set
9496  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9497  *
9498  * Set @p's virtual time to @vtime. Returns %true on success, %false if the
9499  * calling scheduler doesn't have authority over @p.
9500  */
scx_bpf_task_set_dsq_vtime(struct task_struct * p,u64 vtime,const struct bpf_prog_aux * aux)9501 __bpf_kfunc bool scx_bpf_task_set_dsq_vtime(struct task_struct *p, u64 vtime,
9502 					    const struct bpf_prog_aux *aux)
9503 {
9504 	struct scx_sched *sch;
9505 
9506 	guard(rcu)();
9507 	sch = scx_prog_sched(aux);
9508 	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
9509 		return false;
9510 
9511 	p->scx.dsq_vtime = vtime;
9512 	return true;
9513 }
9514 
scx_kick_cpu(struct scx_sched * sch,s32 cpu,u64 flags)9515 void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags)
9516 {
9517 	struct scx_sched_pcpu *pcpu;
9518 	struct rq *this_rq;
9519 	unsigned long irq_flags;
9520 
9521 	/*
9522 	 * The per-cpu kick list is guarded only by local_irq_save(), which does
9523 	 * not mask NMIs, so kicking from NMI could corrupt it and is unsupported.
9524 	 */
9525 	if (unlikely(in_nmi())) {
9526 		scx_error(sch, "scx_bpf_kick_cpu() called from NMI");
9527 		return;
9528 	}
9529 
9530 	local_irq_save(irq_flags);
9531 
9532 	this_rq = this_rq();
9533 	pcpu = this_cpu_ptr(sch->pcpu);
9534 
9535 	/*
9536 	 * While bypassing for PM ops, IRQ handling may not be online which can
9537 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
9538 	 * IRQ status update. Suppress kicking.
9539 	 */
9540 	if (scx_bypassing(sch, cpu_of(this_rq)))
9541 		goto out;
9542 
9543 	/*
9544 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
9545 	 * rq locks. We can probably be smarter and avoid bouncing if called
9546 	 * from ops which don't hold a rq lock.
9547 	 *
9548 	 * The kick masks are owned by @sch->pcpu, so that a preempt kick can be
9549 	 * attributed to @sch.
9550 	 */
9551 	if (flags & SCX_KICK_IDLE) {
9552 		struct rq *target_rq = cpu_rq(cpu);
9553 
9554 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT)))
9555 			scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
9556 
9557 		if (raw_spin_rq_trylock(target_rq)) {
9558 			if (can_skip_idle_kick(target_rq)) {
9559 				scx_rq_lock_drop(target_rq);
9560 				raw_spin_rq_unlock(target_rq);
9561 				goto out;
9562 			}
9563 			scx_rq_lock_drop(target_rq);
9564 			raw_spin_rq_unlock(target_rq);
9565 		}
9566 		cpumask_set_cpu(cpu, pcpu->cpus_to_kick_if_idle);
9567 	} else {
9568 		cpumask_set_cpu(cpu, pcpu->cpus_to_kick);
9569 
9570 		if (flags & SCX_KICK_PREEMPT)
9571 			cpumask_set_cpu(cpu, pcpu->cpus_to_preempt);
9572 		if (flags & SCX_KICK_WAIT)
9573 			cpumask_set_cpu(cpu, pcpu->cpus_to_wait);
9574 	}
9575 
9576 	if (list_empty(&pcpu->to_kick_node))
9577 		list_add_tail(&pcpu->to_kick_node, &this_rq->scx.sched_pcpus_to_kick);
9578 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
9579 out:
9580 	local_irq_restore(irq_flags);
9581 }
9582 
9583 /**
9584  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
9585  * @cpu: cpu to kick
9586  * @flags: %SCX_KICK_* flags
9587  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9588  *
9589  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
9590  * trigger rescheduling on a busy CPU. This can be called from any online
9591  * scx_ops operation and the actual kicking is performed asynchronously through
9592  * an irq work.
9593  */
scx_bpf_kick_cpu(s32 cpu,u64 flags,const struct bpf_prog_aux * aux)9594 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags, const struct bpf_prog_aux *aux)
9595 {
9596 	struct scx_sched *sch;
9597 
9598 	guard(rcu)();
9599 	sch = scx_prog_sched(aux);
9600 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
9601 		scx_kick_cpu(sch, cpu, flags);
9602 }
9603 
9604 /**
9605  * scx_bpf_kick_cid - Trigger reschedule on the CPU mapped to @cid
9606  * @cid: cid to kick
9607  * @flags: %SCX_KICK_* flags
9608  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9609  *
9610  * cid-addressed equivalent of scx_bpf_kick_cpu(). An invalid @cid aborts the
9611  * scheduler via scx_cid_to_cpu(). Caps are enforced on the delivery path: a
9612  * kick is dropped if the caller lacks baseline access on @cid, and a
9613  * %SCX_KICK_PREEMPT degrades to a plain reschedule if the caller lacks
9614  * %SCX_CAP_PREEMPT for a task outside its subtree.
9615  */
scx_bpf_kick_cid(s32 cid,u64 flags,const struct bpf_prog_aux * aux)9616 __bpf_kfunc void scx_bpf_kick_cid(s32 cid, u64 flags, const struct bpf_prog_aux *aux)
9617 {
9618 	struct scx_sched *sch;
9619 	s32 cpu;
9620 
9621 	guard(rcu)();
9622 	sch = scx_prog_sched(aux);
9623 	if (unlikely(!sch))
9624 		return;
9625 	cpu = scx_cid_to_cpu(sch, cid);
9626 	if (cpu < 0)
9627 		return;
9628 	scx_kick_cpu(sch, cpu, flags);
9629 }
9630 
9631 /**
9632  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
9633  * @dsq_id: id of the DSQ
9634  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9635  *
9636  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
9637  * -%ENOENT is returned.
9638  *
9639  * %SCX_DSQ_LOCAL resolves to the local DSQ of the rq the current scheduler
9640  * operation is locked to - e.g. the rq being dispatched for in ops.dispatch() -
9641  * or the calling CPU's when no rq is locked.
9642  */
scx_bpf_dsq_nr_queued(u64 dsq_id,const struct bpf_prog_aux * aux)9643 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id, const struct bpf_prog_aux *aux)
9644 {
9645 	struct scx_sched *sch;
9646 	struct scx_dispatch_q *dsq;
9647 	s32 ret;
9648 
9649 	preempt_disable();
9650 
9651 	sch = scx_prog_sched(aux);
9652 	if (unlikely(!sch)) {
9653 		ret = -ENODEV;
9654 		goto out;
9655 	}
9656 
9657 	if (dsq_id == SCX_DSQ_LOCAL) {
9658 		ret = READ_ONCE((scx_locked_rq() ?: this_rq())->scx.local_dsq.nr);
9659 		goto out;
9660 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
9661 		s32 cpu = scx_cpu_ret(sch, dsq_id & SCX_DSQ_LOCAL_CPU_MASK);
9662 
9663 		if (scx_cpu_valid(sch, cpu, NULL)) {
9664 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
9665 			goto out;
9666 		}
9667 	} else {
9668 		dsq = find_user_dsq(sch, dsq_id);
9669 		if (dsq) {
9670 			ret = READ_ONCE(dsq->nr);
9671 			goto out;
9672 		}
9673 	}
9674 	ret = -ENOENT;
9675 out:
9676 	preempt_enable();
9677 	return ret;
9678 }
9679 
9680 /**
9681  * scx_bpf_destroy_dsq - Destroy a custom DSQ
9682  * @dsq_id: DSQ to destroy
9683  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9684  *
9685  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
9686  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
9687  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
9688  * which doesn't exist. Can be called from any online scx_ops operations.
9689  */
scx_bpf_destroy_dsq(u64 dsq_id,const struct bpf_prog_aux * aux)9690 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id, const struct bpf_prog_aux *aux)
9691 {
9692 	struct scx_sched *sch;
9693 
9694 	guard(rcu)();
9695 	sch = scx_prog_sched(aux);
9696 	if (sch)
9697 		destroy_dsq(sch, dsq_id);
9698 }
9699 
9700 /**
9701  * bpf_iter_scx_dsq_new - Create a DSQ iterator
9702  * @it: iterator to initialize
9703  * @dsq_id: DSQ to iterate
9704  * @flags: %SCX_DSQ_ITER_*
9705  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9706  *
9707  * Initialize BPF iterator @it which can be used with bpf_for_each() to walk
9708  * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes
9709  * tasks which are already queued when this function is invoked.
9710  */
bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq * it,u64 dsq_id,u64 flags,const struct bpf_prog_aux * aux)9711 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id,
9712 				     u64 flags, const struct bpf_prog_aux *aux)
9713 {
9714 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
9715 	struct scx_sched *sch;
9716 
9717 	BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) >
9718 		     sizeof(struct bpf_iter_scx_dsq));
9719 	BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) !=
9720 		     __alignof__(struct bpf_iter_scx_dsq));
9721 	BUILD_BUG_ON(__SCX_DSQ_ITER_ALL_FLAGS &
9722 		     ((1U << __SCX_DSQ_LNODE_PRIV_SHIFT) - 1));
9723 
9724 	/*
9725 	 * next() and destroy() will be called regardless of the return value.
9726 	 * Always clear $kit->dsq.
9727 	 */
9728 	kit->dsq = NULL;
9729 
9730 	sch = scx_prog_sched(aux);
9731 	if (unlikely(!sch))
9732 		return -ENODEV;
9733 
9734 	if (flags & ~__SCX_DSQ_ITER_USER_FLAGS)
9735 		return -EINVAL;
9736 
9737 	kit->dsq = find_user_dsq(sch, dsq_id);
9738 	if (!kit->dsq)
9739 		return -ENOENT;
9740 
9741 	kit->cursor = INIT_DSQ_LIST_CURSOR(kit->cursor, kit->dsq, flags);
9742 
9743 	return 0;
9744 }
9745 
9746 /**
9747  * bpf_iter_scx_dsq_next - Progress a DSQ iterator
9748  * @it: iterator to progress
9749  *
9750  * Return the next task. See bpf_iter_scx_dsq_new().
9751  */
bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq * it)9752 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it)
9753 {
9754 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
9755 
9756 	if (!kit->dsq)
9757 		return NULL;
9758 
9759 	guard(raw_spinlock_irqsave)(&kit->dsq->lock);
9760 
9761 	return nldsq_cursor_next_task(&kit->cursor, kit->dsq);
9762 }
9763 
9764 /**
9765  * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator
9766  * @it: iterator to destroy
9767  *
9768  * Undo scx_iter_scx_dsq_new().
9769  */
bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq * it)9770 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it)
9771 {
9772 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
9773 
9774 	if (!kit->dsq)
9775 		return;
9776 
9777 	if (!list_empty(&kit->cursor.node)) {
9778 		unsigned long flags;
9779 
9780 		raw_spin_lock_irqsave(&kit->dsq->lock, flags);
9781 		list_del_init(&kit->cursor.node);
9782 		raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
9783 	}
9784 	kit->dsq = NULL;
9785 }
9786 
9787 /**
9788  * scx_bpf_dsq_peek - Lockless peek at the first element.
9789  * @dsq_id: DSQ to examine.
9790  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9791  *
9792  * Read the first element in the DSQ. This is semantically equivalent to using
9793  * the DSQ iterator, but is lockfree. Of course, like any lockless operation,
9794  * this provides only a point-in-time snapshot, and the contents may change
9795  * by the time any subsequent locking operation reads the queue.
9796  *
9797  * Returns the pointer, or NULL indicates an empty queue OR internal error.
9798  */
scx_bpf_dsq_peek(u64 dsq_id,const struct bpf_prog_aux * aux)9799 __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id,
9800 						 const struct bpf_prog_aux *aux)
9801 {
9802 	struct scx_sched *sch;
9803 	struct scx_dispatch_q *dsq;
9804 
9805 	sch = scx_prog_sched(aux);
9806 	if (unlikely(!sch))
9807 		return NULL;
9808 
9809 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) {
9810 		scx_error(sch, "peek disallowed on builtin DSQ 0x%llx", dsq_id);
9811 		return NULL;
9812 	}
9813 
9814 	dsq = find_user_dsq(sch, dsq_id);
9815 	if (unlikely(!dsq)) {
9816 		scx_error(sch, "peek on non-existent DSQ 0x%llx", dsq_id);
9817 		return NULL;
9818 	}
9819 
9820 	return rcu_dereference(dsq->first_task);
9821 }
9822 
9823 /**
9824  * scx_bpf_dsq_reenq - Re-enqueue tasks on a DSQ
9825  * @dsq_id: DSQ to re-enqueue
9826  * @reenq_flags: %SCX_RENQ_*
9827  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9828  *
9829  * Iterate over all of the tasks currently enqueued on the DSQ identified by
9830  * @dsq_id, and re-enqueue them in the BPF scheduler. The following DSQs are
9831  * supported:
9832  *
9833  * - Local DSQs (%SCX_DSQ_LOCAL or %SCX_DSQ_LOCAL_ON | $cpu)
9834  * - User DSQs
9835  *
9836  * Re-enqueues are performed asynchronously. Can be called from anywhere.
9837  *
9838  * %SCX_DSQ_LOCAL resolves to the local DSQ of the rq the current scheduler
9839  * operation is locked to - e.g. the rq being dispatched for in ops.dispatch() -
9840  * or the calling CPU's when no rq is locked.
9841  */
scx_bpf_dsq_reenq(u64 dsq_id,u64 reenq_flags,const struct bpf_prog_aux * aux)9842 __bpf_kfunc void scx_bpf_dsq_reenq(u64 dsq_id, u64 reenq_flags,
9843 				   const struct bpf_prog_aux *aux)
9844 {
9845 	struct rq *locked_rq = scx_locked_rq();
9846 	struct scx_sched *sch;
9847 	struct scx_dispatch_q *dsq;
9848 
9849 	guard(preempt)();
9850 
9851 	sch = scx_prog_sched(aux);
9852 	if (unlikely(!sch))
9853 		return;
9854 
9855 	if (unlikely(reenq_flags & ~__SCX_REENQ_USER_MASK)) {
9856 		scx_error(sch, "invalid SCX_REENQ flags 0x%llx", reenq_flags);
9857 		return;
9858 	}
9859 
9860 	/* not specifying any filter bits is the same as %SCX_REENQ_ANY */
9861 	if (!(reenq_flags & __SCX_REENQ_FILTER_MASK))
9862 		reenq_flags |= SCX_REENQ_ANY;
9863 
9864 	dsq = find_dsq_for_dispatch(sch, locked_rq ?: this_rq(), dsq_id, smp_processor_id());
9865 	schedule_dsq_reenq(sch, dsq, reenq_flags, locked_rq);
9866 }
9867 
9868 /**
9869  * scx_bpf_reenqueue_local___v2 - Re-enqueue tasks on a local DSQ
9870  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9871  *
9872  * Iterate over all of the tasks currently enqueued on the local DSQ of the
9873  * caller's CPU, and re-enqueue them in the BPF scheduler. Can be called from
9874  * anywhere.
9875  *
9876  * This is now a special case of scx_bpf_dsq_reenq() and may be removed in the
9877  * future.
9878  */
scx_bpf_reenqueue_local___v2(const struct bpf_prog_aux * aux)9879 __bpf_kfunc void scx_bpf_reenqueue_local___v2(const struct bpf_prog_aux *aux)
9880 {
9881 	scx_bpf_dsq_reenq(SCX_DSQ_LOCAL, 0, aux);
9882 }
9883 
9884 __bpf_kfunc_end_defs();
9885 
9886 __printf(5, 0)
__bstr_format(struct scx_sched * sch,u64 * data_buf,char * line_buf,size_t line_size,char * fmt,unsigned long long * data,u32 data__sz)9887 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
9888 			 size_t line_size, char *fmt, unsigned long long *data,
9889 			 u32 data__sz)
9890 {
9891 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
9892 	s32 ret;
9893 
9894 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
9895 	    (data__sz && !data)) {
9896 		scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz);
9897 		return -EINVAL;
9898 	}
9899 
9900 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
9901 	if (ret < 0) {
9902 		scx_error(sch, "failed to read data fields (%d)", ret);
9903 		return ret;
9904 	}
9905 
9906 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
9907 				  &bprintf_data);
9908 	if (ret < 0) {
9909 		scx_error(sch, "format preparation failed (%d)", ret);
9910 		return ret;
9911 	}
9912 
9913 	ret = bstr_printf(line_buf, line_size, fmt,
9914 			  bprintf_data.bin_args);
9915 	bpf_bprintf_cleanup(&bprintf_data);
9916 	if (ret < 0) {
9917 		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
9918 		return ret;
9919 	}
9920 
9921 	return ret;
9922 }
9923 
9924 /*
9925  * Exit @sch with the reason formatted from a BPF-supplied bstr format. The exit
9926  * is claimed first and the reason is formatted directly into the winner-owned
9927  * exit_info buffer, which allows use from any context including NMI.
9928  *
9929  * @fmt_blame is the sched blamed for formatting failures through the
9930  * scx_error() calls in __bstr_format() and differs from @sch when a parent
9931  * supplies the kill reason for a child. A formatting failure doesn't revert the
9932  * claim - @sch still exits with the claimed kind and a fallback message.
9933  */
9934 __printf(5, 0)
scx_exit_bstr(struct scx_sched * sch,enum scx_exit_kind kind,s64 exit_code,struct scx_sched * fmt_blame,char * fmt,unsigned long long * data,u32 data__sz)9935 bool scx_exit_bstr(struct scx_sched *sch, enum scx_exit_kind kind,
9936 		   s64 exit_code, struct scx_sched *fmt_blame, char *fmt,
9937 		   unsigned long long *data, u32 data__sz)
9938 {
9939 	struct scx_exit_info *ei = sch->exit_info;
9940 	u64 data_buf[MAX_BPRINTF_VARARGS];
9941 	s32 ret;
9942 
9943 	guard(preempt)();
9944 
9945 	if (!scx_claim_exit(sch, kind))
9946 		return false;
9947 
9948 	ret = __bstr_format(fmt_blame, data_buf, ei->msg, SCX_EXIT_MSG_LEN,
9949 			    fmt, data, data__sz);
9950 	if (ret < 0)
9951 		scnprintf(ei->msg, SCX_EXIT_MSG_LEN,
9952 			  "exit message formatting failed (%d)", ret);
9953 
9954 	scx_finish_exit(sch, kind, exit_code, raw_smp_processor_id());
9955 	return true;
9956 }
9957 
9958 __bpf_kfunc_start_defs();
9959 
9960 /**
9961  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
9962  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
9963  * @fmt: error message format string
9964  * @data: format string parameters packaged using ___bpf_fill() macro
9965  * @data__sz: @data len, must end in '__sz' for the verifier
9966  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9967  *
9968  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
9969  * disabling.
9970  */
9971 __printf(2, 0)
scx_bpf_exit_bstr(s64 exit_code,char * fmt,unsigned long long * data,u32 data__sz,const struct bpf_prog_aux * aux)9972 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
9973 				   unsigned long long *data, u32 data__sz,
9974 				   const struct bpf_prog_aux *aux)
9975 {
9976 	struct scx_sched *sch;
9977 
9978 	guard(rcu)();
9979 
9980 	sch = scx_prog_sched(aux);
9981 	if (likely(sch))
9982 		scx_exit_bstr(sch, SCX_EXIT_UNREG_BPF, exit_code, sch, fmt,
9983 			      data, data__sz);
9984 }
9985 
9986 /**
9987  * scx_bpf_error_bstr - Indicate fatal error
9988  * @fmt: error message format string
9989  * @data: format string parameters packaged using ___bpf_fill() macro
9990  * @data__sz: @data len, must end in '__sz' for the verifier
9991  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9992  *
9993  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
9994  * disabling.
9995  */
9996 __printf(1, 0)
scx_bpf_error_bstr(char * fmt,unsigned long long * data,u32 data__sz,const struct bpf_prog_aux * aux)9997 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
9998 				    u32 data__sz, const struct bpf_prog_aux *aux)
9999 {
10000 	struct scx_sched *sch;
10001 
10002 	guard(rcu)();
10003 
10004 	sch = scx_prog_sched(aux);
10005 	if (likely(sch))
10006 		scx_exit_bstr(sch, SCX_EXIT_ERROR_BPF, 0, sch, fmt, data,
10007 			      data__sz);
10008 }
10009 
10010 /**
10011  * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler
10012  * @fmt: format string
10013  * @data: format string parameters packaged using ___bpf_fill() macro
10014  * @data__sz: @data len, must end in '__sz' for the verifier
10015  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10016  *
10017  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
10018  * dump_task() to generate extra debug dump specific to the BPF scheduler.
10019  *
10020  * The extra dump may be multiple lines. A single line may be split over
10021  * multiple calls. The last line is automatically terminated.
10022  */
10023 __printf(1, 0)
scx_bpf_dump_bstr(char * fmt,unsigned long long * data,u32 data__sz,const struct bpf_prog_aux * aux)10024 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
10025 				   u32 data__sz, const struct bpf_prog_aux *aux)
10026 {
10027 	struct scx_sched *sch;
10028 	struct scx_dump_data *dd = &scx_dump_data;
10029 	struct scx_bstr_buf *buf = &dd->buf;
10030 	s32 ret;
10031 
10032 	guard(rcu)();
10033 
10034 	sch = scx_prog_sched(aux);
10035 	if (unlikely(!sch))
10036 		return;
10037 
10038 	if (raw_smp_processor_id() != dd->cpu) {
10039 		scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends");
10040 		return;
10041 	}
10042 
10043 	/* append the formatted string to the line buf */
10044 	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
10045 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
10046 	if (ret < 0) {
10047 		scx_dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
10048 			      dd->prefix, fmt, data, data__sz, ret);
10049 		return;
10050 	}
10051 
10052 	dd->cursor += ret;
10053 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
10054 
10055 	if (!dd->cursor)
10056 		return;
10057 
10058 	/*
10059 	 * If the line buf overflowed or ends in a newline, flush it into the
10060 	 * dump. This is to allow the caller to generate a single line over
10061 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
10062 	 * the line buf, the only case which can lead to an unexpected
10063 	 * truncation is when the caller keeps generating newlines in the middle
10064 	 * instead of the end consecutively. Don't do that.
10065 	 */
10066 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
10067 		ops_dump_flush();
10068 }
10069 
10070 /**
10071  * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU
10072  * @cpu: CPU of interest
10073  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10074  *
10075  * Return the maximum relative capacity of @cpu in relation to the most
10076  * performant CPU in the system. The return value is in the range [1,
10077  * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur().
10078  */
scx_bpf_cpuperf_cap(s32 cpu,const struct bpf_prog_aux * aux)10079 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu, const struct bpf_prog_aux *aux)
10080 {
10081 	struct scx_sched *sch;
10082 
10083 	guard(rcu)();
10084 
10085 	sch = scx_prog_sched(aux);
10086 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
10087 		return arch_scale_cpu_capacity(cpu);
10088 	else
10089 		return SCX_CPUPERF_ONE;
10090 }
10091 
10092 /**
10093  * scx_bpf_cidperf_cap - Query the maximum relative capacity of the CPU at @cid
10094  * @cid: cid of the CPU to query
10095  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10096  *
10097  * cid-addressed equivalent of scx_bpf_cpuperf_cap().
10098  */
scx_bpf_cidperf_cap(s32 cid,const struct bpf_prog_aux * aux)10099 __bpf_kfunc u32 scx_bpf_cidperf_cap(s32 cid, const struct bpf_prog_aux *aux)
10100 {
10101 	struct scx_sched *sch;
10102 	s32 cpu;
10103 
10104 	guard(rcu)();
10105 
10106 	sch = scx_prog_sched(aux);
10107 	if (unlikely(!sch))
10108 		return SCX_CPUPERF_ONE;
10109 	cpu = scx_cid_to_cpu(sch, cid);
10110 	if (cpu < 0)
10111 		return SCX_CPUPERF_ONE;
10112 	return arch_scale_cpu_capacity(cpu);
10113 }
10114 
10115 /**
10116  * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU
10117  * @cpu: CPU of interest
10118  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10119  *
10120  * Return the current relative performance of @cpu in relation to its maximum.
10121  * The return value is in the range [1, %SCX_CPUPERF_ONE].
10122  *
10123  * The current performance level of a CPU in relation to the maximum performance
10124  * available in the system can be calculated as follows:
10125  *
10126  *   scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE
10127  *
10128  * The result is in the range [1, %SCX_CPUPERF_ONE].
10129  */
scx_bpf_cpuperf_cur(s32 cpu,const struct bpf_prog_aux * aux)10130 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu, const struct bpf_prog_aux *aux)
10131 {
10132 	struct scx_sched *sch;
10133 
10134 	guard(rcu)();
10135 
10136 	sch = scx_prog_sched(aux);
10137 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
10138 		return arch_scale_freq_capacity(cpu);
10139 	else
10140 		return SCX_CPUPERF_ONE;
10141 }
10142 
10143 /**
10144  * scx_bpf_cidperf_cur - Query the current performance of the CPU at @cid
10145  * @cid: cid of the CPU to query
10146  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10147  *
10148  * cid-addressed equivalent of scx_bpf_cpuperf_cur().
10149  */
scx_bpf_cidperf_cur(s32 cid,const struct bpf_prog_aux * aux)10150 __bpf_kfunc u32 scx_bpf_cidperf_cur(s32 cid, const struct bpf_prog_aux *aux)
10151 {
10152 	struct scx_sched *sch;
10153 	s32 cpu;
10154 
10155 	guard(rcu)();
10156 
10157 	sch = scx_prog_sched(aux);
10158 	if (unlikely(!sch))
10159 		return SCX_CPUPERF_ONE;
10160 	cpu = scx_cid_to_cpu(sch, cid);
10161 	if (cpu < 0)
10162 		return SCX_CPUPERF_ONE;
10163 	return arch_scale_freq_capacity(cpu);
10164 }
10165 
10166 /* validate and apply a cpuperf target, see scx_bpf_cpuperf_set() */
scx_cpuperf_set(struct scx_sched * sch,s32 cpu,u32 perf)10167 static s32 scx_cpuperf_set(struct scx_sched *sch, s32 cpu, u32 perf)
10168 {
10169 	struct rq *rq, *locked_rq;
10170 	struct rq_flags rf;
10171 	s32 ret;
10172 
10173 	if (unlikely(perf > SCX_CPUPERF_ONE)) {
10174 		scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu);
10175 		return -EINVAL;
10176 	}
10177 
10178 	if (!scx_cpu_valid(sch, cpu, NULL))
10179 		return -EINVAL;
10180 
10181 	rq = cpu_rq(cpu);
10182 	locked_rq = scx_locked_rq();
10183 
10184 	/*
10185 	 * When called with an rq lock held, restrict the operation to the
10186 	 * corresponding CPU to prevent ABBA deadlocks.
10187 	 */
10188 	if (locked_rq && rq != locked_rq) {
10189 		scx_error(sch, "Invalid target CPU %d", cpu);
10190 		return -EINVAL;
10191 	}
10192 
10193 	/*
10194 	 * If no rq lock is held, allow to operate on any CPU by acquiring
10195 	 * the corresponding rq lock.
10196 	 */
10197 	if (!locked_rq) {
10198 		rq_lock_irqsave(rq, &rf);
10199 		update_rq_clock(rq);
10200 	}
10201 
10202 	/*
10203 	 * ecaps updates are folded under the rq lock, making this test
10204 	 * authoritative: a write can never land after a revoke has taken
10205 	 * effect on @cpu.
10206 	 */
10207 	if (likely(!scx_missing_caps(sch, cpu, SCX_CAP_PERF))) {
10208 		rq->scx.cpuperf_target = perf;
10209 		cpufreq_update_util(rq, 0);
10210 		ret = 0;
10211 	} else {
10212 		__scx_add_event(sch, SCX_EV_SUB_CIDPERF_DENIED, 1);
10213 		ret = -EACCES;
10214 	}
10215 
10216 	if (!locked_rq)
10217 		rq_unlock_irqrestore(rq, &rf);
10218 
10219 	return ret;
10220 }
10221 
10222 /**
10223  * scx_bpf_cpuperf_set - Set the relative performance target of a CPU
10224  * @cpu: CPU of interest
10225  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
10226  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10227  *
10228  * Set the target performance level of @cpu to @perf. @perf is in linear
10229  * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the
10230  * schedutil cpufreq governor chooses the target frequency.
10231  *
10232  * The actual performance level chosen, CPU grouping, and the overhead and
10233  * latency of the operations are dependent on the hardware and cpufreq driver in
10234  * use. Consult hardware and cpufreq documentation for more information. The
10235  * current performance level can be monitored using scx_bpf_cpuperf_cur().
10236  */
scx_bpf_cpuperf_set(s32 cpu,u32 perf,const struct bpf_prog_aux * aux)10237 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf, const struct bpf_prog_aux *aux)
10238 {
10239 	struct scx_sched *sch;
10240 
10241 	guard(rcu)();
10242 
10243 	sch = scx_prog_sched(aux);
10244 	if (unlikely(!sch))
10245 		return;
10246 
10247 	scx_cpuperf_set(sch, cpu, perf);
10248 }
10249 
10250 /**
10251  * scx_bpf_cidperf_set - Set the performance target of the CPU at @cid
10252  * @cid: cid of the CPU to target
10253  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
10254  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10255  *
10256  * cid-addressed equivalent of scx_bpf_cpuperf_set(). A sub-sched needs
10257  * SCX_CAP_PERF on @cid. Returns 0 if the target was applied, -%EACCES if
10258  * the write was denied for missing caps, other -errnos if @cid didn't
10259  * resolve.
10260  */
scx_bpf_cidperf_set(s32 cid,u32 perf,const struct bpf_prog_aux * aux)10261 __bpf_kfunc s32 scx_bpf_cidperf_set(s32 cid, u32 perf,
10262 				    const struct bpf_prog_aux *aux)
10263 {
10264 	struct scx_sched *sch;
10265 	s32 cpu;
10266 
10267 	guard(rcu)();
10268 
10269 	sch = scx_prog_sched(aux);
10270 	if (unlikely(!sch))
10271 		return -ENODEV;
10272 	cpu = scx_cid_to_cpu(sch, cid);
10273 	if (cpu < 0)
10274 		return cpu;
10275 
10276 	return scx_cpuperf_set(sch, cpu, perf);
10277 }
10278 
10279 /**
10280  * scx_bpf_nr_node_ids - Return the number of possible node IDs
10281  *
10282  * All valid node IDs in the system are smaller than the returned value.
10283  */
scx_bpf_nr_node_ids(void)10284 __bpf_kfunc u32 scx_bpf_nr_node_ids(void)
10285 {
10286 	return nr_node_ids;
10287 }
10288 
10289 /**
10290  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
10291  *
10292  * All valid CPU IDs in the system are smaller than the returned value.
10293  */
scx_bpf_nr_cpu_ids(void)10294 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
10295 {
10296 	return nr_cpu_ids;
10297 }
10298 
10299 /**
10300  * scx_bpf_nr_cids - Return the size of the cid space
10301  *
10302  * Equals num_possible_cpus(). All valid cids are in [0, return value).
10303  */
scx_bpf_nr_cids(void)10304 __bpf_kfunc u32 scx_bpf_nr_cids(void)
10305 {
10306 	return num_possible_cpus();
10307 }
10308 
10309 /**
10310  * scx_bpf_nr_online_cids - Return current count of online CPUs in cid space
10311  *
10312  * Return num_online_cpus(). The standard model restarts the scheduler on
10313  * hotplug, which lets schedulers treat [0, nr_online_cids) as the online
10314  * range. Schedulers that prefer to handle hotplug without a restart should
10315  * install a custom mapping via scx_bpf_cid_override() and track onlining
10316  * through the ops.cid_online / ops.cid_offline callbacks.
10317  */
scx_bpf_nr_online_cids(void)10318 __bpf_kfunc u32 scx_bpf_nr_online_cids(void)
10319 {
10320 	return num_online_cpus();
10321 }
10322 
10323 /**
10324  * scx_bpf_this_cid - Return the cid of the CPU this program is running on
10325  *
10326  * cid-addressed equivalent of bpf_get_smp_processor_id() for scx programs.
10327  * The current cpu is trivially valid, so this is just a table lookup. Return
10328  * -EINVAL if called before any scheduler has ever published its cid tables.
10329  */
scx_bpf_this_cid(void)10330 __bpf_kfunc s32 scx_bpf_this_cid(void)
10331 {
10332 	s16 *tbl;
10333 
10334 	guard(rcu)();
10335 
10336 	tbl = rcu_dereference(scx_cpu_to_cid_tbl);
10337 	if (!tbl)
10338 		return -EINVAL;
10339 	return tbl[raw_smp_processor_id()];
10340 }
10341 
10342 /**
10343  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
10344  */
scx_bpf_get_possible_cpumask(void)10345 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
10346 {
10347 	return cpu_possible_mask;
10348 }
10349 
10350 /**
10351  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
10352  */
scx_bpf_get_online_cpumask(void)10353 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
10354 {
10355 	return cpu_online_mask;
10356 }
10357 
10358 /**
10359  * scx_bpf_put_cpumask - Release a possible/online cpumask
10360  * @cpumask: cpumask to release
10361  */
scx_bpf_put_cpumask(const struct cpumask * cpumask)10362 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
10363 {
10364 	/*
10365 	 * Empty function body because we aren't actually acquiring or releasing
10366 	 * a reference to a global cpumask, which is read-only in the caller and
10367 	 * is never released. The acquire / release semantics here are just used
10368 	 * to make the cpumask is a trusted pointer in the caller.
10369 	 */
10370 }
10371 
10372 /**
10373  * scx_bpf_task_running - Is task currently running?
10374  * @p: task of interest
10375  */
scx_bpf_task_running(const struct task_struct * p)10376 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
10377 {
10378 	return task_rq(p)->curr == p;
10379 }
10380 
10381 /**
10382  * scx_bpf_task_cpu - CPU a task is currently associated with
10383  * @p: task of interest
10384  */
scx_bpf_task_cpu(const struct task_struct * p)10385 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
10386 {
10387 	return task_cpu(p);
10388 }
10389 
10390 /**
10391  * scx_bpf_task_cid - cid a task is currently associated with
10392  * @p: task of interest
10393  *
10394  * cid-addressed equivalent of scx_bpf_task_cpu(). task_cpu(p) is always a
10395  * valid cpu, so this is just a table lookup. Return -EINVAL if called before
10396  * any scheduler has ever published its cid tables.
10397  */
scx_bpf_task_cid(const struct task_struct * p)10398 __bpf_kfunc s32 scx_bpf_task_cid(const struct task_struct *p)
10399 {
10400 	s16 *tbl;
10401 
10402 	/* KF_RCU covers only @p - a sleepable program holds no RCU lock */
10403 	guard(rcu)();
10404 
10405 	tbl = rcu_dereference(scx_cpu_to_cid_tbl);
10406 	if (!tbl)
10407 		return -EINVAL;
10408 	return tbl[task_cpu(p)];
10409 }
10410 
10411 /**
10412  * scx_bpf_locked_rq - Return the rq currently locked by SCX
10413  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10414  *
10415  * Returns the rq if a rq lock is currently held by SCX.
10416  * Otherwise emits an error and returns NULL.
10417  */
scx_bpf_locked_rq(const struct bpf_prog_aux * aux)10418 __bpf_kfunc struct rq *scx_bpf_locked_rq(const struct bpf_prog_aux *aux)
10419 {
10420 	struct scx_sched *sch;
10421 	struct rq *rq;
10422 
10423 	guard(preempt)();
10424 
10425 	sch = scx_prog_sched(aux);
10426 	if (unlikely(!sch))
10427 		return NULL;
10428 
10429 	rq = scx_locked_rq();
10430 	if (!rq) {
10431 		scx_error(sch, "accessing rq without holding rq lock");
10432 		return NULL;
10433 	}
10434 
10435 	return rq;
10436 }
10437 
10438 /**
10439  * scx_bpf_cpu_curr - Return remote CPU's curr task
10440  * @cpu: CPU of interest
10441  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10442  *
10443  * Callers must hold RCU read lock (KF_RCU).
10444  */
scx_bpf_cpu_curr(s32 cpu,const struct bpf_prog_aux * aux)10445 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_aux *aux)
10446 {
10447 	struct scx_sched *sch;
10448 
10449 	guard(rcu)();
10450 
10451 	sch = scx_prog_sched(aux);
10452 	if (unlikely(!sch))
10453 		return NULL;
10454 
10455 	if (!scx_cpu_valid(sch, cpu, NULL))
10456 		return NULL;
10457 
10458 	return rcu_dereference(cpu_rq(cpu)->curr);
10459 }
10460 
10461 /**
10462  * scx_bpf_cid_curr - Return the curr task on the CPU at @cid
10463  * @cid: cid of interest
10464  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10465  *
10466  * cid-addressed equivalent of scx_bpf_cpu_curr(). Callers must hold RCU
10467  * read lock (KF_RCU).
10468  */
scx_bpf_cid_curr(s32 cid,const struct bpf_prog_aux * aux)10469 __bpf_kfunc struct task_struct *scx_bpf_cid_curr(s32 cid, const struct bpf_prog_aux *aux)
10470 {
10471 	struct scx_sched *sch;
10472 	s32 cpu;
10473 
10474 	guard(rcu)();
10475 
10476 	sch = scx_prog_sched(aux);
10477 	if (unlikely(!sch))
10478 		return NULL;
10479 	cpu = scx_cid_to_cpu(sch, cid);
10480 	if (cpu < 0)
10481 		return NULL;
10482 	return rcu_dereference(cpu_rq(cpu)->curr);
10483 }
10484 
10485 /**
10486  * scx_bpf_tid_to_task - Look up a task by its scx tid
10487  * @tid: task ID previously read from p->scx.tid
10488  *
10489  * Returns the task with the given tid, or NULL if no such task exists. The
10490  * returned pointer is valid until the end of the current RCU read section
10491  * (KF_RCU_PROTECTED). Requires SCX_OPS_TID_TO_TASK to be set on the root
10492  * scheduler; otherwise an error is raised and NULL returned.
10493  */
scx_bpf_tid_to_task(u64 tid)10494 __bpf_kfunc struct task_struct *scx_bpf_tid_to_task(u64 tid)
10495 {
10496 	struct sched_ext_entity *scx;
10497 
10498 	if (!scx_tid_to_task_enabled()) {
10499 		struct scx_sched *sch = rcu_dereference(scx_root);
10500 
10501 		if (sch)
10502 			scx_error(sch, "scx_bpf_tid_to_task() called without SCX_OPS_TID_TO_TASK");
10503 		return NULL;
10504 	}
10505 
10506 	scx = rhashtable_lookup(&scx_tid_hash, &tid, scx_tid_hash_params);
10507 	if (!scx)
10508 		return NULL;
10509 
10510 	return container_of(scx, struct task_struct, scx);
10511 }
10512 
__scx_bpf_now(struct rq * rq)10513 u64 __scx_bpf_now(struct rq *rq)
10514 {
10515 	/* the caller must be on @rq's cpu or hold its lock */
10516 	lockdep_assert((rq == this_rq() && !preemptible()) ||
10517 		       lockdep_is_held(__rq_lockp(rq)));
10518 
10519 	if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) {
10520 		/* if the rq clock is valid, use the cached rq clock */
10521 		return READ_ONCE(rq->scx.clock);
10522 	} else {
10523 		/*
10524 		 * Otherwise, return a fresh rq clock.
10525 		 *
10526 		 * The rq clock is updated outside of the rq lock.
10527 		 * In this case, keep the updated rq clock invalid so the next
10528 		 * read outside the rq lock gets a fresh rq clock.
10529 		 */
10530 		return sched_clock_cpu(cpu_of(rq));
10531 	}
10532 }
10533 
10534 /**
10535  * scx_bpf_now - Returns a high-performance monotonically non-decreasing
10536  * clock for the current CPU. The clock returned is in nanoseconds.
10537  *
10538  * It provides the following properties:
10539  *
10540  * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently
10541  *  to account for execution time and track tasks' runtime properties.
10542  *  Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which
10543  *  eventually reads a hardware timestamp counter -- is neither performant nor
10544  *  scalable. scx_bpf_now() aims to provide a high-performance clock by
10545  *  using the rq clock in the scheduler core whenever possible.
10546  *
10547  * 2) High enough resolution for the BPF scheduler use cases: In most BPF
10548  *  scheduler use cases, the required clock resolution is lower than the most
10549  *  accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically
10550  *  uses the rq clock in the scheduler core whenever it is valid. It considers
10551  *  that the rq clock is valid from the time the rq clock is updated
10552  *  (update_rq_clock) until the rq is unlocked (rq_unpin_lock).
10553  *
10554  * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now()
10555  *  guarantees the clock never goes backward when comparing them in the same
10556  *  CPU. On the other hand, when comparing clocks in different CPUs, there
10557  *  is no such guarantee -- the clock can go backward. It provides a
10558  *  monotonically *non-decreasing* clock so that it would provide the same
10559  *  clock values in two different scx_bpf_now() calls in the same CPU
10560  *  during the same period of when the rq clock is valid.
10561  */
scx_bpf_now(void)10562 __bpf_kfunc u64 scx_bpf_now(void)
10563 {
10564 	/*
10565 	 * Note that scx_bpf_now() is re-entrant between a process context and
10566 	 * an interrupt context (e.g., timer interrupt). However, we don't need
10567 	 * to consider the race between them because such race is not observable
10568 	 * from a caller.
10569 	 */
10570 	guard(preempt)();
10571 	return __scx_bpf_now(this_rq());
10572 }
10573 
scx_read_events(struct scx_sched * sch,struct scx_event_stats * events)10574 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events)
10575 {
10576 	int cpu;
10577 
10578 	/* Aggregate per-CPU event counters into @events. */
10579 	memset(events, 0, sizeof(*events));
10580 	for_each_possible_cpu(cpu) {
10581 		struct scx_event_stats *e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats;
10582 #define SCX_EVENT(name)	(events->name += READ_ONCE(e_cpu->name))
10583 		SCX_EVENTS_LIST(SCX_EVENT);
10584 #undef SCX_EVENT
10585 	}
10586 }
10587 
10588 /**
10589  * scx_bpf_events - Read the event counters of the calling scheduler
10590  * @events: output buffer from a BPF program
10591  * @events__sz: @events len, must end in '__sz' for the verifier
10592  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10593  *
10594  * Read the event counters of the scheduler associated with the calling program.
10595  * @events is zeroed when no scheduler can be resolved.
10596  */
scx_bpf_events(struct scx_event_stats * events,size_t events__sz,const struct bpf_prog_aux * aux)10597 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events, size_t events__sz,
10598 				const struct bpf_prog_aux *aux)
10599 {
10600 	struct scx_sched *sch;
10601 	struct scx_event_stats e_sys;
10602 
10603 	rcu_read_lock();
10604 	sch = scx_prog_sched(aux);
10605 	if (sch)
10606 		scx_read_events(sch, &e_sys);
10607 	else
10608 		memset(&e_sys, 0, sizeof(e_sys));
10609 	rcu_read_unlock();
10610 
10611 	/*
10612 	 * We cannot entirely trust a BPF-provided size since a BPF program
10613 	 * might be compiled against a different vmlinux.h, of which
10614 	 * scx_event_stats would be larger (a newer vmlinux.h) or smaller
10615 	 * (an older vmlinux.h). Hence, we use the smaller size to avoid
10616 	 * memory corruption.
10617 	 */
10618 	events__sz = min(events__sz, sizeof(*events));
10619 	memcpy(events, &e_sys, events__sz);
10620 }
10621 
10622 #ifdef CONFIG_CGROUP_SCHED
10623 /**
10624  * scx_bpf_task_cgroup - Return the sched cgroup of a task
10625  * @p: task of interest
10626  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10627  *
10628  * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with
10629  * from the scheduler's POV. SCX operations should use this function to
10630  * determine @p's current cgroup as, unlike following @p->cgroups,
10631  * @p->sched_task_group is stable for the duration of the SCX op. See
10632  * SCX_CALL_OP_TASK() for details.
10633  */
scx_bpf_task_cgroup(struct task_struct * p,const struct bpf_prog_aux * aux)10634 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p,
10635 					       const struct bpf_prog_aux *aux)
10636 {
10637 	struct task_group *tg = p->sched_task_group;
10638 	struct cgroup *cgrp = &cgrp_dfl_root.cgrp;
10639 	struct scx_sched *sch;
10640 
10641 	guard(rcu)();
10642 
10643 	sch = scx_prog_sched(aux);
10644 	if (unlikely(!sch))
10645 		goto out;
10646 
10647 	if (!scx_kf_arg_task_ok(sch, p))
10648 		goto out;
10649 
10650 	cgrp = tg_cgrp(tg);
10651 
10652 out:
10653 	cgroup_get(cgrp);
10654 	return cgrp;
10655 }
10656 #endif	/* CONFIG_CGROUP_SCHED */
10657 
10658 __bpf_kfunc_end_defs();
10659 
10660 BTF_KFUNCS_START(scx_kfunc_ids_any)
10661 BTF_ID_FLAGS(func, scx_bpf_task_set_slice, KF_IMPLICIT_ARGS | KF_RCU);
10662 BTF_ID_FLAGS(func, scx_bpf_task_set_dsq_vtime, KF_IMPLICIT_ARGS | KF_RCU);
10663 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
10664 BTF_ID_FLAGS(func, scx_bpf_kick_cid, KF_IMPLICIT_ARGS)
10665 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued, KF_IMPLICIT_ARGS)
10666 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS)
10667 BTF_ID_FLAGS(func, scx_bpf_dsq_peek, KF_IMPLICIT_ARGS | KF_RCU_PROTECTED | KF_RET_NULL)
10668 BTF_ID_FLAGS(func, scx_bpf_dsq_reenq, KF_IMPLICIT_ARGS)
10669 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local___v2, KF_IMPLICIT_ARGS)
10670 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_IMPLICIT_ARGS | KF_ITER_NEW | KF_RCU_PROTECTED)
10671 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
10672 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
10673 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_IMPLICIT_ARGS)
10674 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_IMPLICIT_ARGS)
10675 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_IMPLICIT_ARGS)
10676 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS)
10677 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS)
10678 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
10679 BTF_ID_FLAGS(func, scx_bpf_cidperf_cap, KF_IMPLICIT_ARGS)
10680 BTF_ID_FLAGS(func, scx_bpf_cidperf_cur, KF_IMPLICIT_ARGS)
10681 BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS)
10682 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
10683 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
10684 BTF_ID_FLAGS(func, scx_bpf_nr_cids)
10685 BTF_ID_FLAGS(func, scx_bpf_nr_online_cids)
10686 BTF_ID_FLAGS(func, scx_bpf_this_cid)
10687 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
10688 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
10689 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
10690 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
10691 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
10692 BTF_ID_FLAGS(func, scx_bpf_task_cid, KF_RCU)
10693 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL)
10694 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
10695 BTF_ID_FLAGS(func, scx_bpf_cid_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
10696 BTF_ID_FLAGS(func, scx_bpf_tid_to_task, KF_RET_NULL | KF_RCU_PROTECTED)
10697 BTF_ID_FLAGS(func, scx_bpf_now)
10698 BTF_ID_FLAGS(func, scx_bpf_events, KF_IMPLICIT_ARGS)
10699 #ifdef CONFIG_CGROUP_SCHED
10700 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_IMPLICIT_ARGS | KF_RCU | KF_ACQUIRE)
10701 #endif
10702 BTF_ID_FLAGS(func, scx_bpf_sub_grant, KF_IMPLICIT_ARGS)
10703 BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS)
10704 BTF_ID_FLAGS(func, scx_bpf_sub_caps, KF_IMPLICIT_ARGS)
10705 BTF_ID_FLAGS(func, scx_bpf_sub_kill_bstr, KF_IMPLICIT_ARGS)
10706 BTF_KFUNCS_END(scx_kfunc_ids_any)
10707 
10708 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
10709 	.owner			= THIS_MODULE,
10710 	.set			= &scx_kfunc_ids_any,
10711 	.filter			= scx_kfunc_context_filter,
10712 };
10713 
10714 /*
10715  * cpu-form kfuncs that are forbidden from cid-form schedulers
10716  * (bpf_sched_ext_ops_cid). Programs targeting the cid struct_ops type must
10717  * use the cid-form alternative (cid/cmask kfuncs).
10718  *
10719  * Membership overlaps with scx_kfunc_ids_{any,idle,select_cpu}; the filter
10720  * tests this set independently and rejects matches before the per-op
10721  * allow-list check runs.
10722  *
10723  * pahole/resolve_btfids scans every BTF_ID_FLAGS() at build time and
10724  * intersects flags across duplicate entries, so each entry must carry the
10725  * same flags as the kfunc's primary declaration; otherwise the flags get
10726  * dropped globally.
10727  */
10728 BTF_KFUNCS_START(scx_kfunc_ids_cpu_only)
10729 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
10730 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
10731 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
10732 BTF_ID_FLAGS(func, scx_bpf_cpu_node, KF_IMPLICIT_ARGS)
10733 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS)
10734 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS)
10735 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
10736 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
10737 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
10738 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
10739 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU)
10740 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU)
10741 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU)
10742 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10743 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10744 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10745 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10746 BTF_ID_FLAGS(func, scx_bpf_put_idle_cpumask, KF_RELEASE)
10747 BTF_ID_FLAGS(func, scx_bpf_test_and_clear_cpu_idle, KF_IMPLICIT_ARGS)
10748 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu, KF_IMPLICIT_ARGS | KF_RCU)
10749 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu_node, KF_IMPLICIT_ARGS | KF_RCU)
10750 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu, KF_IMPLICIT_ARGS | KF_RCU)
10751 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu_node, KF_IMPLICIT_ARGS | KF_RCU)
10752 BTF_KFUNCS_END(scx_kfunc_ids_cpu_only)
10753 
10754 /*
10755  * Per-op kfunc allow flags. Each bit corresponds to a context-sensitive kfunc
10756  * group; an op may permit zero or more groups, with the union expressed in
10757  * scx_kf_allow_flags[]. The verifier-time filter (scx_kfunc_context_filter())
10758  * consults this table to decide whether a context-sensitive kfunc is callable
10759  * from a given SCX op.
10760  */
10761 enum scx_kf_allow_flags {
10762 	SCX_KF_ALLOW_UNLOCKED		= 1 << 0,
10763 	SCX_KF_ALLOW_INIT_CIDS		= 1 << 1,
10764 	SCX_KF_ALLOW_CPU_RELEASE	= 1 << 2,
10765 	SCX_KF_ALLOW_DISPATCH		= 1 << 3,
10766 	SCX_KF_ALLOW_ENQUEUE		= 1 << 4,
10767 	SCX_KF_ALLOW_SELECT_CPU		= 1 << 5,
10768 };
10769 
10770 /*
10771  * Map each SCX op to the union of kfunc groups it permits, indexed by
10772  * SCX_OP_IDX(op). Ops not listed only permit kfuncs that are not
10773  * context-sensitive.
10774  */
10775 static const u32 scx_kf_allow_flags[] = {
10776 	[SCX_OP_IDX(select_cpu)]	= SCX_KF_ALLOW_SELECT_CPU | SCX_KF_ALLOW_ENQUEUE,
10777 	[SCX_OP_IDX(enqueue)]		= SCX_KF_ALLOW_SELECT_CPU | SCX_KF_ALLOW_ENQUEUE,
10778 	[SCX_OP_IDX(dispatch)]		= SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH,
10779 	[SCX_OP_IDX(cpu_release)]	= SCX_KF_ALLOW_CPU_RELEASE,
10780 	[SCX_OP_IDX(init_task)]		= SCX_KF_ALLOW_UNLOCKED,
10781 	[SCX_OP_IDX(dump)]		= SCX_KF_ALLOW_UNLOCKED,
10782 #ifdef CONFIG_EXT_GROUP_SCHED
10783 	[SCX_OP_IDX(cgroup_init)]	= SCX_KF_ALLOW_UNLOCKED,
10784 	[SCX_OP_IDX(cgroup_exit)]	= SCX_KF_ALLOW_UNLOCKED,
10785 	[SCX_OP_IDX(cgroup_prep_move)]	= SCX_KF_ALLOW_UNLOCKED,
10786 	[SCX_OP_IDX(cgroup_cancel_move)] = SCX_KF_ALLOW_UNLOCKED,
10787 	[SCX_OP_IDX(cgroup_set_weight)]	= SCX_KF_ALLOW_UNLOCKED,
10788 	[SCX_OP_IDX(cgroup_set_bandwidth)] = SCX_KF_ALLOW_UNLOCKED,
10789 	[SCX_OP_IDX(cgroup_set_idle)]	= SCX_KF_ALLOW_UNLOCKED,
10790 #endif	/* CONFIG_EXT_GROUP_SCHED */
10791 	[SCX_OP_IDX(sub_attach)]	= SCX_KF_ALLOW_UNLOCKED,
10792 	[SCX_OP_IDX(sub_detach)]	= SCX_KF_ALLOW_UNLOCKED,
10793 	[SCX_OP_IDX(sub_ecaps_updated)]	= SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH,
10794 	[SCX_OP_IDX(cpu_online)]	= SCX_KF_ALLOW_UNLOCKED,
10795 	[SCX_OP_IDX(cpu_offline)]	= SCX_KF_ALLOW_UNLOCKED,
10796 	[SCX_OP_IDX(init_cids)]		= SCX_KF_ALLOW_UNLOCKED | SCX_KF_ALLOW_INIT_CIDS,
10797 	[SCX_OP_IDX(init)]		= SCX_KF_ALLOW_UNLOCKED,
10798 	[SCX_OP_IDX(exit)]		= SCX_KF_ALLOW_UNLOCKED,
10799 };
10800 
10801 /*
10802  * Verifier-time filter for SCX kfuncs. Registered via the .filter field on
10803  * each per-group btf_kfunc_id_set. The BPF core invokes this for every kfunc
10804  * call in the registered hook (BPF_PROG_TYPE_STRUCT_OPS or
10805  * BPF_PROG_TYPE_SYSCALL), regardless of which set originally introduced the
10806  * kfunc - so the filter must short-circuit on kfuncs it doesn't govern by
10807  * falling through to "allow" when none of the SCX sets contain the kfunc.
10808  */
scx_kfunc_context_filter(const struct bpf_prog * prog,u32 kfunc_id)10809 int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id)
10810 {
10811 	bool in_unlocked = btf_id_set8_contains(&scx_kfunc_ids_unlocked, kfunc_id);
10812 	bool in_init_cids = btf_id_set8_contains(&scx_kfunc_ids_init_cids, kfunc_id);
10813 	bool in_select_cpu = btf_id_set8_contains(&scx_kfunc_ids_select_cpu, kfunc_id);
10814 	bool in_enqueue = btf_id_set8_contains(&scx_kfunc_ids_enqueue_dispatch, kfunc_id);
10815 	bool in_dispatch = btf_id_set8_contains(&scx_kfunc_ids_dispatch, kfunc_id);
10816 	bool in_cpu_release = btf_id_set8_contains(&scx_kfunc_ids_cpu_release, kfunc_id);
10817 	bool in_idle = btf_id_set8_contains(&scx_kfunc_ids_idle, kfunc_id);
10818 	bool in_any = btf_id_set8_contains(&scx_kfunc_ids_any, kfunc_id);
10819 	bool in_cpu_only = btf_id_set8_contains(&scx_kfunc_ids_cpu_only, kfunc_id);
10820 	bool in_cid = btf_id_set8_contains(&scx_kfunc_ids_cid, kfunc_id);
10821 	u32 moff, flags;
10822 
10823 	/* Not an SCX kfunc - allow. */
10824 	if (!(in_unlocked || in_init_cids || in_select_cpu || in_enqueue || in_dispatch ||
10825 	      in_cpu_release || in_idle || in_any || in_cid))
10826 		return 0;
10827 
10828 	/* SYSCALL progs (e.g. BPF test_run()) may call unlocked and select_cpu kfuncs. */
10829 	if (prog->type == BPF_PROG_TYPE_SYSCALL)
10830 		return (in_unlocked || in_select_cpu || in_idle || in_any || in_cid) ? 0 : -EACCES;
10831 
10832 	if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
10833 		return (in_any || in_idle || in_cid) ? 0 : -EACCES;
10834 
10835 	/*
10836 	 * add_subprog_and_kfunc() collects all kfunc calls, including dead code
10837 	 * guarded by bpf_ksym_exists(), before check_attach_btf_id() sets
10838 	 * prog->aux->st_ops. Allow all kfuncs when st_ops is not yet set;
10839 	 * do_check_main() re-runs the filter with st_ops set and enforces the
10840 	 * actual restrictions.
10841 	 */
10842 	if (!prog->aux->st_ops)
10843 		return 0;
10844 
10845 	/*
10846 	 * Non-SCX struct_ops: SCX kfuncs are not permitted.
10847 	 *
10848 	 * Both bpf_sched_ext_ops (cpu-form) and bpf_sched_ext_ops_cid
10849 	 * (cid-form) are valid SCX struct_ops. Member offsets match between
10850 	 * the two (verified by BUILD_BUG_ON in scx_init()), so the shared
10851 	 * scx_kf_allow_flags[] table indexed by SCX_MOFF_IDX(moff) applies to
10852 	 * both.
10853 	 */
10854 	if (prog->aux->st_ops != &bpf_sched_ext_ops &&
10855 	    prog->aux->st_ops != &bpf_sched_ext_ops_cid)
10856 		return -EACCES;
10857 
10858 	/*
10859 	 * cid-form schedulers must use cid/cmask kfuncs. cid and cpu are both
10860 	 * small s32s and trivially confused, so cpu-only kfuncs are rejected at
10861 	 * load time. The reverse (cpu-form calling cid-form kfuncs) is
10862 	 * intentionally permissive to ease gradual cpumask -> cid migration.
10863 	 */
10864 	if (prog->aux->st_ops == &bpf_sched_ext_ops_cid && in_cpu_only)
10865 		return -EACCES;
10866 
10867 	/* SCX struct_ops: check the per-op allow list. */
10868 	if (in_any || in_idle || in_cid)
10869 		return 0;
10870 
10871 	moff = prog->aux->attach_st_ops_member_off;
10872 	flags = scx_kf_allow_flags[SCX_MOFF_IDX(moff)];
10873 
10874 	if ((flags & SCX_KF_ALLOW_UNLOCKED) && in_unlocked)
10875 		return 0;
10876 	if ((flags & SCX_KF_ALLOW_INIT_CIDS) && in_init_cids)
10877 		return 0;
10878 	if ((flags & SCX_KF_ALLOW_CPU_RELEASE) && in_cpu_release)
10879 		return 0;
10880 	if ((flags & SCX_KF_ALLOW_DISPATCH) && in_dispatch)
10881 		return 0;
10882 	if ((flags & SCX_KF_ALLOW_ENQUEUE) && in_enqueue)
10883 		return 0;
10884 	if ((flags & SCX_KF_ALLOW_SELECT_CPU) && in_select_cpu)
10885 		return 0;
10886 
10887 	return -EACCES;
10888 }
10889 
scx_init(void)10890 static int __init scx_init(void)
10891 {
10892 	int ret;
10893 
10894 	/*
10895 	 * sched_ext_ops_cid mirrors sched_ext_ops up to and including @priv.
10896 	 * Both bpf_scx_init_member() and bpf_scx_check_member() use offsets
10897 	 * from struct sched_ext_ops; sched_ext_ops_cid relies on those offsets
10898 	 * matching for the shared fields. Catch any drift at boot.
10899 	 */
10900 #define CID_OFFSET_MATCH(cpu_field, cid_field)					\
10901 	BUILD_BUG_ON(offsetof(struct sched_ext_ops, cpu_field) !=		\
10902 		     offsetof(struct sched_ext_ops_cid, cid_field))
10903 	/* data fields used by bpf_scx_init_member() */
10904 	CID_OFFSET_MATCH(dispatch_max_batch, dispatch_max_batch);
10905 	CID_OFFSET_MATCH(flags, flags);
10906 	CID_OFFSET_MATCH(name, name);
10907 	CID_OFFSET_MATCH(timeout_ms, timeout_ms);
10908 	CID_OFFSET_MATCH(exit_dump_len, exit_dump_len);
10909 	CID_OFFSET_MATCH(hotplug_seq, hotplug_seq);
10910 	CID_OFFSET_MATCH(cid_shard_size, cid_shard_size);
10911 	CID_OFFSET_MATCH(rescue_bandwidth_ppt, rescue_bandwidth_ppt);
10912 	CID_OFFSET_MATCH(rescue_quantum_us, rescue_quantum_us);
10913 	CID_OFFSET_MATCH(sub_cgroup_id, sub_cgroup_id);
10914 	/* shared callbacks: the union view requires byte-for-byte offset match */
10915 	CID_OFFSET_MATCH(enqueue, enqueue);
10916 	CID_OFFSET_MATCH(dequeue, dequeue);
10917 	CID_OFFSET_MATCH(dispatch, dispatch);
10918 	CID_OFFSET_MATCH(tick, tick);
10919 	CID_OFFSET_MATCH(runnable, runnable);
10920 	CID_OFFSET_MATCH(running, running);
10921 	CID_OFFSET_MATCH(stopping, stopping);
10922 	CID_OFFSET_MATCH(quiescent, quiescent);
10923 	CID_OFFSET_MATCH(yield, yield);
10924 	CID_OFFSET_MATCH(core_sched_before, core_sched_before);
10925 	CID_OFFSET_MATCH(set_weight, set_weight);
10926 	CID_OFFSET_MATCH(update_idle, update_idle);
10927 	CID_OFFSET_MATCH(init_task, init_task);
10928 	CID_OFFSET_MATCH(exit_task, exit_task);
10929 	CID_OFFSET_MATCH(enable, enable);
10930 	CID_OFFSET_MATCH(disable, disable);
10931 	CID_OFFSET_MATCH(dump, dump);
10932 	CID_OFFSET_MATCH(dump_task, dump_task);
10933 	CID_OFFSET_MATCH(sub_attach, sub_attach);
10934 	CID_OFFSET_MATCH(sub_detach, sub_detach);
10935 	CID_OFFSET_MATCH(sub_caps_updated, sub_caps_updated);
10936 	CID_OFFSET_MATCH(sub_ecaps_updated, sub_ecaps_updated);
10937 	CID_OFFSET_MATCH(init_cids, init_cids);
10938 	CID_OFFSET_MATCH(init, init);
10939 	CID_OFFSET_MATCH(exit, exit);
10940 	/* renamed callbacks must occupy the same slot as their cpu-form sibling */
10941 	CID_OFFSET_MATCH(select_cpu, select_cid);
10942 	CID_OFFSET_MATCH(set_cpumask, set_cmask);
10943 	CID_OFFSET_MATCH(cpu_online, cid_online);
10944 	CID_OFFSET_MATCH(cpu_offline, cid_offline);
10945 	CID_OFFSET_MATCH(dump_cpu, dump_cid);
10946 #ifdef CONFIG_EXT_GROUP_SCHED
10947 	CID_OFFSET_MATCH(cgroup_init, cpuctl_init);
10948 	CID_OFFSET_MATCH(cgroup_exit, cpuctl_exit);
10949 	CID_OFFSET_MATCH(cgroup_prep_move, cpuctl_prep_move);
10950 	CID_OFFSET_MATCH(cgroup_move, cpuctl_move);
10951 	CID_OFFSET_MATCH(cgroup_cancel_move, cpuctl_cancel_move);
10952 	CID_OFFSET_MATCH(cgroup_set_weight, cpuctl_set_weight);
10953 	CID_OFFSET_MATCH(cgroup_set_bandwidth, cpuctl_set_bandwidth);
10954 	CID_OFFSET_MATCH(cgroup_set_idle, cpuctl_set_idle);
10955 #endif
10956 	/* @priv tail must align since both share the same data block */
10957 	CID_OFFSET_MATCH(priv, priv);
10958 	/*
10959 	 * cid-form must end exactly at @priv - scx_validate_ops() skips
10960 	 * cpu_acquire/cpu_release for cid-form because reading those fields
10961 	 * past the BPF allocation would be UB.
10962 	 */
10963 	BUILD_BUG_ON(offsetof(struct sched_ext_ops_cid, __end) !=
10964 		     offsetofend(struct sched_ext_ops, priv));
10965 #undef CID_OFFSET_MATCH
10966 
10967 	/*
10968 	 * kfunc registration can't be done from init_sched_ext_class() as
10969 	 * register_btf_kfunc_id_set() needs most of the system to be up.
10970 	 *
10971 	 * Some kfuncs are context-sensitive and can only be called from
10972 	 * specific SCX ops. They are grouped into per-context BTF sets, each
10973 	 * registered with scx_kfunc_context_filter as its .filter callback. The
10974 	 * BPF core dedups identical filter pointers per hook
10975 	 * (btf_populate_kfunc_set()), so the filter is invoked exactly once per
10976 	 * kfunc lookup; it consults scx_kf_allow_flags[] to enforce per-op
10977 	 * restrictions at verify time.
10978 	 */
10979 	if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
10980 					     &scx_kfunc_set_enqueue_dispatch)) ||
10981 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
10982 					     &scx_kfunc_set_dispatch)) ||
10983 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
10984 					     &scx_kfunc_set_cpu_release)) ||
10985 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
10986 					     &scx_kfunc_set_unlocked)) ||
10987 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
10988 					     &scx_kfunc_set_unlocked)) ||
10989 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
10990 					     &scx_kfunc_set_any)) ||
10991 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
10992 					     &scx_kfunc_set_any)) ||
10993 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
10994 					     &scx_kfunc_set_any))) {
10995 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
10996 		return ret;
10997 	}
10998 
10999 	ret = scx_idle_init();
11000 	if (ret) {
11001 		pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret);
11002 		return ret;
11003 	}
11004 
11005 	ret = scx_cid_kfunc_init();
11006 	if (ret) {
11007 		pr_err("sched_ext: Failed to register cid kfuncs (%d)\n", ret);
11008 		return ret;
11009 	}
11010 
11011 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops);
11012 	if (ret) {
11013 		pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret);
11014 		return ret;
11015 	}
11016 
11017 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops_cid, sched_ext_ops_cid);
11018 	if (ret) {
11019 		pr_err("sched_ext: Failed to register cid struct_ops (%d)\n", ret);
11020 		return ret;
11021 	}
11022 
11023 	ret = register_pm_notifier(&scx_pm_notifier);
11024 	if (ret) {
11025 		pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret);
11026 		return ret;
11027 	}
11028 
11029 	scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj);
11030 	if (!scx_kset) {
11031 		pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n");
11032 		return -ENOMEM;
11033 	}
11034 
11035 	ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group);
11036 	if (ret < 0) {
11037 		pr_err("sched_ext: Failed to add global attributes\n");
11038 		return ret;
11039 	}
11040 
11041 	return 0;
11042 }
11043 __initcall(scx_init);
11044