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