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