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