xref: /linux/kernel/sched/ext.c (revision cb251eae7b0aec8a7924fb27bcb5b0388a3706bc)
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 = container_of(kobj, struct scx_sched, kobj);
4846 
4847 	return add_uevent_var(env, "SCXOPS=%s", sch->ops.name);
4848 }
4849 
4850 static const struct kset_uevent_ops scx_uevent_ops = {
4851 	.uevent = scx_uevent,
4852 };
4853 
4854 /*
4855  * Used by sched_fork() and __setscheduler_prio() to pick the matching
4856  * sched_class. dl/rt are already handled.
4857  */
4858 bool task_should_scx(int policy)
4859 {
4860 	if (!scx_enabled() || unlikely(scx_enable_state() == SCX_DISABLING))
4861 		return false;
4862 	if (READ_ONCE(scx_switching_all))
4863 		return true;
4864 	return policy == SCHED_EXT;
4865 }
4866 
4867 bool scx_allow_ttwu_queue(const struct task_struct *p)
4868 {
4869 	struct scx_sched *sch;
4870 
4871 	if (!scx_enabled())
4872 		return true;
4873 
4874 	sch = scx_task_sched(p);
4875 	if (unlikely(!sch))
4876 		return true;
4877 
4878 	if (sch->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP)
4879 		return true;
4880 
4881 	if (unlikely(p->sched_class != &ext_sched_class))
4882 		return true;
4883 
4884 	return false;
4885 }
4886 
4887 /**
4888  * handle_lockup - sched_ext common lockup handler
4889  * @fmt: format string
4890  *
4891  * Called on system stall or lockup condition and initiates abort of sched_ext
4892  * if enabled, which may resolve the reported lockup.
4893  *
4894  * Returns %true if sched_ext is enabled and abort was initiated, which may
4895  * resolve the lockup. %false if sched_ext is not enabled or abort was already
4896  * initiated by someone else.
4897  */
4898 static __printf(1, 2) bool handle_lockup(const char *fmt, ...)
4899 {
4900 	struct scx_sched *sch;
4901 	va_list args;
4902 	bool ret;
4903 
4904 	guard(rcu)();
4905 
4906 	sch = rcu_dereference(scx_root);
4907 	if (unlikely(!sch))
4908 		return false;
4909 
4910 	switch (scx_enable_state()) {
4911 	case SCX_ENABLING:
4912 	case SCX_ENABLED:
4913 		va_start(args, fmt);
4914 		ret = scx_verror(sch, fmt, args);
4915 		va_end(args);
4916 		return ret;
4917 	default:
4918 		return false;
4919 	}
4920 }
4921 
4922 /**
4923  * scx_rcu_cpu_stall - sched_ext RCU CPU stall handler
4924  *
4925  * While there are various reasons why RCU CPU stalls can occur on a system
4926  * that may not be caused by the current BPF scheduler, try kicking out the
4927  * current scheduler in an attempt to recover the system to a good state before
4928  * issuing panics.
4929  *
4930  * Returns %true if sched_ext is enabled and abort was initiated, which may
4931  * resolve the reported RCU stall. %false if sched_ext is not enabled or someone
4932  * else already initiated abort.
4933  */
4934 bool scx_rcu_cpu_stall(void)
4935 {
4936 	return handle_lockup("RCU CPU stall detected!");
4937 }
4938 
4939 /**
4940  * scx_softlockup - sched_ext softlockup handler
4941  * @dur_s: number of seconds of CPU stuck due to soft lockup
4942  *
4943  * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can
4944  * live-lock the system by making many CPUs target the same DSQ to the point
4945  * where soft-lockup detection triggers. This function is called from
4946  * soft-lockup watchdog when the triggering point is close and tries to unjam
4947  * the system and aborting the BPF scheduler.
4948  */
4949 void scx_softlockup(u32 dur_s)
4950 {
4951 	if (!handle_lockup("soft lockup - CPU %d stuck for %us", smp_processor_id(), dur_s))
4952 		return;
4953 
4954 	printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU %d stuck for %us, disabling BPF scheduler\n",
4955 			smp_processor_id(), dur_s);
4956 }
4957 
4958 /**
4959  * scx_hardlockup - sched_ext hardlockup handler
4960  *
4961  * A poorly behaving BPF scheduler can trigger hard lockup by e.g. putting
4962  * numerous affinitized tasks in a single queue and directing all CPUs at it.
4963  * Try kicking out the current scheduler in an attempt to recover the system to
4964  * a good state before taking more drastic actions.
4965  *
4966  * Returns %true if sched_ext is enabled and abort was initiated, which may
4967  * resolve the reported hardlockup. %false if sched_ext is not enabled or
4968  * someone else already initiated abort.
4969  */
4970 bool scx_hardlockup(int cpu)
4971 {
4972 	if (!handle_lockup("hard lockup - CPU %d", cpu))
4973 		return false;
4974 
4975 	printk_deferred(KERN_ERR "sched_ext: Hard lockup - CPU %d, disabling BPF scheduler\n",
4976 			cpu);
4977 	return true;
4978 }
4979 
4980 static u32 bypass_lb_cpu(struct scx_sched *sch, s32 donor,
4981 			 struct cpumask *donee_mask, struct cpumask *resched_mask,
4982 			 u32 nr_donor_target, u32 nr_donee_target)
4983 {
4984 	struct rq *donor_rq = cpu_rq(donor);
4985 	struct scx_dispatch_q *donor_dsq = bypass_dsq(sch, donor);
4986 	struct task_struct *p, *n;
4987 	struct scx_dsq_list_node cursor = INIT_DSQ_LIST_CURSOR(cursor, donor_dsq, 0);
4988 	s32 delta = READ_ONCE(donor_dsq->nr) - nr_donor_target;
4989 	u32 nr_balanced = 0, min_delta_us;
4990 
4991 	/*
4992 	 * All we want to guarantee is reasonable forward progress. No reason to
4993 	 * fine tune. Assuming every task on @donor_dsq runs their full slice,
4994 	 * consider offloading iff the total queued duration is over the
4995 	 * threshold.
4996 	 */
4997 	min_delta_us = READ_ONCE(scx_bypass_lb_intv_us) / SCX_BYPASS_LB_MIN_DELTA_DIV;
4998 	if (delta < DIV_ROUND_UP(min_delta_us, READ_ONCE(scx_slice_bypass_us)))
4999 		return 0;
5000 
5001 	raw_spin_rq_lock_irq(donor_rq);
5002 	raw_spin_lock(&donor_dsq->lock);
5003 	list_add(&cursor.node, &donor_dsq->list);
5004 resume:
5005 	n = container_of(&cursor, struct task_struct, scx.dsq_list);
5006 	n = nldsq_next_task(donor_dsq, n, false);
5007 
5008 	while ((p = n)) {
5009 		struct scx_dispatch_q *donee_dsq;
5010 		int donee;
5011 
5012 		n = nldsq_next_task(donor_dsq, n, false);
5013 
5014 		if (donor_dsq->nr <= nr_donor_target)
5015 			break;
5016 
5017 		if (cpumask_empty(donee_mask))
5018 			break;
5019 
5020 		donee = cpumask_any_and_distribute(donee_mask, p->cpus_ptr);
5021 		if (donee >= nr_cpu_ids)
5022 			continue;
5023 
5024 		donee_dsq = bypass_dsq(sch, donee);
5025 
5026 		/*
5027 		 * $p's rq is not locked but $p's DSQ lock protects its
5028 		 * scheduling properties making this test safe.
5029 		 */
5030 		if (!task_can_run_on_remote_rq(sch, p, cpu_rq(donee), false))
5031 			continue;
5032 
5033 		/*
5034 		 * Moving $p from one non-local DSQ to another. The source rq
5035 		 * and DSQ are already locked. Do an abbreviated dequeue and
5036 		 * then perform enqueue without unlocking $donor_dsq.
5037 		 *
5038 		 * We don't want to drop and reacquire the lock on each
5039 		 * iteration as @donor_dsq can be very long and potentially
5040 		 * highly contended. Donee DSQs are less likely to be contended.
5041 		 * The nested locking is safe as only this LB moves tasks
5042 		 * between bypass DSQs.
5043 		 */
5044 		dispatch_dequeue_locked(p, donor_dsq);
5045 		dispatch_enqueue(sch, cpu_rq(donee), donee_dsq, p, SCX_ENQ_NESTED);
5046 
5047 		/*
5048 		 * $donee might have been idle and need to be woken up. No need
5049 		 * to be clever. Kick every CPU that receives tasks.
5050 		 */
5051 		cpumask_set_cpu(donee, resched_mask);
5052 
5053 		if (READ_ONCE(donee_dsq->nr) >= nr_donee_target)
5054 			cpumask_clear_cpu(donee, donee_mask);
5055 
5056 		nr_balanced++;
5057 		if (!(nr_balanced % SCX_BYPASS_LB_BATCH) && n) {
5058 			list_move_tail(&cursor.node, &n->scx.dsq_list.node);
5059 			raw_spin_unlock(&donor_dsq->lock);
5060 			raw_spin_rq_unlock_irq(donor_rq);
5061 			cpu_relax();
5062 			raw_spin_rq_lock_irq(donor_rq);
5063 			raw_spin_lock(&donor_dsq->lock);
5064 			goto resume;
5065 		}
5066 	}
5067 
5068 	list_del_init(&cursor.node);
5069 	raw_spin_unlock(&donor_dsq->lock);
5070 	raw_spin_rq_unlock_irq(donor_rq);
5071 
5072 	return nr_balanced;
5073 }
5074 
5075 static void bypass_lb_node(struct scx_sched *sch, int node)
5076 {
5077 	const struct cpumask *node_mask = cpumask_of_node(node);
5078 	struct cpumask *donee_mask = scx_bypass_lb_donee_cpumask;
5079 	struct cpumask *resched_mask = scx_bypass_lb_resched_cpumask;
5080 	u32 nr_tasks = 0, nr_cpus = 0, nr_balanced = 0;
5081 	u32 nr_target, nr_donor_target;
5082 	u32 before_min = U32_MAX, before_max = 0;
5083 	u32 after_min = U32_MAX, after_max = 0;
5084 	int cpu;
5085 
5086 	/* count the target tasks and CPUs */
5087 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5088 		u32 nr = READ_ONCE(bypass_dsq(sch, cpu)->nr);
5089 
5090 		nr_tasks += nr;
5091 		nr_cpus++;
5092 
5093 		before_min = min(nr, before_min);
5094 		before_max = max(nr, before_max);
5095 	}
5096 
5097 	if (!nr_cpus)
5098 		return;
5099 
5100 	/*
5101 	 * We don't want CPUs to have more than $nr_donor_target tasks and
5102 	 * balancing to fill donee CPUs upto $nr_target. Once targets are
5103 	 * calculated, find the donee CPUs.
5104 	 */
5105 	nr_target = DIV_ROUND_UP(nr_tasks, nr_cpus);
5106 	nr_donor_target = DIV_ROUND_UP(nr_target * SCX_BYPASS_LB_DONOR_PCT, 100);
5107 
5108 	cpumask_clear(donee_mask);
5109 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5110 		if (READ_ONCE(bypass_dsq(sch, cpu)->nr) < nr_target)
5111 			cpumask_set_cpu(cpu, donee_mask);
5112 	}
5113 
5114 	/* iterate !donee CPUs and see if they should be offloaded */
5115 	cpumask_clear(resched_mask);
5116 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5117 		if (cpumask_empty(donee_mask))
5118 			break;
5119 		if (cpumask_test_cpu(cpu, donee_mask))
5120 			continue;
5121 		if (READ_ONCE(bypass_dsq(sch, cpu)->nr) <= nr_donor_target)
5122 			continue;
5123 
5124 		nr_balanced += bypass_lb_cpu(sch, cpu, donee_mask, resched_mask,
5125 					     nr_donor_target, nr_target);
5126 	}
5127 
5128 	for_each_cpu(cpu, resched_mask)
5129 		resched_cpu(cpu);
5130 
5131 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5132 		u32 nr = READ_ONCE(bypass_dsq(sch, cpu)->nr);
5133 
5134 		after_min = min(nr, after_min);
5135 		after_max = max(nr, after_max);
5136 
5137 	}
5138 
5139 	trace_sched_ext_bypass_lb(node, nr_cpus, nr_tasks, nr_balanced,
5140 				  before_min, before_max, after_min, after_max);
5141 }
5142 
5143 /*
5144  * In bypass mode, all tasks are put on the per-CPU bypass DSQs. If the machine
5145  * is over-saturated and the BPF scheduler skewed tasks into few CPUs, some
5146  * bypass DSQs can be overloaded. If there are enough tasks to saturate other
5147  * lightly loaded CPUs, such imbalance can lead to very high execution latency
5148  * on the overloaded CPUs and thus to hung tasks and RCU stalls. To avoid such
5149  * outcomes, a simple load balancing mechanism is implemented by the following
5150  * timer which runs periodically while bypass mode is in effect.
5151  */
5152 static void scx_bypass_lb_timerfn(struct timer_list *timer)
5153 {
5154 	struct scx_sched *sch = container_of(timer, struct scx_sched, bypass_lb_timer);
5155 	int node;
5156 	u32 intv_us;
5157 
5158 	if (!bypass_dsp_enabled(sch))
5159 		return;
5160 
5161 	for_each_node_with_cpus(node)
5162 		bypass_lb_node(sch, node);
5163 
5164 	intv_us = READ_ONCE(scx_bypass_lb_intv_us);
5165 	if (intv_us)
5166 		mod_timer(timer, jiffies + usecs_to_jiffies(intv_us));
5167 }
5168 
5169 static bool inc_bypass_depth(struct scx_sched *sch)
5170 {
5171 	lockdep_assert_held(&scx_bypass_lock);
5172 
5173 	WARN_ON_ONCE(sch->bypass_depth < 0);
5174 	WRITE_ONCE(sch->bypass_depth, sch->bypass_depth + 1);
5175 	if (sch->bypass_depth != 1)
5176 		return false;
5177 
5178 	WRITE_ONCE(sch->slice_dfl, READ_ONCE(scx_slice_bypass_us) * NSEC_PER_USEC);
5179 	sch->bypass_timestamp = ktime_get_ns();
5180 	scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1);
5181 	return true;
5182 }
5183 
5184 static bool dec_bypass_depth(struct scx_sched *sch)
5185 {
5186 	lockdep_assert_held(&scx_bypass_lock);
5187 
5188 	WARN_ON_ONCE(sch->bypass_depth < 1);
5189 	WRITE_ONCE(sch->bypass_depth, sch->bypass_depth - 1);
5190 	if (sch->bypass_depth != 0)
5191 		return false;
5192 
5193 	WRITE_ONCE(sch->slice_dfl, SCX_SLICE_DFL);
5194 	scx_add_event(sch, SCX_EV_BYPASS_DURATION,
5195 		      ktime_get_ns() - sch->bypass_timestamp);
5196 	return true;
5197 }
5198 
5199 static void enable_bypass_dsp(struct scx_sched *sch)
5200 {
5201 	struct scx_sched *host = scx_parent(sch) ?: sch;
5202 	u32 intv_us = READ_ONCE(scx_bypass_lb_intv_us);
5203 	s32 ret;
5204 
5205 	/*
5206 	 * @sch->bypass_depth transitioning from 0 to 1 triggers enabling.
5207 	 * Shouldn't stagger.
5208 	 */
5209 	if (WARN_ON_ONCE(test_and_set_bit(0, &sch->bypass_dsp_claim)))
5210 		return;
5211 
5212 	/*
5213 	 * When a sub-sched bypasses, its tasks are queued on the bypass DSQs of
5214 	 * the nearest non-bypassing ancestor or root. As enable_bypass_dsp() is
5215 	 * called iff @sch is not already bypassed due to an ancestor bypassing,
5216 	 * we can assume that the parent is not bypassing and thus will be the
5217 	 * host of the bypass DSQs.
5218 	 *
5219 	 * While the situation may change in the future, the following
5220 	 * guarantees that the nearest non-bypassing ancestor or root has bypass
5221 	 * dispatch enabled while a descendant is bypassing, which is all that's
5222 	 * required.
5223 	 *
5224 	 * bypass_dsp_enabled() test is used to determine whether to enter the
5225 	 * bypass dispatch handling path from both bypassing and hosting scheds.
5226 	 * Bump enable depth on both @sch and bypass dispatch host.
5227 	 */
5228 	ret = atomic_inc_return(&sch->bypass_dsp_enable_depth);
5229 	WARN_ON_ONCE(ret <= 0);
5230 
5231 	if (host != sch) {
5232 		ret = atomic_inc_return(&host->bypass_dsp_enable_depth);
5233 		WARN_ON_ONCE(ret <= 0);
5234 	}
5235 
5236 	/*
5237 	 * The LB timer will stop running if bypass dispatch is disabled. Start
5238 	 * after enabling bypass dispatch.
5239 	 */
5240 	if (intv_us && !timer_pending(&host->bypass_lb_timer))
5241 		mod_timer(&host->bypass_lb_timer,
5242 			  jiffies + usecs_to_jiffies(intv_us));
5243 }
5244 
5245 /* may be called without holding scx_bypass_lock */
5246 static void disable_bypass_dsp(struct scx_sched *sch)
5247 {
5248 	s32 ret;
5249 
5250 	if (!test_and_clear_bit(0, &sch->bypass_dsp_claim))
5251 		return;
5252 
5253 	ret = atomic_dec_return(&sch->bypass_dsp_enable_depth);
5254 	WARN_ON_ONCE(ret < 0);
5255 
5256 	if (scx_parent(sch)) {
5257 		ret = atomic_dec_return(&scx_parent(sch)->bypass_dsp_enable_depth);
5258 		WARN_ON_ONCE(ret < 0);
5259 	}
5260 }
5261 
5262 /**
5263  * scx_bypass - [Un]bypass scx_ops and guarantee forward progress
5264  * @sch: sched to bypass
5265  * @bypass: true for bypass, false for unbypass
5266  *
5267  * Bypassing guarantees that all runnable tasks make forward progress without
5268  * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might
5269  * be held by tasks that the BPF scheduler is forgetting to run, which
5270  * unfortunately also excludes toggling the static branches.
5271  *
5272  * Let's work around by overriding a couple ops and modifying behaviors based on
5273  * the DISABLING state and then cycling the queued tasks through dequeue/enqueue
5274  * to force global FIFO scheduling.
5275  *
5276  * - ops.select_cpu() is ignored and the default select_cpu() is used.
5277  *
5278  * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order.
5279  *   %SCX_OPS_ENQ_LAST is also ignored.
5280  *
5281  * - ops.dispatch() is ignored.
5282  *
5283  * - balance_one() does not set %SCX_RQ_BAL_KEEP on non-zero slice as slice
5284  *   can't be trusted. Whenever a tick triggers, the running task is rotated to
5285  *   the tail of the queue with core_sched_at touched.
5286  *
5287  * - pick_next_task() suppresses zero slice warning.
5288  *
5289  * - scx_kick_cpu() is disabled to avoid irq_work malfunction during PM
5290  *   operations.
5291  *
5292  * - scx_prio_less() reverts to the default core_sched_at order.
5293  */
5294 static void scx_bypass(struct scx_sched *sch, bool bypass)
5295 {
5296 	struct scx_sched *pos;
5297 	unsigned long flags;
5298 	int cpu;
5299 
5300 	raw_spin_lock_irqsave(&scx_bypass_lock, flags);
5301 
5302 	if (bypass) {
5303 		if (!inc_bypass_depth(sch))
5304 			goto unlock;
5305 
5306 		enable_bypass_dsp(sch);
5307 	} else {
5308 		if (!dec_bypass_depth(sch))
5309 			goto unlock;
5310 	}
5311 
5312 	/*
5313 	 * Bypass state is propagated to all descendants - an scx_sched bypasses
5314 	 * if itself or any of its ancestors are in bypass mode.
5315 	 */
5316 	raw_spin_lock(&scx_sched_lock);
5317 	scx_for_each_descendant_pre(pos, sch) {
5318 		if (pos == sch)
5319 			continue;
5320 		if (bypass)
5321 			inc_bypass_depth(pos);
5322 		else
5323 			dec_bypass_depth(pos);
5324 	}
5325 	raw_spin_unlock(&scx_sched_lock);
5326 
5327 	/*
5328 	 * No task property is changing. We just need to make sure all currently
5329 	 * queued tasks are re-queued according to the new scx_bypassing()
5330 	 * state. As an optimization, walk each rq's runnable_list instead of
5331 	 * the scx_tasks list.
5332 	 *
5333 	 * This function can't trust the scheduler and thus can't use
5334 	 * cpus_read_lock(). Walk all possible CPUs instead of online.
5335 	 */
5336 	for_each_possible_cpu(cpu) {
5337 		struct rq *rq = cpu_rq(cpu);
5338 		struct task_struct *p, *n;
5339 
5340 		raw_spin_rq_lock(rq);
5341 		raw_spin_lock(&scx_sched_lock);
5342 
5343 		scx_for_each_descendant_pre(pos, sch) {
5344 			struct scx_sched_pcpu *pcpu = per_cpu_ptr(pos->pcpu, cpu);
5345 
5346 			if (pos->bypass_depth)
5347 				pcpu->flags |= SCX_SCHED_PCPU_BYPASSING;
5348 			else
5349 				pcpu->flags &= ~SCX_SCHED_PCPU_BYPASSING;
5350 		}
5351 
5352 		raw_spin_unlock(&scx_sched_lock);
5353 
5354 		/*
5355 		 * We need to guarantee that no tasks are on the BPF scheduler
5356 		 * while bypassing. Either we see enabled or the enable path
5357 		 * sees scx_bypassing() before moving tasks to SCX.
5358 		 */
5359 		if (!scx_enabled()) {
5360 			raw_spin_rq_unlock(rq);
5361 			continue;
5362 		}
5363 
5364 		/*
5365 		 * The use of list_for_each_entry_safe_reverse() is required
5366 		 * because each task is going to be removed from and added back
5367 		 * to the runnable_list during iteration. Because they're added
5368 		 * to the tail of the list, safe reverse iteration can still
5369 		 * visit all nodes.
5370 		 */
5371 		list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list,
5372 						 scx.runnable_node) {
5373 			if (!scx_is_descendant(scx_task_sched(p), sch))
5374 				continue;
5375 
5376 			/* cycling deq/enq is enough, see the function comment */
5377 			scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
5378 				/* nothing */ ;
5379 			}
5380 		}
5381 
5382 		/* resched to restore ticks and idle state */
5383 		if (cpu_online(cpu) || cpu == smp_processor_id())
5384 			resched_curr(rq);
5385 
5386 		raw_spin_rq_unlock(rq);
5387 	}
5388 
5389 	/* disarming must come after moving all tasks out of the bypass DSQs */
5390 	if (!bypass)
5391 		disable_bypass_dsp(sch);
5392 unlock:
5393 	raw_spin_unlock_irqrestore(&scx_bypass_lock, flags);
5394 }
5395 
5396 static void free_exit_info(struct scx_exit_info *ei)
5397 {
5398 	kvfree(ei->dump);
5399 	kfree(ei->msg);
5400 	kfree(ei->bt);
5401 	kfree(ei);
5402 }
5403 
5404 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
5405 {
5406 	struct scx_exit_info *ei;
5407 
5408 	ei = kzalloc_obj(*ei);
5409 	if (!ei)
5410 		return NULL;
5411 
5412 	ei->bt = kzalloc_objs(ei->bt[0], SCX_EXIT_BT_LEN);
5413 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
5414 	ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL);
5415 
5416 	if (!ei->bt || !ei->msg || !ei->dump) {
5417 		free_exit_info(ei);
5418 		return NULL;
5419 	}
5420 
5421 	return ei;
5422 }
5423 
5424 static const char *scx_exit_reason(enum scx_exit_kind kind)
5425 {
5426 	switch (kind) {
5427 	case SCX_EXIT_UNREG:
5428 		return "unregistered from user space";
5429 	case SCX_EXIT_UNREG_BPF:
5430 		return "unregistered from BPF";
5431 	case SCX_EXIT_UNREG_KERN:
5432 		return "unregistered from the main kernel";
5433 	case SCX_EXIT_SYSRQ:
5434 		return "disabled by sysrq-S";
5435 	case SCX_EXIT_PARENT:
5436 		return "parent exiting";
5437 	case SCX_EXIT_ERROR:
5438 		return "runtime error";
5439 	case SCX_EXIT_ERROR_BPF:
5440 		return "scx_bpf_error";
5441 	case SCX_EXIT_ERROR_STALL:
5442 		return "runnable task stall";
5443 	default:
5444 		return "<UNKNOWN>";
5445 	}
5446 }
5447 
5448 static void free_kick_syncs(void)
5449 {
5450 	int cpu;
5451 
5452 	for_each_possible_cpu(cpu) {
5453 		struct scx_kick_syncs **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
5454 		struct scx_kick_syncs *to_free;
5455 
5456 		to_free = rcu_replace_pointer(*ksyncs, NULL, true);
5457 		if (to_free)
5458 			kvfree_rcu(to_free, rcu);
5459 	}
5460 }
5461 
5462 static void refresh_watchdog(void)
5463 {
5464 	struct scx_sched *sch;
5465 	unsigned long intv = ULONG_MAX;
5466 
5467 	/* take the shortest timeout and use its half for watchdog interval */
5468 	rcu_read_lock();
5469 	list_for_each_entry_rcu(sch, &scx_sched_all, all)
5470 		intv = max(min(intv, sch->watchdog_timeout / 2), 1);
5471 	rcu_read_unlock();
5472 
5473 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
5474 	WRITE_ONCE(scx_watchdog_interval, intv);
5475 
5476 	if (intv < ULONG_MAX)
5477 		mod_delayed_work(system_dfl_wq, &scx_watchdog_work, intv);
5478 	else
5479 		cancel_delayed_work_sync(&scx_watchdog_work);
5480 }
5481 
5482 static s32 scx_link_sched(struct scx_sched *sch)
5483 {
5484 	scoped_guard(raw_spinlock_irq, &scx_sched_lock) {
5485 #ifdef CONFIG_EXT_SUB_SCHED
5486 		struct scx_sched *parent = scx_parent(sch);
5487 		s32 ret;
5488 
5489 		if (parent) {
5490 			/*
5491 			 * scx_claim_exit() propagates exit_kind transition to
5492 			 * its sub-scheds while holding scx_sched_lock - either
5493 			 * we can see the parent's non-NONE exit_kind or the
5494 			 * parent can shoot us down.
5495 			 */
5496 			if (atomic_read(&parent->exit_kind) != SCX_EXIT_NONE) {
5497 				scx_error(sch, "parent disabled");
5498 				return -ENOENT;
5499 			}
5500 
5501 			ret = rhashtable_lookup_insert_fast(&scx_sched_hash,
5502 					&sch->hash_node, scx_sched_hash_params);
5503 			if (ret) {
5504 				scx_error(sch, "failed to insert into scx_sched_hash (%d)", ret);
5505 				return ret;
5506 			}
5507 
5508 			list_add_tail(&sch->sibling, &parent->children);
5509 		}
5510 #endif	/* CONFIG_EXT_SUB_SCHED */
5511 
5512 		list_add_tail_rcu(&sch->all, &scx_sched_all);
5513 	}
5514 
5515 	refresh_watchdog();
5516 	return 0;
5517 }
5518 
5519 static void scx_unlink_sched(struct scx_sched *sch)
5520 {
5521 	scoped_guard(raw_spinlock_irq, &scx_sched_lock) {
5522 #ifdef CONFIG_EXT_SUB_SCHED
5523 		if (scx_parent(sch)) {
5524 			rhashtable_remove_fast(&scx_sched_hash, &sch->hash_node,
5525 					       scx_sched_hash_params);
5526 			list_del_init(&sch->sibling);
5527 		}
5528 #endif	/* CONFIG_EXT_SUB_SCHED */
5529 		list_del_rcu(&sch->all);
5530 	}
5531 
5532 	refresh_watchdog();
5533 }
5534 
5535 /*
5536  * Called to disable future dumps and wait for in-progress one while disabling
5537  * @sch. Once @sch becomes empty during disable, there's no point in dumping it.
5538  * This prevents calling dump ops on a dead sch.
5539  */
5540 static void scx_disable_dump(struct scx_sched *sch)
5541 {
5542 	guard(raw_spinlock_irqsave)(&scx_dump_lock);
5543 	sch->dump_disabled = true;
5544 }
5545 
5546 #ifdef CONFIG_EXT_SUB_SCHED
5547 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq);
5548 
5549 static void drain_descendants(struct scx_sched *sch)
5550 {
5551 	/*
5552 	 * Child scheds that finished the critical part of disabling will take
5553 	 * themselves off @sch->children. Wait for it to drain. As propagation
5554 	 * is recursive, empty @sch->children means that all proper descendant
5555 	 * scheds reached unlinking stage.
5556 	 */
5557 	wait_event(scx_unlink_waitq, list_empty(&sch->children));
5558 }
5559 
5560 static void scx_fail_parent(struct scx_sched *sch,
5561 			    struct task_struct *failed, s32 fail_code)
5562 {
5563 	struct scx_sched *parent = scx_parent(sch);
5564 	struct scx_task_iter sti;
5565 	struct task_struct *p;
5566 
5567 	scx_error(parent, "ops.init_task() failed (%d) for %s[%d] while disabling a sub-scheduler",
5568 		  fail_code, failed->comm, failed->pid);
5569 
5570 	/*
5571 	 * Once $parent is bypassed, it's safe to put SCX_TASK_NONE tasks into
5572 	 * it. This may cause downstream failures on the BPF side but $parent is
5573 	 * dying anyway.
5574 	 */
5575 	scx_bypass(parent, true);
5576 
5577 	scx_task_iter_start(&sti, sch->cgrp);
5578 	while ((p = scx_task_iter_next_locked(&sti))) {
5579 		if (scx_task_on_sched(parent, p))
5580 			continue;
5581 
5582 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
5583 			scx_disable_and_exit_task(sch, p);
5584 			rcu_assign_pointer(p->scx.sched, parent);
5585 		}
5586 	}
5587 	scx_task_iter_stop(&sti);
5588 }
5589 
5590 static void scx_sub_disable(struct scx_sched *sch)
5591 {
5592 	struct scx_sched *parent = scx_parent(sch);
5593 	struct scx_task_iter sti;
5594 	struct task_struct *p;
5595 	int ret;
5596 
5597 	/*
5598 	 * Guarantee forward progress and wait for descendants to be disabled.
5599 	 * To limit disruptions, $parent is not bypassed. Tasks are fully
5600 	 * prepped and then inserted back into $parent.
5601 	 */
5602 	scx_bypass(sch, true);
5603 	drain_descendants(sch);
5604 
5605 	/*
5606 	 * Here, every runnable task is guaranteed to make forward progress and
5607 	 * we can safely use blocking synchronization constructs. Actually
5608 	 * disable ops.
5609 	 */
5610 	mutex_lock(&scx_enable_mutex);
5611 	percpu_down_write(&scx_fork_rwsem);
5612 	scx_cgroup_lock();
5613 
5614 	set_cgroup_sched(sch_cgroup(sch), parent);
5615 
5616 	scx_task_iter_start(&sti, sch->cgrp);
5617 	while ((p = scx_task_iter_next_locked(&sti))) {
5618 		struct rq *rq;
5619 		struct rq_flags rf;
5620 
5621 		/* filter out duplicate visits */
5622 		if (scx_task_on_sched(parent, p))
5623 			continue;
5624 
5625 		/*
5626 		 * By the time control reaches here, all descendant schedulers
5627 		 * should already have been disabled.
5628 		 */
5629 		WARN_ON_ONCE(!scx_task_on_sched(sch, p));
5630 
5631 		/*
5632 		 * If $p is about to be freed, nothing prevents $sch from
5633 		 * unloading before $p reaches sched_ext_free(). Disable and
5634 		 * exit $p right away.
5635 		 */
5636 		if (!tryget_task_struct(p)) {
5637 			scx_disable_and_exit_task(sch, p);
5638 			continue;
5639 		}
5640 
5641 		scx_task_iter_unlock(&sti);
5642 
5643 		/*
5644 		 * $p is READY or ENABLED on @sch. Initialize for $parent,
5645 		 * disable and exit from @sch, and then switch over to $parent.
5646 		 *
5647 		 * If a task fails to initialize for $parent, the only available
5648 		 * action is disabling $parent too. While this allows disabling
5649 		 * of a child sched to cause the parent scheduler to fail, the
5650 		 * failure can only originate from ops.init_task() of the
5651 		 * parent. A child can't directly affect the parent through its
5652 		 * own failures.
5653 		 */
5654 		ret = __scx_init_task(parent, p, false);
5655 		if (ret) {
5656 			scx_fail_parent(sch, p, ret);
5657 			put_task_struct(p);
5658 			break;
5659 		}
5660 
5661 		rq = task_rq_lock(p, &rf);
5662 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
5663 			/*
5664 			 * $p is initialized for $parent and still attached to
5665 			 * @sch. Disable and exit for @sch, switch over to
5666 			 * $parent, override the state to READY to account for
5667 			 * $p having already been initialized, and then enable.
5668 			 */
5669 			scx_disable_and_exit_task(sch, p);
5670 			scx_set_task_state(p, SCX_TASK_INIT);
5671 			rcu_assign_pointer(p->scx.sched, parent);
5672 			scx_set_task_state(p, SCX_TASK_READY);
5673 			scx_enable_task(parent, p);
5674 		}
5675 		task_rq_unlock(rq, p, &rf);
5676 
5677 		put_task_struct(p);
5678 	}
5679 	scx_task_iter_stop(&sti);
5680 
5681 	scx_disable_dump(sch);
5682 
5683 	scx_cgroup_unlock();
5684 	percpu_up_write(&scx_fork_rwsem);
5685 
5686 	/*
5687 	 * All tasks are moved off of @sch but there may still be on-going
5688 	 * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use
5689 	 * the expedited version as ancestors may be waiting in bypass mode.
5690 	 * Also, tell the parent that there is no need to keep running bypass
5691 	 * DSQs for us.
5692 	 */
5693 	synchronize_rcu_expedited();
5694 	disable_bypass_dsp(sch);
5695 
5696 	scx_unlink_sched(sch);
5697 
5698 	mutex_unlock(&scx_enable_mutex);
5699 
5700 	/*
5701 	 * @sch is now unlinked from the parent's children list. Notify and call
5702 	 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called
5703 	 * after unlinking and releasing all locks. See scx_claim_exit().
5704 	 */
5705 	wake_up_all(&scx_unlink_waitq);
5706 
5707 	if (parent->ops.sub_detach && sch->sub_attached) {
5708 		struct scx_sub_detach_args sub_detach_args = {
5709 			.ops = &sch->ops,
5710 			.cgroup_path = sch->cgrp_path,
5711 		};
5712 		SCX_CALL_OP(parent, SCX_KF_UNLOCKED, sub_detach, NULL,
5713 			    &sub_detach_args);
5714 	}
5715 
5716 	if (sch->ops.exit)
5717 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, exit, NULL, sch->exit_info);
5718 	kobject_del(&sch->kobj);
5719 }
5720 #else	/* CONFIG_EXT_SUB_SCHED */
5721 static void drain_descendants(struct scx_sched *sch) { }
5722 static void scx_sub_disable(struct scx_sched *sch) { }
5723 #endif	/* CONFIG_EXT_SUB_SCHED */
5724 
5725 static void scx_root_disable(struct scx_sched *sch)
5726 {
5727 	struct scx_exit_info *ei = sch->exit_info;
5728 	struct scx_task_iter sti;
5729 	struct task_struct *p;
5730 	int cpu;
5731 
5732 	/* guarantee forward progress and wait for descendants to be disabled */
5733 	scx_bypass(sch, true);
5734 	drain_descendants(sch);
5735 
5736 	switch (scx_set_enable_state(SCX_DISABLING)) {
5737 	case SCX_DISABLING:
5738 		WARN_ONCE(true, "sched_ext: duplicate disabling instance?");
5739 		break;
5740 	case SCX_DISABLED:
5741 		pr_warn("sched_ext: ops error detected without ops (%s)\n",
5742 			sch->exit_info->msg);
5743 		WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
5744 		goto done;
5745 	default:
5746 		break;
5747 	}
5748 
5749 	/*
5750 	 * Here, every runnable task is guaranteed to make forward progress and
5751 	 * we can safely use blocking synchronization constructs. Actually
5752 	 * disable ops.
5753 	 */
5754 	mutex_lock(&scx_enable_mutex);
5755 
5756 	static_branch_disable(&__scx_switched_all);
5757 	WRITE_ONCE(scx_switching_all, false);
5758 
5759 	/*
5760 	 * Shut down cgroup support before tasks so that the cgroup attach path
5761 	 * doesn't race against scx_disable_and_exit_task().
5762 	 */
5763 	scx_cgroup_lock();
5764 	scx_cgroup_exit(sch);
5765 	scx_cgroup_unlock();
5766 
5767 	/*
5768 	 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones
5769 	 * must be switched out and exited synchronously.
5770 	 */
5771 	percpu_down_write(&scx_fork_rwsem);
5772 
5773 	scx_init_task_enabled = false;
5774 
5775 	scx_task_iter_start(&sti, NULL);
5776 	while ((p = scx_task_iter_next_locked(&sti))) {
5777 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
5778 		const struct sched_class *old_class = p->sched_class;
5779 		const struct sched_class *new_class = scx_setscheduler_class(p);
5780 
5781 		update_rq_clock(task_rq(p));
5782 
5783 		if (old_class != new_class)
5784 			queue_flags |= DEQUEUE_CLASS;
5785 
5786 		scoped_guard (sched_change, p, queue_flags) {
5787 			p->sched_class = new_class;
5788 		}
5789 
5790 		scx_disable_and_exit_task(scx_task_sched(p), p);
5791 	}
5792 	scx_task_iter_stop(&sti);
5793 
5794 	scx_disable_dump(sch);
5795 
5796 	scx_cgroup_lock();
5797 	set_cgroup_sched(sch_cgroup(sch), NULL);
5798 	scx_cgroup_unlock();
5799 
5800 	percpu_up_write(&scx_fork_rwsem);
5801 
5802 	/*
5803 	 * Invalidate all the rq clocks to prevent getting outdated
5804 	 * rq clocks from a previous scx scheduler.
5805 	 */
5806 	for_each_possible_cpu(cpu) {
5807 		struct rq *rq = cpu_rq(cpu);
5808 		scx_rq_clock_invalidate(rq);
5809 	}
5810 
5811 	/* no task is on scx, turn off all the switches and flush in-progress calls */
5812 	static_branch_disable(&__scx_enabled);
5813 	bitmap_zero(sch->has_op, SCX_OPI_END);
5814 	scx_idle_disable();
5815 	synchronize_rcu();
5816 
5817 	if (ei->kind >= SCX_EXIT_ERROR) {
5818 		pr_err("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
5819 		       sch->ops.name, ei->reason);
5820 
5821 		if (ei->msg[0] != '\0')
5822 			pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg);
5823 #ifdef CONFIG_STACKTRACE
5824 		stack_trace_print(ei->bt, ei->bt_len, 2);
5825 #endif
5826 	} else {
5827 		pr_info("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
5828 			sch->ops.name, ei->reason);
5829 	}
5830 
5831 	if (sch->ops.exit)
5832 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, exit, NULL, ei);
5833 
5834 	scx_unlink_sched(sch);
5835 
5836 	/*
5837 	 * scx_root clearing must be inside cpus_read_lock(). See
5838 	 * handle_hotplug().
5839 	 */
5840 	cpus_read_lock();
5841 	RCU_INIT_POINTER(scx_root, NULL);
5842 	cpus_read_unlock();
5843 
5844 	/*
5845 	 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs
5846 	 * could observe an object of the same name still in the hierarchy when
5847 	 * the next scheduler is loaded.
5848 	 */
5849 	kobject_del(&sch->kobj);
5850 
5851 	free_kick_syncs();
5852 
5853 	mutex_unlock(&scx_enable_mutex);
5854 
5855 	WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
5856 done:
5857 	scx_bypass(sch, false);
5858 }
5859 
5860 /*
5861  * Claim the exit on @sch. The caller must ensure that the helper kthread work
5862  * is kicked before the current task can be preempted. Once exit_kind is
5863  * claimed, scx_error() can no longer trigger, so if the current task gets
5864  * preempted and the BPF scheduler fails to schedule it back, the helper work
5865  * will never be kicked and the whole system can wedge.
5866  */
5867 static bool scx_claim_exit(struct scx_sched *sch, enum scx_exit_kind kind)
5868 {
5869 	int none = SCX_EXIT_NONE;
5870 
5871 	lockdep_assert_preemption_disabled();
5872 
5873 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
5874 		kind = SCX_EXIT_ERROR;
5875 
5876 	if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind))
5877 		return false;
5878 
5879 	/*
5880 	 * Some CPUs may be trapped in the dispatch paths. Set the aborting
5881 	 * flag to break potential live-lock scenarios, ensuring we can
5882 	 * successfully reach scx_bypass().
5883 	 */
5884 	WRITE_ONCE(sch->aborting, true);
5885 
5886 	/*
5887 	 * Propagate exits to descendants immediately. Each has a dedicated
5888 	 * helper kthread and can run in parallel. While most of disabling is
5889 	 * serialized, running them in separate threads allows parallelizing
5890 	 * ops.exit(), which can take arbitrarily long prolonging bypass mode.
5891 	 *
5892 	 * To guarantee forward progress, this propagation must be in-line so
5893 	 * that ->aborting is synchronously asserted for all sub-scheds. The
5894 	 * propagation is also the interlocking point against sub-sched
5895 	 * attachment. See scx_link_sched().
5896 	 *
5897 	 * This doesn't cause recursions as propagation only takes place for
5898 	 * non-propagation exits.
5899 	 */
5900 	if (kind != SCX_EXIT_PARENT) {
5901 		scoped_guard (raw_spinlock_irqsave, &scx_sched_lock) {
5902 			struct scx_sched *pos;
5903 			scx_for_each_descendant_pre(pos, sch)
5904 				scx_disable(pos, SCX_EXIT_PARENT);
5905 		}
5906 	}
5907 
5908 	return true;
5909 }
5910 
5911 static void scx_disable_workfn(struct kthread_work *work)
5912 {
5913 	struct scx_sched *sch = container_of(work, struct scx_sched, disable_work);
5914 	struct scx_exit_info *ei = sch->exit_info;
5915 	int kind;
5916 
5917 	kind = atomic_read(&sch->exit_kind);
5918 	while (true) {
5919 		if (kind == SCX_EXIT_DONE)	/* already disabled? */
5920 			return;
5921 		WARN_ON_ONCE(kind == SCX_EXIT_NONE);
5922 		if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE))
5923 			break;
5924 	}
5925 	ei->kind = kind;
5926 	ei->reason = scx_exit_reason(ei->kind);
5927 
5928 	if (scx_parent(sch))
5929 		scx_sub_disable(sch);
5930 	else
5931 		scx_root_disable(sch);
5932 }
5933 
5934 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind)
5935 {
5936 	guard(preempt)();
5937 	if (scx_claim_exit(sch, kind))
5938 		irq_work_queue(&sch->disable_irq_work);
5939 }
5940 
5941 static void dump_newline(struct seq_buf *s)
5942 {
5943 	trace_sched_ext_dump("");
5944 
5945 	/* @s may be zero sized and seq_buf triggers WARN if so */
5946 	if (s->size)
5947 		seq_buf_putc(s, '\n');
5948 }
5949 
5950 static __printf(2, 3) void dump_line(struct seq_buf *s, const char *fmt, ...)
5951 {
5952 	va_list args;
5953 
5954 #ifdef CONFIG_TRACEPOINTS
5955 	if (trace_sched_ext_dump_enabled()) {
5956 		/* protected by scx_dump_lock */
5957 		static char line_buf[SCX_EXIT_MSG_LEN];
5958 
5959 		va_start(args, fmt);
5960 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
5961 		va_end(args);
5962 
5963 		trace_sched_ext_dump(line_buf);
5964 	}
5965 #endif
5966 	/* @s may be zero sized and seq_buf triggers WARN if so */
5967 	if (s->size) {
5968 		va_start(args, fmt);
5969 		seq_buf_vprintf(s, fmt, args);
5970 		va_end(args);
5971 
5972 		seq_buf_putc(s, '\n');
5973 	}
5974 }
5975 
5976 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
5977 			     const unsigned long *bt, unsigned int len)
5978 {
5979 	unsigned int i;
5980 
5981 	for (i = 0; i < len; i++)
5982 		dump_line(s, "%s%pS", prefix, (void *)bt[i]);
5983 }
5984 
5985 static void ops_dump_init(struct seq_buf *s, const char *prefix)
5986 {
5987 	struct scx_dump_data *dd = &scx_dump_data;
5988 
5989 	lockdep_assert_irqs_disabled();
5990 
5991 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
5992 	dd->first = true;
5993 	dd->cursor = 0;
5994 	dd->s = s;
5995 	dd->prefix = prefix;
5996 }
5997 
5998 static void ops_dump_flush(void)
5999 {
6000 	struct scx_dump_data *dd = &scx_dump_data;
6001 	char *line = dd->buf.line;
6002 
6003 	if (!dd->cursor)
6004 		return;
6005 
6006 	/*
6007 	 * There's something to flush and this is the first line. Insert a blank
6008 	 * line to distinguish ops dump.
6009 	 */
6010 	if (dd->first) {
6011 		dump_newline(dd->s);
6012 		dd->first = false;
6013 	}
6014 
6015 	/*
6016 	 * There may be multiple lines in $line. Scan and emit each line
6017 	 * separately.
6018 	 */
6019 	while (true) {
6020 		char *end = line;
6021 		char c;
6022 
6023 		while (*end != '\n' && *end != '\0')
6024 			end++;
6025 
6026 		/*
6027 		 * If $line overflowed, it may not have newline at the end.
6028 		 * Always emit with a newline.
6029 		 */
6030 		c = *end;
6031 		*end = '\0';
6032 		dump_line(dd->s, "%s%s", dd->prefix, line);
6033 		if (c == '\0')
6034 			break;
6035 
6036 		/* move to the next line */
6037 		end++;
6038 		if (*end == '\0')
6039 			break;
6040 		line = end;
6041 	}
6042 
6043 	dd->cursor = 0;
6044 }
6045 
6046 static void ops_dump_exit(void)
6047 {
6048 	ops_dump_flush();
6049 	scx_dump_data.cpu = -1;
6050 }
6051 
6052 static void scx_dump_task(struct scx_sched *sch,
6053 			  struct seq_buf *s, struct scx_dump_ctx *dctx,
6054 			  struct task_struct *p, char marker)
6055 {
6056 	static unsigned long bt[SCX_EXIT_BT_LEN];
6057 	struct scx_sched *task_sch = scx_task_sched(p);
6058 	const char *own_marker;
6059 	char sch_id_buf[32];
6060 	char dsq_id_buf[19] = "(n/a)";
6061 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
6062 	unsigned int bt_len = 0;
6063 
6064 	own_marker = task_sch == sch ? "*" : "";
6065 
6066 	if (task_sch->level == 0)
6067 		scnprintf(sch_id_buf, sizeof(sch_id_buf), "root");
6068 	else
6069 		scnprintf(sch_id_buf, sizeof(sch_id_buf), "sub%d-%llu",
6070 			  task_sch->level, task_sch->ops.sub_cgroup_id);
6071 
6072 	if (p->scx.dsq)
6073 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
6074 			  (unsigned long long)p->scx.dsq->id);
6075 
6076 	dump_newline(s);
6077 	dump_line(s, " %c%c %s[%d] %s%s %+ldms",
6078 		  marker, task_state_to_char(p), p->comm, p->pid,
6079 		  own_marker, sch_id_buf,
6080 		  jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
6081 	dump_line(s, "      scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu",
6082 		  scx_get_task_state(p) >> SCX_TASK_STATE_SHIFT,
6083 		  p->scx.flags & ~SCX_TASK_STATE_MASK,
6084 		  p->scx.dsq_flags, ops_state & SCX_OPSS_STATE_MASK,
6085 		  ops_state >> SCX_OPSS_QSEQ_SHIFT);
6086 	dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
6087 		  p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
6088 	dump_line(s, "      dsq_vtime=%llu slice=%llu weight=%u",
6089 		  p->scx.dsq_vtime, p->scx.slice, p->scx.weight);
6090 	dump_line(s, "      cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr),
6091 		  p->migration_disabled);
6092 
6093 	if (SCX_HAS_OP(sch, dump_task)) {
6094 		ops_dump_init(s, "    ");
6095 		SCX_CALL_OP(sch, SCX_KF_REST, dump_task, NULL, dctx, p);
6096 		ops_dump_exit();
6097 	}
6098 
6099 #ifdef CONFIG_STACKTRACE
6100 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
6101 #endif
6102 	if (bt_len) {
6103 		dump_newline(s);
6104 		dump_stack_trace(s, "    ", bt, bt_len);
6105 	}
6106 }
6107 
6108 /*
6109  * Dump scheduler state. If @dump_all_tasks is true, dump all tasks regardless
6110  * of which scheduler they belong to. If false, only dump tasks owned by @sch.
6111  * For SysRq-D dumps, @dump_all_tasks=false since all schedulers are dumped
6112  * separately. For error dumps, @dump_all_tasks=true since only the failing
6113  * scheduler is dumped.
6114  */
6115 static void scx_dump_state(struct scx_sched *sch, struct scx_exit_info *ei,
6116 			   size_t dump_len, bool dump_all_tasks)
6117 {
6118 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
6119 	struct scx_dump_ctx dctx = {
6120 		.kind = ei->kind,
6121 		.exit_code = ei->exit_code,
6122 		.reason = ei->reason,
6123 		.at_ns = ktime_get_ns(),
6124 		.at_jiffies = jiffies,
6125 	};
6126 	struct seq_buf s;
6127 	struct scx_event_stats events;
6128 	char *buf;
6129 	int cpu;
6130 
6131 	guard(raw_spinlock_irqsave)(&scx_dump_lock);
6132 
6133 	if (sch->dump_disabled)
6134 		return;
6135 
6136 	seq_buf_init(&s, ei->dump, dump_len);
6137 
6138 #ifdef CONFIG_EXT_SUB_SCHED
6139 	if (sch->level == 0)
6140 		dump_line(&s, "%s: root", sch->ops.name);
6141 	else
6142 		dump_line(&s, "%s: sub%d-%llu %s",
6143 			  sch->ops.name, sch->level, sch->ops.sub_cgroup_id,
6144 			  sch->cgrp_path);
6145 #endif
6146 	if (ei->kind == SCX_EXIT_NONE) {
6147 		dump_line(&s, "Debug dump triggered by %s", ei->reason);
6148 	} else {
6149 		dump_line(&s, "%s[%d] triggered exit kind %d:",
6150 			  current->comm, current->pid, ei->kind);
6151 		dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
6152 		dump_newline(&s);
6153 		dump_line(&s, "Backtrace:");
6154 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
6155 	}
6156 
6157 	if (SCX_HAS_OP(sch, dump)) {
6158 		ops_dump_init(&s, "");
6159 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, dump, NULL, &dctx);
6160 		ops_dump_exit();
6161 	}
6162 
6163 	dump_newline(&s);
6164 	dump_line(&s, "CPU states");
6165 	dump_line(&s, "----------");
6166 
6167 	for_each_possible_cpu(cpu) {
6168 		struct rq *rq = cpu_rq(cpu);
6169 		struct rq_flags rf;
6170 		struct task_struct *p;
6171 		struct seq_buf ns;
6172 		size_t avail, used;
6173 		bool idle;
6174 
6175 		rq_lock_irqsave(rq, &rf);
6176 
6177 		idle = list_empty(&rq->scx.runnable_list) &&
6178 			rq->curr->sched_class == &idle_sched_class;
6179 
6180 		if (idle && !SCX_HAS_OP(sch, dump_cpu))
6181 			goto next;
6182 
6183 		/*
6184 		 * We don't yet know whether ops.dump_cpu() will produce output
6185 		 * and we may want to skip the default CPU dump if it doesn't.
6186 		 * Use a nested seq_buf to generate the standard dump so that we
6187 		 * can decide whether to commit later.
6188 		 */
6189 		avail = seq_buf_get_buf(&s, &buf);
6190 		seq_buf_init(&ns, buf, avail);
6191 
6192 		dump_newline(&ns);
6193 		dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu ksync=%lu",
6194 			  cpu, rq->scx.nr_running, rq->scx.flags,
6195 			  rq->scx.cpu_released, rq->scx.ops_qseq,
6196 			  rq->scx.kick_sync);
6197 		dump_line(&ns, "          curr=%s[%d] class=%ps",
6198 			  rq->curr->comm, rq->curr->pid,
6199 			  rq->curr->sched_class);
6200 		if (!cpumask_empty(rq->scx.cpus_to_kick))
6201 			dump_line(&ns, "  cpus_to_kick   : %*pb",
6202 				  cpumask_pr_args(rq->scx.cpus_to_kick));
6203 		if (!cpumask_empty(rq->scx.cpus_to_kick_if_idle))
6204 			dump_line(&ns, "  idle_to_kick   : %*pb",
6205 				  cpumask_pr_args(rq->scx.cpus_to_kick_if_idle));
6206 		if (!cpumask_empty(rq->scx.cpus_to_preempt))
6207 			dump_line(&ns, "  cpus_to_preempt: %*pb",
6208 				  cpumask_pr_args(rq->scx.cpus_to_preempt));
6209 		if (!cpumask_empty(rq->scx.cpus_to_wait))
6210 			dump_line(&ns, "  cpus_to_wait   : %*pb",
6211 				  cpumask_pr_args(rq->scx.cpus_to_wait));
6212 
6213 		used = seq_buf_used(&ns);
6214 		if (SCX_HAS_OP(sch, dump_cpu)) {
6215 			ops_dump_init(&ns, "  ");
6216 			SCX_CALL_OP(sch, SCX_KF_REST, dump_cpu, NULL,
6217 				    &dctx, cpu, idle);
6218 			ops_dump_exit();
6219 		}
6220 
6221 		/*
6222 		 * If idle && nothing generated by ops.dump_cpu(), there's
6223 		 * nothing interesting. Skip.
6224 		 */
6225 		if (idle && used == seq_buf_used(&ns))
6226 			goto next;
6227 
6228 		/*
6229 		 * $s may already have overflowed when $ns was created. If so,
6230 		 * calling commit on it will trigger BUG.
6231 		 */
6232 		if (avail) {
6233 			seq_buf_commit(&s, seq_buf_used(&ns));
6234 			if (seq_buf_has_overflowed(&ns))
6235 				seq_buf_set_overflow(&s);
6236 		}
6237 
6238 		if (rq->curr->sched_class == &ext_sched_class &&
6239 		    (dump_all_tasks || scx_task_on_sched(sch, rq->curr)))
6240 			scx_dump_task(sch, &s, &dctx, rq->curr, '*');
6241 
6242 		list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
6243 			if (dump_all_tasks || scx_task_on_sched(sch, p))
6244 				scx_dump_task(sch, &s, &dctx, p, ' ');
6245 	next:
6246 		rq_unlock_irqrestore(rq, &rf);
6247 	}
6248 
6249 	dump_newline(&s);
6250 	dump_line(&s, "Event counters");
6251 	dump_line(&s, "--------------");
6252 
6253 	scx_read_events(sch, &events);
6254 	scx_dump_event(s, &events, SCX_EV_SELECT_CPU_FALLBACK);
6255 	scx_dump_event(s, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
6256 	scx_dump_event(s, &events, SCX_EV_DISPATCH_KEEP_LAST);
6257 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_EXITING);
6258 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
6259 	scx_dump_event(s, &events, SCX_EV_REENQ_IMMED);
6260 	scx_dump_event(s, &events, SCX_EV_REENQ_LOCAL_REPEAT);
6261 	scx_dump_event(s, &events, SCX_EV_REFILL_SLICE_DFL);
6262 	scx_dump_event(s, &events, SCX_EV_BYPASS_DURATION);
6263 	scx_dump_event(s, &events, SCX_EV_BYPASS_DISPATCH);
6264 	scx_dump_event(s, &events, SCX_EV_BYPASS_ACTIVATE);
6265 	scx_dump_event(s, &events, SCX_EV_INSERT_NOT_OWNED);
6266 	scx_dump_event(s, &events, SCX_EV_SUB_BYPASS_DISPATCH);
6267 
6268 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
6269 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
6270 		       trunc_marker, sizeof(trunc_marker));
6271 }
6272 
6273 static void scx_disable_irq_workfn(struct irq_work *irq_work)
6274 {
6275 	struct scx_sched *sch = container_of(irq_work, struct scx_sched, disable_irq_work);
6276 	struct scx_exit_info *ei = sch->exit_info;
6277 
6278 	if (ei->kind >= SCX_EXIT_ERROR)
6279 		scx_dump_state(sch, ei, sch->ops.exit_dump_len, true);
6280 
6281 	kthread_queue_work(sch->helper, &sch->disable_work);
6282 }
6283 
6284 static bool scx_vexit(struct scx_sched *sch,
6285 		      enum scx_exit_kind kind, s64 exit_code,
6286 		      const char *fmt, va_list args)
6287 {
6288 	struct scx_exit_info *ei = sch->exit_info;
6289 
6290 	guard(preempt)();
6291 
6292 	if (!scx_claim_exit(sch, kind))
6293 		return false;
6294 
6295 	ei->exit_code = exit_code;
6296 #ifdef CONFIG_STACKTRACE
6297 	if (kind >= SCX_EXIT_ERROR)
6298 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
6299 #endif
6300 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
6301 
6302 	/*
6303 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
6304 	 * in scx_disable_workfn().
6305 	 */
6306 	ei->kind = kind;
6307 	ei->reason = scx_exit_reason(ei->kind);
6308 
6309 	irq_work_queue(&sch->disable_irq_work);
6310 	return true;
6311 }
6312 
6313 static int alloc_kick_syncs(void)
6314 {
6315 	int cpu;
6316 
6317 	/*
6318 	 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size
6319 	 * can exceed percpu allocator limits on large machines.
6320 	 */
6321 	for_each_possible_cpu(cpu) {
6322 		struct scx_kick_syncs **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
6323 		struct scx_kick_syncs *new_ksyncs;
6324 
6325 		WARN_ON_ONCE(rcu_access_pointer(*ksyncs));
6326 
6327 		new_ksyncs = kvzalloc_node(struct_size(new_ksyncs, syncs, nr_cpu_ids),
6328 					   GFP_KERNEL, cpu_to_node(cpu));
6329 		if (!new_ksyncs) {
6330 			free_kick_syncs();
6331 			return -ENOMEM;
6332 		}
6333 
6334 		rcu_assign_pointer(*ksyncs, new_ksyncs);
6335 	}
6336 
6337 	return 0;
6338 }
6339 
6340 static void free_pnode(struct scx_sched_pnode *pnode)
6341 {
6342 	if (!pnode)
6343 		return;
6344 	exit_dsq(&pnode->global_dsq);
6345 	kfree(pnode);
6346 }
6347 
6348 static struct scx_sched_pnode *alloc_pnode(struct scx_sched *sch, int node)
6349 {
6350 	struct scx_sched_pnode *pnode;
6351 
6352 	pnode = kzalloc_node(sizeof(*pnode), GFP_KERNEL, node);
6353 	if (!pnode)
6354 		return NULL;
6355 
6356 	if (init_dsq(&pnode->global_dsq, SCX_DSQ_GLOBAL, sch)) {
6357 		kfree(pnode);
6358 		return NULL;
6359 	}
6360 
6361 	return pnode;
6362 }
6363 
6364 /*
6365  * Allocate and initialize a new scx_sched. @cgrp's reference is always
6366  * consumed whether the function succeeds or fails.
6367  */
6368 static struct scx_sched *scx_alloc_and_add_sched(struct sched_ext_ops *ops,
6369 						 struct cgroup *cgrp,
6370 						 struct scx_sched *parent)
6371 {
6372 	struct scx_sched *sch;
6373 	s32 level = parent ? parent->level + 1 : 0;
6374 	s32 node, cpu, ret, bypass_fail_cpu = nr_cpu_ids;
6375 
6376 	sch = kzalloc_flex(*sch, ancestors, level + 1);
6377 	if (!sch) {
6378 		ret = -ENOMEM;
6379 		goto err_put_cgrp;
6380 	}
6381 
6382 	sch->exit_info = alloc_exit_info(ops->exit_dump_len);
6383 	if (!sch->exit_info) {
6384 		ret = -ENOMEM;
6385 		goto err_free_sch;
6386 	}
6387 
6388 	ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params);
6389 	if (ret < 0)
6390 		goto err_free_ei;
6391 
6392 	sch->pnode = kzalloc_objs(sch->pnode[0], nr_node_ids);
6393 	if (!sch->pnode) {
6394 		ret = -ENOMEM;
6395 		goto err_free_hash;
6396 	}
6397 
6398 	for_each_node_state(node, N_POSSIBLE) {
6399 		sch->pnode[node] = alloc_pnode(sch, node);
6400 		if (!sch->pnode[node]) {
6401 			ret = -ENOMEM;
6402 			goto err_free_pnode;
6403 		}
6404 	}
6405 
6406 	sch->dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
6407 	sch->pcpu = __alloc_percpu(struct_size_t(struct scx_sched_pcpu,
6408 						 dsp_ctx.buf, sch->dsp_max_batch),
6409 				   __alignof__(struct scx_sched_pcpu));
6410 	if (!sch->pcpu) {
6411 		ret = -ENOMEM;
6412 		goto err_free_pnode;
6413 	}
6414 
6415 	for_each_possible_cpu(cpu) {
6416 		ret = init_dsq(bypass_dsq(sch, cpu), SCX_DSQ_BYPASS, sch);
6417 		if (ret) {
6418 			bypass_fail_cpu = cpu;
6419 			goto err_free_pcpu;
6420 		}
6421 	}
6422 
6423 	for_each_possible_cpu(cpu) {
6424 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
6425 
6426 		pcpu->sch = sch;
6427 		INIT_LIST_HEAD(&pcpu->deferred_reenq_local.node);
6428 	}
6429 
6430 	sch->helper = kthread_run_worker(0, "sched_ext_helper");
6431 	if (IS_ERR(sch->helper)) {
6432 		ret = PTR_ERR(sch->helper);
6433 		goto err_free_pcpu;
6434 	}
6435 
6436 	sched_set_fifo(sch->helper->task);
6437 
6438 	if (parent)
6439 		memcpy(sch->ancestors, parent->ancestors,
6440 		       level * sizeof(parent->ancestors[0]));
6441 	sch->ancestors[level] = sch;
6442 	sch->level = level;
6443 
6444 	if (ops->timeout_ms)
6445 		sch->watchdog_timeout = msecs_to_jiffies(ops->timeout_ms);
6446 	else
6447 		sch->watchdog_timeout = SCX_WATCHDOG_MAX_TIMEOUT;
6448 
6449 	sch->slice_dfl = SCX_SLICE_DFL;
6450 	atomic_set(&sch->exit_kind, SCX_EXIT_NONE);
6451 	init_irq_work(&sch->disable_irq_work, scx_disable_irq_workfn);
6452 	kthread_init_work(&sch->disable_work, scx_disable_workfn);
6453 	timer_setup(&sch->bypass_lb_timer, scx_bypass_lb_timerfn, 0);
6454 	sch->ops = *ops;
6455 	rcu_assign_pointer(ops->priv, sch);
6456 
6457 	sch->kobj.kset = scx_kset;
6458 
6459 #ifdef CONFIG_EXT_SUB_SCHED
6460 	char *buf = kzalloc(PATH_MAX, GFP_KERNEL);
6461 	if (!buf) {
6462 		ret = -ENOMEM;
6463 		goto err_stop_helper;
6464 	}
6465 	cgroup_path(cgrp, buf, PATH_MAX);
6466 	sch->cgrp_path = kstrdup(buf, GFP_KERNEL);
6467 	kfree(buf);
6468 	if (!sch->cgrp_path) {
6469 		ret = -ENOMEM;
6470 		goto err_stop_helper;
6471 	}
6472 
6473 	sch->cgrp = cgrp;
6474 	INIT_LIST_HEAD(&sch->children);
6475 	INIT_LIST_HEAD(&sch->sibling);
6476 
6477 	if (parent)
6478 		ret = kobject_init_and_add(&sch->kobj, &scx_ktype,
6479 					   &parent->sub_kset->kobj,
6480 					   "sub-%llu", cgroup_id(cgrp));
6481 	else
6482 		ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root");
6483 
6484 	if (ret < 0) {
6485 		kobject_put(&sch->kobj);
6486 		return ERR_PTR(ret);
6487 	}
6488 
6489 	if (ops->sub_attach) {
6490 		sch->sub_kset = kset_create_and_add("sub", NULL, &sch->kobj);
6491 		if (!sch->sub_kset) {
6492 			kobject_put(&sch->kobj);
6493 			return ERR_PTR(-ENOMEM);
6494 		}
6495 	}
6496 #else	/* CONFIG_EXT_SUB_SCHED */
6497 	ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root");
6498 	if (ret < 0) {
6499 		kobject_put(&sch->kobj);
6500 		return ERR_PTR(ret);
6501 	}
6502 #endif	/* CONFIG_EXT_SUB_SCHED */
6503 	return sch;
6504 
6505 #ifdef CONFIG_EXT_SUB_SCHED
6506 err_stop_helper:
6507 	kthread_destroy_worker(sch->helper);
6508 #endif
6509 err_free_pcpu:
6510 	for_each_possible_cpu(cpu) {
6511 		if (cpu == bypass_fail_cpu)
6512 			break;
6513 		exit_dsq(bypass_dsq(sch, cpu));
6514 	}
6515 	free_percpu(sch->pcpu);
6516 err_free_pnode:
6517 	for_each_node_state(node, N_POSSIBLE)
6518 		free_pnode(sch->pnode[node]);
6519 	kfree(sch->pnode);
6520 err_free_hash:
6521 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
6522 err_free_ei:
6523 	free_exit_info(sch->exit_info);
6524 err_free_sch:
6525 	kfree(sch);
6526 err_put_cgrp:
6527 #if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED)
6528 	cgroup_put(cgrp);
6529 #endif
6530 	return ERR_PTR(ret);
6531 }
6532 
6533 static int check_hotplug_seq(struct scx_sched *sch,
6534 			      const struct sched_ext_ops *ops)
6535 {
6536 	unsigned long long global_hotplug_seq;
6537 
6538 	/*
6539 	 * If a hotplug event has occurred between when a scheduler was
6540 	 * initialized, and when we were able to attach, exit and notify user
6541 	 * space about it.
6542 	 */
6543 	if (ops->hotplug_seq) {
6544 		global_hotplug_seq = atomic_long_read(&scx_hotplug_seq);
6545 		if (ops->hotplug_seq != global_hotplug_seq) {
6546 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
6547 				 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
6548 				 "expected hotplug seq %llu did not match actual %llu",
6549 				 ops->hotplug_seq, global_hotplug_seq);
6550 			return -EBUSY;
6551 		}
6552 	}
6553 
6554 	return 0;
6555 }
6556 
6557 static int validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
6558 {
6559 	/*
6560 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
6561 	 * ops.enqueue() callback isn't implemented.
6562 	 */
6563 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
6564 		scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
6565 		return -EINVAL;
6566 	}
6567 
6568 	/*
6569 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle
6570 	 * selection policy to be enabled.
6571 	 */
6572 	if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) &&
6573 	    (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) {
6574 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled");
6575 		return -EINVAL;
6576 	}
6577 
6578 	if (ops->cpu_acquire || ops->cpu_release)
6579 		pr_warn("ops->cpu_acquire/release() are deprecated, use sched_switch TP instead\n");
6580 
6581 	return 0;
6582 }
6583 
6584 /*
6585  * scx_enable() is offloaded to a dedicated system-wide RT kthread to avoid
6586  * starvation. During the READY -> ENABLED task switching loop, the calling
6587  * thread's sched_class gets switched from fair to ext. As fair has higher
6588  * priority than ext, the calling thread can be indefinitely starved under
6589  * fair-class saturation, leading to a system hang.
6590  */
6591 struct scx_enable_cmd {
6592 	struct kthread_work	work;
6593 	struct sched_ext_ops	*ops;
6594 	int			ret;
6595 };
6596 
6597 static void scx_root_enable_workfn(struct kthread_work *work)
6598 {
6599 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
6600 	struct sched_ext_ops *ops = cmd->ops;
6601 	struct cgroup *cgrp = root_cgroup();
6602 	struct scx_sched *sch;
6603 	struct scx_task_iter sti;
6604 	struct task_struct *p;
6605 	int i, cpu, ret;
6606 
6607 	mutex_lock(&scx_enable_mutex);
6608 
6609 	if (scx_enable_state() != SCX_DISABLED) {
6610 		ret = -EBUSY;
6611 		goto err_unlock;
6612 	}
6613 
6614 	ret = alloc_kick_syncs();
6615 	if (ret)
6616 		goto err_unlock;
6617 
6618 #if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED)
6619 	cgroup_get(cgrp);
6620 #endif
6621 	sch = scx_alloc_and_add_sched(ops, cgrp, NULL);
6622 	if (IS_ERR(sch)) {
6623 		ret = PTR_ERR(sch);
6624 		goto err_free_ksyncs;
6625 	}
6626 
6627 	/*
6628 	 * Transition to ENABLING and clear exit info to arm the disable path.
6629 	 * Failure triggers full disabling from here on.
6630 	 */
6631 	WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED);
6632 	WARN_ON_ONCE(scx_root);
6633 
6634 	atomic_long_set(&scx_nr_rejected, 0);
6635 
6636 	for_each_possible_cpu(cpu) {
6637 		struct rq *rq = cpu_rq(cpu);
6638 
6639 		rq->scx.local_dsq.sched = sch;
6640 		rq->scx.cpuperf_target = SCX_CPUPERF_ONE;
6641 	}
6642 
6643 	/*
6644 	 * Keep CPUs stable during enable so that the BPF scheduler can track
6645 	 * online CPUs by watching ->on/offline_cpu() after ->init().
6646 	 */
6647 	cpus_read_lock();
6648 
6649 	/*
6650 	 * Make the scheduler instance visible. Must be inside cpus_read_lock().
6651 	 * See handle_hotplug().
6652 	 */
6653 	rcu_assign_pointer(scx_root, sch);
6654 
6655 	ret = scx_link_sched(sch);
6656 	if (ret)
6657 		goto err_disable;
6658 
6659 	scx_idle_enable(ops);
6660 
6661 	if (sch->ops.init) {
6662 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init, NULL);
6663 		if (ret) {
6664 			ret = ops_sanitize_err(sch, "init", ret);
6665 			cpus_read_unlock();
6666 			scx_error(sch, "ops.init() failed (%d)", ret);
6667 			goto err_disable;
6668 		}
6669 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
6670 	}
6671 
6672 	for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++)
6673 		if (((void (**)(void))ops)[i])
6674 			set_bit(i, sch->has_op);
6675 
6676 	ret = check_hotplug_seq(sch, ops);
6677 	if (ret) {
6678 		cpus_read_unlock();
6679 		goto err_disable;
6680 	}
6681 	scx_idle_update_selcpu_topology(ops);
6682 
6683 	cpus_read_unlock();
6684 
6685 	ret = validate_ops(sch, ops);
6686 	if (ret)
6687 		goto err_disable;
6688 
6689 	/*
6690 	 * Once __scx_enabled is set, %current can be switched to SCX anytime.
6691 	 * This can lead to stalls as some BPF schedulers (e.g. userspace
6692 	 * scheduling) may not function correctly before all tasks are switched.
6693 	 * Init in bypass mode to guarantee forward progress.
6694 	 */
6695 	scx_bypass(sch, true);
6696 
6697 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
6698 		if (((void (**)(void))ops)[i])
6699 			set_bit(i, sch->has_op);
6700 
6701 	if (sch->ops.cpu_acquire || sch->ops.cpu_release)
6702 		sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT;
6703 
6704 	/*
6705 	 * Lock out forks, cgroup on/offlining and moves before opening the
6706 	 * floodgate so that they don't wander into the operations prematurely.
6707 	 */
6708 	percpu_down_write(&scx_fork_rwsem);
6709 
6710 	WARN_ON_ONCE(scx_init_task_enabled);
6711 	scx_init_task_enabled = true;
6712 
6713 	/*
6714 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
6715 	 * preventing new tasks from being added. No need to exclude tasks
6716 	 * leaving as sched_ext_free() can handle both prepped and enabled
6717 	 * tasks. Prep all tasks first and then enable them with preemption
6718 	 * disabled.
6719 	 *
6720 	 * All cgroups should be initialized before scx_init_task() so that the
6721 	 * BPF scheduler can reliably track each task's cgroup membership from
6722 	 * scx_init_task(). Lock out cgroup on/offlining and task migrations
6723 	 * while tasks are being initialized so that scx_cgroup_can_attach()
6724 	 * never sees uninitialized tasks.
6725 	 */
6726 	scx_cgroup_lock();
6727 	set_cgroup_sched(sch_cgroup(sch), sch);
6728 	ret = scx_cgroup_init(sch);
6729 	if (ret)
6730 		goto err_disable_unlock_all;
6731 
6732 	scx_task_iter_start(&sti, NULL);
6733 	while ((p = scx_task_iter_next_locked(&sti))) {
6734 		/*
6735 		 * @p may already be dead, have lost all its usages counts and
6736 		 * be waiting for RCU grace period before being freed. @p can't
6737 		 * be initialized for SCX in such cases and should be ignored.
6738 		 */
6739 		if (!tryget_task_struct(p))
6740 			continue;
6741 
6742 		scx_task_iter_unlock(&sti);
6743 
6744 		ret = scx_init_task(sch, p, false);
6745 		if (ret) {
6746 			put_task_struct(p);
6747 			scx_task_iter_stop(&sti);
6748 			scx_error(sch, "ops.init_task() failed (%d) for %s[%d]",
6749 				  ret, p->comm, p->pid);
6750 			goto err_disable_unlock_all;
6751 		}
6752 
6753 		scx_set_task_sched(p, sch);
6754 		scx_set_task_state(p, SCX_TASK_READY);
6755 
6756 		put_task_struct(p);
6757 	}
6758 	scx_task_iter_stop(&sti);
6759 	scx_cgroup_unlock();
6760 	percpu_up_write(&scx_fork_rwsem);
6761 
6762 	/*
6763 	 * All tasks are READY. It's safe to turn on scx_enabled() and switch
6764 	 * all eligible tasks.
6765 	 */
6766 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
6767 	static_branch_enable(&__scx_enabled);
6768 
6769 	/*
6770 	 * We're fully committed and can't fail. The task READY -> ENABLED
6771 	 * transitions here are synchronized against sched_ext_free() through
6772 	 * scx_tasks_lock.
6773 	 */
6774 	percpu_down_write(&scx_fork_rwsem);
6775 	scx_task_iter_start(&sti, NULL);
6776 	while ((p = scx_task_iter_next_locked(&sti))) {
6777 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
6778 		const struct sched_class *old_class = p->sched_class;
6779 		const struct sched_class *new_class = scx_setscheduler_class(p);
6780 
6781 		if (scx_get_task_state(p) != SCX_TASK_READY)
6782 			continue;
6783 
6784 		if (old_class != new_class)
6785 			queue_flags |= DEQUEUE_CLASS;
6786 
6787 		scoped_guard (sched_change, p, queue_flags) {
6788 			p->scx.slice = READ_ONCE(sch->slice_dfl);
6789 			p->sched_class = new_class;
6790 		}
6791 	}
6792 	scx_task_iter_stop(&sti);
6793 	percpu_up_write(&scx_fork_rwsem);
6794 
6795 	scx_bypass(sch, false);
6796 
6797 	if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) {
6798 		WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE);
6799 		goto err_disable;
6800 	}
6801 
6802 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
6803 		static_branch_enable(&__scx_switched_all);
6804 
6805 	pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n",
6806 		sch->ops.name, scx_switched_all() ? "" : " (partial)");
6807 	kobject_uevent(&sch->kobj, KOBJ_ADD);
6808 	mutex_unlock(&scx_enable_mutex);
6809 
6810 	atomic_long_inc(&scx_enable_seq);
6811 
6812 	cmd->ret = 0;
6813 	return;
6814 
6815 err_free_ksyncs:
6816 	free_kick_syncs();
6817 err_unlock:
6818 	mutex_unlock(&scx_enable_mutex);
6819 	cmd->ret = ret;
6820 	return;
6821 
6822 err_disable_unlock_all:
6823 	scx_cgroup_unlock();
6824 	percpu_up_write(&scx_fork_rwsem);
6825 	/* we'll soon enter disable path, keep bypass on */
6826 err_disable:
6827 	mutex_unlock(&scx_enable_mutex);
6828 	/*
6829 	 * Returning an error code here would not pass all the error information
6830 	 * to userspace. Record errno using scx_error() for cases scx_error()
6831 	 * wasn't already invoked and exit indicating success so that the error
6832 	 * is notified through ops.exit() with all the details.
6833 	 *
6834 	 * Flush scx_disable_work to ensure that error is reported before init
6835 	 * completion. sch's base reference will be put by bpf_scx_unreg().
6836 	 */
6837 	scx_error(sch, "scx_root_enable() failed (%d)", ret);
6838 	kthread_flush_work(&sch->disable_work);
6839 	cmd->ret = 0;
6840 }
6841 
6842 #ifdef CONFIG_EXT_SUB_SCHED
6843 /* verify that a scheduler can be attached to @cgrp and return the parent */
6844 static struct scx_sched *find_parent_sched(struct cgroup *cgrp)
6845 {
6846 	struct scx_sched *parent = cgrp->scx_sched;
6847 	struct scx_sched *pos;
6848 
6849 	lockdep_assert_held(&scx_sched_lock);
6850 
6851 	/* can't attach twice to the same cgroup */
6852 	if (parent->cgrp == cgrp)
6853 		return ERR_PTR(-EBUSY);
6854 
6855 	/* does $parent allow sub-scheds? */
6856 	if (!parent->ops.sub_attach)
6857 		return ERR_PTR(-EOPNOTSUPP);
6858 
6859 	/* can't insert between $parent and its exiting children */
6860 	list_for_each_entry(pos, &parent->children, sibling)
6861 		if (cgroup_is_descendant(pos->cgrp, cgrp))
6862 			return ERR_PTR(-EBUSY);
6863 
6864 	return parent;
6865 }
6866 
6867 static bool assert_task_ready_or_enabled(struct task_struct *p)
6868 {
6869 	u32 state = scx_get_task_state(p);
6870 
6871 	switch (state) {
6872 	case SCX_TASK_READY:
6873 	case SCX_TASK_ENABLED:
6874 		return true;
6875 	default:
6876 		WARN_ONCE(true, "sched_ext: Invalid task state %d for %s[%d] during enabling sub sched",
6877 			  state, p->comm, p->pid);
6878 		return false;
6879 	}
6880 }
6881 
6882 static void scx_sub_enable_workfn(struct kthread_work *work)
6883 {
6884 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
6885 	struct sched_ext_ops *ops = cmd->ops;
6886 	struct cgroup *cgrp;
6887 	struct scx_sched *parent, *sch;
6888 	struct scx_task_iter sti;
6889 	struct task_struct *p;
6890 	s32 i, ret;
6891 
6892 	mutex_lock(&scx_enable_mutex);
6893 
6894 	if (!scx_enabled()) {
6895 		ret = -ENODEV;
6896 		goto out_unlock;
6897 	}
6898 
6899 	cgrp = cgroup_get_from_id(ops->sub_cgroup_id);
6900 	if (IS_ERR(cgrp)) {
6901 		ret = PTR_ERR(cgrp);
6902 		goto out_unlock;
6903 	}
6904 
6905 	raw_spin_lock_irq(&scx_sched_lock);
6906 	parent = find_parent_sched(cgrp);
6907 	if (IS_ERR(parent)) {
6908 		raw_spin_unlock_irq(&scx_sched_lock);
6909 		ret = PTR_ERR(parent);
6910 		goto out_put_cgrp;
6911 	}
6912 	kobject_get(&parent->kobj);
6913 	raw_spin_unlock_irq(&scx_sched_lock);
6914 
6915 	/* scx_alloc_and_add_sched() consumes @cgrp whether it succeeds or not */
6916 	sch = scx_alloc_and_add_sched(ops, cgrp, parent);
6917 	kobject_put(&parent->kobj);
6918 	if (IS_ERR(sch)) {
6919 		ret = PTR_ERR(sch);
6920 		goto out_unlock;
6921 	}
6922 
6923 	ret = scx_link_sched(sch);
6924 	if (ret)
6925 		goto err_disable;
6926 
6927 	if (sch->level >= SCX_SUB_MAX_DEPTH) {
6928 		scx_error(sch, "max nesting depth %d violated",
6929 			  SCX_SUB_MAX_DEPTH);
6930 		goto err_disable;
6931 	}
6932 
6933 	if (sch->ops.init) {
6934 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init, NULL);
6935 		if (ret) {
6936 			ret = ops_sanitize_err(sch, "init", ret);
6937 			scx_error(sch, "ops.init() failed (%d)", ret);
6938 			goto err_disable;
6939 		}
6940 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
6941 	}
6942 
6943 	if (validate_ops(sch, ops))
6944 		goto err_disable;
6945 
6946 	struct scx_sub_attach_args sub_attach_args = {
6947 		.ops = &sch->ops,
6948 		.cgroup_path = sch->cgrp_path,
6949 	};
6950 
6951 	ret = SCX_CALL_OP_RET(parent, SCX_KF_UNLOCKED, sub_attach, NULL,
6952 			      &sub_attach_args);
6953 	if (ret) {
6954 		ret = ops_sanitize_err(sch, "sub_attach", ret);
6955 		scx_error(sch, "parent rejected (%d)", ret);
6956 		goto err_disable;
6957 	}
6958 	sch->sub_attached = true;
6959 
6960 	scx_bypass(sch, true);
6961 
6962 	for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++)
6963 		if (((void (**)(void))ops)[i])
6964 			set_bit(i, sch->has_op);
6965 
6966 	percpu_down_write(&scx_fork_rwsem);
6967 	scx_cgroup_lock();
6968 
6969 	/*
6970 	 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see
6971 	 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down.
6972 	 */
6973 	set_cgroup_sched(sch_cgroup(sch), sch);
6974 	if (!(cgrp->self.flags & CSS_ONLINE)) {
6975 		scx_error(sch, "cgroup is not online");
6976 		goto err_unlock_and_disable;
6977 	}
6978 
6979 	/*
6980 	 * Initialize tasks for the new child $sch without exiting them for
6981 	 * $parent so that the tasks can always be reverted back to $parent
6982 	 * sched on child init failure.
6983 	 */
6984 	WARN_ON_ONCE(scx_enabling_sub_sched);
6985 	scx_enabling_sub_sched = sch;
6986 
6987 	scx_task_iter_start(&sti, sch->cgrp);
6988 	while ((p = scx_task_iter_next_locked(&sti))) {
6989 		struct rq *rq;
6990 		struct rq_flags rf;
6991 
6992 		/*
6993 		 * Task iteration may visit the same task twice when racing
6994 		 * against exiting. Use %SCX_TASK_SUB_INIT to mark tasks which
6995 		 * finished __scx_init_task() and skip if set.
6996 		 *
6997 		 * A task may exit and get freed between __scx_init_task()
6998 		 * completion and scx_enable_task(). In such cases,
6999 		 * scx_disable_and_exit_task() must exit the task for both the
7000 		 * parent and child scheds.
7001 		 */
7002 		if (p->scx.flags & SCX_TASK_SUB_INIT)
7003 			continue;
7004 
7005 		/* see scx_root_enable() */
7006 		if (!tryget_task_struct(p))
7007 			continue;
7008 
7009 		if (!assert_task_ready_or_enabled(p)) {
7010 			ret = -EINVAL;
7011 			goto abort;
7012 		}
7013 
7014 		scx_task_iter_unlock(&sti);
7015 
7016 		/*
7017 		 * As $p is still on $parent, it can't be transitioned to INIT.
7018 		 * Let's worry about task state later. Use __scx_init_task().
7019 		 */
7020 		ret = __scx_init_task(sch, p, false);
7021 		if (ret)
7022 			goto abort;
7023 
7024 		rq = task_rq_lock(p, &rf);
7025 		p->scx.flags |= SCX_TASK_SUB_INIT;
7026 		task_rq_unlock(rq, p, &rf);
7027 
7028 		put_task_struct(p);
7029 	}
7030 	scx_task_iter_stop(&sti);
7031 
7032 	/*
7033 	 * All tasks are prepped. Disable/exit tasks for $parent and enable for
7034 	 * the new @sch.
7035 	 */
7036 	scx_task_iter_start(&sti, sch->cgrp);
7037 	while ((p = scx_task_iter_next_locked(&sti))) {
7038 		/*
7039 		 * Use clearing of %SCX_TASK_SUB_INIT to detect and skip
7040 		 * duplicate iterations.
7041 		 */
7042 		if (!(p->scx.flags & SCX_TASK_SUB_INIT))
7043 			continue;
7044 
7045 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
7046 			/*
7047 			 * $p must be either READY or ENABLED. If ENABLED,
7048 			 * __scx_disabled_and_exit_task() first disables and
7049 			 * makes it READY. However, after exiting $p, it will
7050 			 * leave $p as READY.
7051 			 */
7052 			assert_task_ready_or_enabled(p);
7053 			__scx_disable_and_exit_task(parent, p);
7054 
7055 			/*
7056 			 * $p is now only initialized for @sch and READY, which
7057 			 * is what we want. Assign it to @sch and enable.
7058 			 */
7059 			rcu_assign_pointer(p->scx.sched, sch);
7060 			scx_enable_task(sch, p);
7061 
7062 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
7063 		}
7064 	}
7065 	scx_task_iter_stop(&sti);
7066 
7067 	scx_enabling_sub_sched = NULL;
7068 
7069 	scx_cgroup_unlock();
7070 	percpu_up_write(&scx_fork_rwsem);
7071 
7072 	scx_bypass(sch, false);
7073 
7074 	pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name);
7075 	kobject_uevent(&sch->kobj, KOBJ_ADD);
7076 	ret = 0;
7077 	goto out_unlock;
7078 
7079 out_put_cgrp:
7080 	cgroup_put(cgrp);
7081 out_unlock:
7082 	mutex_unlock(&scx_enable_mutex);
7083 	cmd->ret = ret;
7084 	return;
7085 
7086 abort:
7087 	put_task_struct(p);
7088 	scx_task_iter_stop(&sti);
7089 	scx_enabling_sub_sched = NULL;
7090 
7091 	scx_task_iter_start(&sti, sch->cgrp);
7092 	while ((p = scx_task_iter_next_locked(&sti))) {
7093 		if (p->scx.flags & SCX_TASK_SUB_INIT) {
7094 			__scx_disable_and_exit_task(sch, p);
7095 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
7096 		}
7097 	}
7098 	scx_task_iter_stop(&sti);
7099 err_unlock_and_disable:
7100 	/* we'll soon enter disable path, keep bypass on */
7101 	scx_cgroup_unlock();
7102 	percpu_up_write(&scx_fork_rwsem);
7103 err_disable:
7104 	mutex_unlock(&scx_enable_mutex);
7105 	kthread_flush_work(&sch->disable_work);
7106 	cmd->ret = 0;
7107 }
7108 
7109 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb,
7110 				      unsigned long action, void *data)
7111 {
7112 	struct cgroup *cgrp = data;
7113 	struct cgroup *parent = cgroup_parent(cgrp);
7114 
7115 	if (!cgroup_on_dfl(cgrp))
7116 		return NOTIFY_OK;
7117 
7118 	switch (action) {
7119 	case CGROUP_LIFETIME_ONLINE:
7120 		/* inherit ->scx_sched from $parent */
7121 		if (parent)
7122 			rcu_assign_pointer(cgrp->scx_sched, parent->scx_sched);
7123 		break;
7124 	case CGROUP_LIFETIME_OFFLINE:
7125 		/* if there is a sched attached, shoot it down */
7126 		if (cgrp->scx_sched && cgrp->scx_sched->cgrp == cgrp)
7127 			scx_exit(cgrp->scx_sched, SCX_EXIT_UNREG_KERN,
7128 				 SCX_ECODE_RSN_CGROUP_OFFLINE,
7129 				 "cgroup %llu going offline", cgroup_id(cgrp));
7130 		break;
7131 	}
7132 
7133 	return NOTIFY_OK;
7134 }
7135 
7136 static struct notifier_block scx_cgroup_lifetime_nb = {
7137 	.notifier_call = scx_cgroup_lifetime_notify,
7138 };
7139 
7140 static s32 __init scx_cgroup_lifetime_notifier_init(void)
7141 {
7142 	return blocking_notifier_chain_register(&cgroup_lifetime_notifier,
7143 						&scx_cgroup_lifetime_nb);
7144 }
7145 core_initcall(scx_cgroup_lifetime_notifier_init);
7146 #endif	/* CONFIG_EXT_SUB_SCHED */
7147 
7148 static s32 scx_enable(struct sched_ext_ops *ops, struct bpf_link *link)
7149 {
7150 	static struct kthread_worker *helper;
7151 	static DEFINE_MUTEX(helper_mutex);
7152 	struct scx_enable_cmd cmd;
7153 
7154 	if (!cpumask_equal(housekeeping_cpumask(HK_TYPE_DOMAIN),
7155 			   cpu_possible_mask)) {
7156 		pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n");
7157 		return -EINVAL;
7158 	}
7159 
7160 	if (!READ_ONCE(helper)) {
7161 		mutex_lock(&helper_mutex);
7162 		if (!helper) {
7163 			struct kthread_worker *w =
7164 				kthread_run_worker(0, "scx_enable_helper");
7165 			if (IS_ERR_OR_NULL(w)) {
7166 				mutex_unlock(&helper_mutex);
7167 				return -ENOMEM;
7168 			}
7169 			sched_set_fifo(w->task);
7170 			WRITE_ONCE(helper, w);
7171 		}
7172 		mutex_unlock(&helper_mutex);
7173 	}
7174 
7175 #ifdef CONFIG_EXT_SUB_SCHED
7176 	if (ops->sub_cgroup_id > 1)
7177 		kthread_init_work(&cmd.work, scx_sub_enable_workfn);
7178 	else
7179 #endif	/* CONFIG_EXT_SUB_SCHED */
7180 		kthread_init_work(&cmd.work, scx_root_enable_workfn);
7181 	cmd.ops = ops;
7182 
7183 	kthread_queue_work(READ_ONCE(helper), &cmd.work);
7184 	kthread_flush_work(&cmd.work);
7185 	return cmd.ret;
7186 }
7187 
7188 
7189 /********************************************************************************
7190  * bpf_struct_ops plumbing.
7191  */
7192 #include <linux/bpf_verifier.h>
7193 #include <linux/bpf.h>
7194 #include <linux/btf.h>
7195 
7196 static const struct btf_type *task_struct_type;
7197 
7198 static bool bpf_scx_is_valid_access(int off, int size,
7199 				    enum bpf_access_type type,
7200 				    const struct bpf_prog *prog,
7201 				    struct bpf_insn_access_aux *info)
7202 {
7203 	if (type != BPF_READ)
7204 		return false;
7205 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
7206 		return false;
7207 	if (off % size != 0)
7208 		return false;
7209 
7210 	return btf_ctx_access(off, size, type, prog, info);
7211 }
7212 
7213 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
7214 				     const struct bpf_reg_state *reg, int off,
7215 				     int size)
7216 {
7217 	const struct btf_type *t;
7218 
7219 	t = btf_type_by_id(reg->btf, reg->btf_id);
7220 	if (t == task_struct_type) {
7221 		/*
7222 		 * COMPAT: Will be removed in v6.23.
7223 		 */
7224 		if ((off >= offsetof(struct task_struct, scx.slice) &&
7225 		     off + size <= offsetofend(struct task_struct, scx.slice)) ||
7226 		    (off >= offsetof(struct task_struct, scx.dsq_vtime) &&
7227 		     off + size <= offsetofend(struct task_struct, scx.dsq_vtime))) {
7228 			pr_warn("sched_ext: Writing directly to p->scx.slice/dsq_vtime is deprecated, use scx_bpf_task_set_slice/dsq_vtime()");
7229 			return SCALAR_VALUE;
7230 		}
7231 
7232 		if (off >= offsetof(struct task_struct, scx.disallow) &&
7233 		    off + size <= offsetofend(struct task_struct, scx.disallow))
7234 			return SCALAR_VALUE;
7235 	}
7236 
7237 	return -EACCES;
7238 }
7239 
7240 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
7241 	.get_func_proto = bpf_base_func_proto,
7242 	.is_valid_access = bpf_scx_is_valid_access,
7243 	.btf_struct_access = bpf_scx_btf_struct_access,
7244 };
7245 
7246 static int bpf_scx_init_member(const struct btf_type *t,
7247 			       const struct btf_member *member,
7248 			       void *kdata, const void *udata)
7249 {
7250 	const struct sched_ext_ops *uops = udata;
7251 	struct sched_ext_ops *ops = kdata;
7252 	u32 moff = __btf_member_bit_offset(t, member) / 8;
7253 	int ret;
7254 
7255 	switch (moff) {
7256 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
7257 		if (*(u32 *)(udata + moff) > INT_MAX)
7258 			return -E2BIG;
7259 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
7260 		return 1;
7261 	case offsetof(struct sched_ext_ops, flags):
7262 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
7263 			return -EINVAL;
7264 		ops->flags = *(u64 *)(udata + moff);
7265 		return 1;
7266 	case offsetof(struct sched_ext_ops, name):
7267 		ret = bpf_obj_name_cpy(ops->name, uops->name,
7268 				       sizeof(ops->name));
7269 		if (ret < 0)
7270 			return ret;
7271 		if (ret == 0)
7272 			return -EINVAL;
7273 		return 1;
7274 	case offsetof(struct sched_ext_ops, timeout_ms):
7275 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
7276 		    SCX_WATCHDOG_MAX_TIMEOUT)
7277 			return -E2BIG;
7278 		ops->timeout_ms = *(u32 *)(udata + moff);
7279 		return 1;
7280 	case offsetof(struct sched_ext_ops, exit_dump_len):
7281 		ops->exit_dump_len =
7282 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
7283 		return 1;
7284 	case offsetof(struct sched_ext_ops, hotplug_seq):
7285 		ops->hotplug_seq = *(u64 *)(udata + moff);
7286 		return 1;
7287 #ifdef CONFIG_EXT_SUB_SCHED
7288 	case offsetof(struct sched_ext_ops, sub_cgroup_id):
7289 		ops->sub_cgroup_id = *(u64 *)(udata + moff);
7290 		return 1;
7291 #endif	/* CONFIG_EXT_SUB_SCHED */
7292 	}
7293 
7294 	return 0;
7295 }
7296 
7297 #ifdef CONFIG_EXT_SUB_SCHED
7298 static void scx_pstack_recursion_on_dispatch(struct bpf_prog *prog)
7299 {
7300 	struct scx_sched *sch;
7301 
7302 	guard(rcu)();
7303 	sch = scx_prog_sched(prog->aux);
7304 	if (unlikely(!sch))
7305 		return;
7306 
7307 	scx_error(sch, "dispatch recursion detected");
7308 }
7309 #endif	/* CONFIG_EXT_SUB_SCHED */
7310 
7311 static int bpf_scx_check_member(const struct btf_type *t,
7312 				const struct btf_member *member,
7313 				const struct bpf_prog *prog)
7314 {
7315 	u32 moff = __btf_member_bit_offset(t, member) / 8;
7316 
7317 	switch (moff) {
7318 	case offsetof(struct sched_ext_ops, init_task):
7319 #ifdef CONFIG_EXT_GROUP_SCHED
7320 	case offsetof(struct sched_ext_ops, cgroup_init):
7321 	case offsetof(struct sched_ext_ops, cgroup_exit):
7322 	case offsetof(struct sched_ext_ops, cgroup_prep_move):
7323 #endif
7324 	case offsetof(struct sched_ext_ops, cpu_online):
7325 	case offsetof(struct sched_ext_ops, cpu_offline):
7326 	case offsetof(struct sched_ext_ops, init):
7327 	case offsetof(struct sched_ext_ops, exit):
7328 	case offsetof(struct sched_ext_ops, sub_attach):
7329 	case offsetof(struct sched_ext_ops, sub_detach):
7330 		break;
7331 	default:
7332 		if (prog->sleepable)
7333 			return -EINVAL;
7334 	}
7335 
7336 #ifdef CONFIG_EXT_SUB_SCHED
7337 	/*
7338 	 * Enable private stack for operations that can nest along the
7339 	 * hierarchy.
7340 	 *
7341 	 * XXX - Ideally, we should only do this for scheds that allow
7342 	 * sub-scheds and sub-scheds themselves but I don't know how to access
7343 	 * struct_ops from here.
7344 	 */
7345 	switch (moff) {
7346 	case offsetof(struct sched_ext_ops, dispatch):
7347 		prog->aux->priv_stack_requested = true;
7348 		prog->aux->recursion_detected = scx_pstack_recursion_on_dispatch;
7349 	}
7350 #endif	/* CONFIG_EXT_SUB_SCHED */
7351 
7352 	return 0;
7353 }
7354 
7355 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
7356 {
7357 	return scx_enable(kdata, link);
7358 }
7359 
7360 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
7361 {
7362 	struct sched_ext_ops *ops = kdata;
7363 	struct scx_sched *sch = rcu_dereference_protected(ops->priv, true);
7364 
7365 	scx_disable(sch, SCX_EXIT_UNREG);
7366 	kthread_flush_work(&sch->disable_work);
7367 	RCU_INIT_POINTER(ops->priv, NULL);
7368 	kobject_put(&sch->kobj);
7369 }
7370 
7371 static int bpf_scx_init(struct btf *btf)
7372 {
7373 	task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]);
7374 
7375 	return 0;
7376 }
7377 
7378 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
7379 {
7380 	/*
7381 	 * sched_ext does not support updating the actively-loaded BPF
7382 	 * scheduler, as registering a BPF scheduler can always fail if the
7383 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
7384 	 * etc. Similarly, we can always race with unregistration happening
7385 	 * elsewhere, such as with sysrq.
7386 	 */
7387 	return -EOPNOTSUPP;
7388 }
7389 
7390 static int bpf_scx_validate(void *kdata)
7391 {
7392 	return 0;
7393 }
7394 
7395 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
7396 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
7397 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
7398 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {}
7399 static void sched_ext_ops__tick(struct task_struct *p) {}
7400 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {}
7401 static void sched_ext_ops__running(struct task_struct *p) {}
7402 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {}
7403 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {}
7404 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; }
7405 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; }
7406 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {}
7407 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {}
7408 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {}
7409 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {}
7410 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {}
7411 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
7412 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {}
7413 static void sched_ext_ops__enable(struct task_struct *p) {}
7414 static void sched_ext_ops__disable(struct task_struct *p) {}
7415 #ifdef CONFIG_EXT_GROUP_SCHED
7416 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; }
7417 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {}
7418 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; }
7419 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
7420 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
7421 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
7422 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
7423 static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}
7424 #endif	/* CONFIG_EXT_GROUP_SCHED */
7425 static s32 sched_ext_ops__sub_attach(struct scx_sub_attach_args *args) { return -EINVAL; }
7426 static void sched_ext_ops__sub_detach(struct scx_sub_detach_args *args) {}
7427 static void sched_ext_ops__cpu_online(s32 cpu) {}
7428 static void sched_ext_ops__cpu_offline(s32 cpu) {}
7429 static s32 sched_ext_ops__init(void) { return -EINVAL; }
7430 static void sched_ext_ops__exit(struct scx_exit_info *info) {}
7431 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {}
7432 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {}
7433 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {}
7434 
7435 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
7436 	.select_cpu		= sched_ext_ops__select_cpu,
7437 	.enqueue		= sched_ext_ops__enqueue,
7438 	.dequeue		= sched_ext_ops__dequeue,
7439 	.dispatch		= sched_ext_ops__dispatch,
7440 	.tick			= sched_ext_ops__tick,
7441 	.runnable		= sched_ext_ops__runnable,
7442 	.running		= sched_ext_ops__running,
7443 	.stopping		= sched_ext_ops__stopping,
7444 	.quiescent		= sched_ext_ops__quiescent,
7445 	.yield			= sched_ext_ops__yield,
7446 	.core_sched_before	= sched_ext_ops__core_sched_before,
7447 	.set_weight		= sched_ext_ops__set_weight,
7448 	.set_cpumask		= sched_ext_ops__set_cpumask,
7449 	.update_idle		= sched_ext_ops__update_idle,
7450 	.cpu_acquire		= sched_ext_ops__cpu_acquire,
7451 	.cpu_release		= sched_ext_ops__cpu_release,
7452 	.init_task		= sched_ext_ops__init_task,
7453 	.exit_task		= sched_ext_ops__exit_task,
7454 	.enable			= sched_ext_ops__enable,
7455 	.disable		= sched_ext_ops__disable,
7456 #ifdef CONFIG_EXT_GROUP_SCHED
7457 	.cgroup_init		= sched_ext_ops__cgroup_init,
7458 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
7459 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
7460 	.cgroup_move		= sched_ext_ops__cgroup_move,
7461 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
7462 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
7463 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
7464 	.cgroup_set_idle	= sched_ext_ops__cgroup_set_idle,
7465 #endif
7466 	.sub_attach		= sched_ext_ops__sub_attach,
7467 	.sub_detach		= sched_ext_ops__sub_detach,
7468 	.cpu_online		= sched_ext_ops__cpu_online,
7469 	.cpu_offline		= sched_ext_ops__cpu_offline,
7470 	.init			= sched_ext_ops__init,
7471 	.exit			= sched_ext_ops__exit,
7472 	.dump			= sched_ext_ops__dump,
7473 	.dump_cpu		= sched_ext_ops__dump_cpu,
7474 	.dump_task		= sched_ext_ops__dump_task,
7475 };
7476 
7477 static struct bpf_struct_ops bpf_sched_ext_ops = {
7478 	.verifier_ops = &bpf_scx_verifier_ops,
7479 	.reg = bpf_scx_reg,
7480 	.unreg = bpf_scx_unreg,
7481 	.check_member = bpf_scx_check_member,
7482 	.init_member = bpf_scx_init_member,
7483 	.init = bpf_scx_init,
7484 	.update = bpf_scx_update,
7485 	.validate = bpf_scx_validate,
7486 	.name = "sched_ext_ops",
7487 	.owner = THIS_MODULE,
7488 	.cfi_stubs = &__bpf_ops_sched_ext_ops
7489 };
7490 
7491 
7492 /********************************************************************************
7493  * System integration and init.
7494  */
7495 
7496 static void sysrq_handle_sched_ext_reset(u8 key)
7497 {
7498 	struct scx_sched *sch;
7499 
7500 	rcu_read_lock();
7501 	sch = rcu_dereference(scx_root);
7502 	if (likely(sch))
7503 		scx_disable(sch, SCX_EXIT_SYSRQ);
7504 	else
7505 		pr_info("sched_ext: BPF schedulers not loaded\n");
7506 	rcu_read_unlock();
7507 }
7508 
7509 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
7510 	.handler	= sysrq_handle_sched_ext_reset,
7511 	.help_msg	= "reset-sched-ext(S)",
7512 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
7513 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
7514 };
7515 
7516 static void sysrq_handle_sched_ext_dump(u8 key)
7517 {
7518 	struct scx_exit_info ei = { .kind = SCX_EXIT_NONE, .reason = "SysRq-D" };
7519 	struct scx_sched *sch;
7520 
7521 	list_for_each_entry_rcu(sch, &scx_sched_all, all)
7522 		scx_dump_state(sch, &ei, 0, false);
7523 }
7524 
7525 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
7526 	.handler	= sysrq_handle_sched_ext_dump,
7527 	.help_msg	= "dump-sched-ext(D)",
7528 	.action_msg	= "Trigger sched_ext debug dump",
7529 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
7530 };
7531 
7532 static bool can_skip_idle_kick(struct rq *rq)
7533 {
7534 	lockdep_assert_rq_held(rq);
7535 
7536 	/*
7537 	 * We can skip idle kicking if @rq is going to go through at least one
7538 	 * full SCX scheduling cycle before going idle. Just checking whether
7539 	 * curr is not idle is insufficient because we could be racing
7540 	 * balance_one() trying to pull the next task from a remote rq, which
7541 	 * may fail, and @rq may become idle afterwards.
7542 	 *
7543 	 * The race window is small and we don't and can't guarantee that @rq is
7544 	 * only kicked while idle anyway. Skip only when sure.
7545 	 */
7546 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_BALANCE);
7547 }
7548 
7549 static bool kick_one_cpu(s32 cpu, struct rq *this_rq, unsigned long *ksyncs)
7550 {
7551 	struct rq *rq = cpu_rq(cpu);
7552 	struct scx_rq *this_scx = &this_rq->scx;
7553 	const struct sched_class *cur_class;
7554 	bool should_wait = false;
7555 	unsigned long flags;
7556 
7557 	raw_spin_rq_lock_irqsave(rq, flags);
7558 	cur_class = rq->curr->sched_class;
7559 
7560 	/*
7561 	 * During CPU hotplug, a CPU may depend on kicking itself to make
7562 	 * forward progress. Allow kicking self regardless of online state. If
7563 	 * @cpu is running a higher class task, we have no control over @cpu.
7564 	 * Skip kicking.
7565 	 */
7566 	if ((cpu_online(cpu) || cpu == cpu_of(this_rq)) &&
7567 	    !sched_class_above(cur_class, &ext_sched_class)) {
7568 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_preempt)) {
7569 			if (cur_class == &ext_sched_class)
7570 				rq->curr->scx.slice = 0;
7571 			cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
7572 		}
7573 
7574 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_wait)) {
7575 			if (cur_class == &ext_sched_class) {
7576 				ksyncs[cpu] = rq->scx.kick_sync;
7577 				should_wait = true;
7578 			} else {
7579 				cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
7580 			}
7581 		}
7582 
7583 		resched_curr(rq);
7584 	} else {
7585 		cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
7586 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
7587 	}
7588 
7589 	raw_spin_rq_unlock_irqrestore(rq, flags);
7590 
7591 	return should_wait;
7592 }
7593 
7594 static void kick_one_cpu_if_idle(s32 cpu, struct rq *this_rq)
7595 {
7596 	struct rq *rq = cpu_rq(cpu);
7597 	unsigned long flags;
7598 
7599 	raw_spin_rq_lock_irqsave(rq, flags);
7600 
7601 	if (!can_skip_idle_kick(rq) &&
7602 	    (cpu_online(cpu) || cpu == cpu_of(this_rq)))
7603 		resched_curr(rq);
7604 
7605 	raw_spin_rq_unlock_irqrestore(rq, flags);
7606 }
7607 
7608 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
7609 {
7610 	struct rq *this_rq = this_rq();
7611 	struct scx_rq *this_scx = &this_rq->scx;
7612 	struct scx_kick_syncs __rcu *ksyncs_pcpu = __this_cpu_read(scx_kick_syncs);
7613 	bool should_wait = false;
7614 	unsigned long *ksyncs;
7615 	s32 cpu;
7616 
7617 	if (unlikely(!ksyncs_pcpu)) {
7618 		pr_warn_once("kick_cpus_irq_workfn() called with NULL scx_kick_syncs");
7619 		return;
7620 	}
7621 
7622 	ksyncs = rcu_dereference_bh(ksyncs_pcpu)->syncs;
7623 
7624 	for_each_cpu(cpu, this_scx->cpus_to_kick) {
7625 		should_wait |= kick_one_cpu(cpu, this_rq, ksyncs);
7626 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick);
7627 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
7628 	}
7629 
7630 	for_each_cpu(cpu, this_scx->cpus_to_kick_if_idle) {
7631 		kick_one_cpu_if_idle(cpu, this_rq);
7632 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
7633 	}
7634 
7635 	if (!should_wait)
7636 		return;
7637 
7638 	for_each_cpu(cpu, this_scx->cpus_to_wait) {
7639 		unsigned long *wait_kick_sync = &cpu_rq(cpu)->scx.kick_sync;
7640 
7641 		/*
7642 		 * Busy-wait until the task running at the time of kicking is no
7643 		 * longer running. This can be used to implement e.g. core
7644 		 * scheduling.
7645 		 *
7646 		 * smp_cond_load_acquire() pairs with store_releases in
7647 		 * pick_task_scx() and put_prev_task_scx(). The former breaks
7648 		 * the wait if SCX's scheduling path is entered even if the same
7649 		 * task is picked subsequently. The latter is necessary to break
7650 		 * the wait when $cpu is taken by a higher sched class.
7651 		 */
7652 		if (cpu != cpu_of(this_rq))
7653 			smp_cond_load_acquire(wait_kick_sync, VAL != ksyncs[cpu]);
7654 
7655 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
7656 	}
7657 }
7658 
7659 /**
7660  * print_scx_info - print out sched_ext scheduler state
7661  * @log_lvl: the log level to use when printing
7662  * @p: target task
7663  *
7664  * If a sched_ext scheduler is enabled, print the name and state of the
7665  * scheduler. If @p is on sched_ext, print further information about the task.
7666  *
7667  * This function can be safely called on any task as long as the task_struct
7668  * itself is accessible. While safe, this function isn't synchronized and may
7669  * print out mixups or garbages of limited length.
7670  */
7671 void print_scx_info(const char *log_lvl, struct task_struct *p)
7672 {
7673 	struct scx_sched *sch = scx_root;
7674 	enum scx_enable_state state = scx_enable_state();
7675 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
7676 	char runnable_at_buf[22] = "?";
7677 	struct sched_class *class;
7678 	unsigned long runnable_at;
7679 
7680 	if (state == SCX_DISABLED)
7681 		return;
7682 
7683 	/*
7684 	 * Carefully check if the task was running on sched_ext, and then
7685 	 * carefully copy the time it's been runnable, and its state.
7686 	 */
7687 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
7688 	    class != &ext_sched_class) {
7689 		printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name,
7690 		       scx_enable_state_str[state], all);
7691 		return;
7692 	}
7693 
7694 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
7695 				      sizeof(runnable_at)))
7696 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
7697 			  jiffies_delta_msecs(runnable_at, jiffies));
7698 
7699 	/* print everything onto one line to conserve console space */
7700 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
7701 	       log_lvl, sch->ops.name, scx_enable_state_str[state], all,
7702 	       runnable_at_buf);
7703 }
7704 
7705 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr)
7706 {
7707 	struct scx_sched *sch;
7708 
7709 	guard(rcu)();
7710 
7711 	sch = rcu_dereference(scx_root);
7712 	if (!sch)
7713 		return NOTIFY_OK;
7714 
7715 	/*
7716 	 * SCX schedulers often have userspace components which are sometimes
7717 	 * involved in critial scheduling paths. PM operations involve freezing
7718 	 * userspace which can lead to scheduling misbehaviors including stalls.
7719 	 * Let's bypass while PM operations are in progress.
7720 	 */
7721 	switch (event) {
7722 	case PM_HIBERNATION_PREPARE:
7723 	case PM_SUSPEND_PREPARE:
7724 	case PM_RESTORE_PREPARE:
7725 		scx_bypass(sch, true);
7726 		break;
7727 	case PM_POST_HIBERNATION:
7728 	case PM_POST_SUSPEND:
7729 	case PM_POST_RESTORE:
7730 		scx_bypass(sch, false);
7731 		break;
7732 	}
7733 
7734 	return NOTIFY_OK;
7735 }
7736 
7737 static struct notifier_block scx_pm_notifier = {
7738 	.notifier_call = scx_pm_handler,
7739 };
7740 
7741 void __init init_sched_ext_class(void)
7742 {
7743 	s32 cpu, v;
7744 
7745 	/*
7746 	 * The following is to prevent the compiler from optimizing out the enum
7747 	 * definitions so that BPF scheduler implementations can use them
7748 	 * through the generated vmlinux.h.
7749 	 */
7750 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT |
7751 		   SCX_TG_ONLINE);
7752 
7753 	scx_idle_init_masks();
7754 
7755 	for_each_possible_cpu(cpu) {
7756 		struct rq *rq = cpu_rq(cpu);
7757 		int  n = cpu_to_node(cpu);
7758 
7759 		/* local_dsq's sch will be set during scx_root_enable() */
7760 		BUG_ON(init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL, NULL));
7761 
7762 		INIT_LIST_HEAD(&rq->scx.runnable_list);
7763 		INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals);
7764 
7765 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick, GFP_KERNEL, n));
7766 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick_if_idle, GFP_KERNEL, n));
7767 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_preempt, GFP_KERNEL, n));
7768 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_wait, GFP_KERNEL, n));
7769 		raw_spin_lock_init(&rq->scx.deferred_reenq_lock);
7770 		INIT_LIST_HEAD(&rq->scx.deferred_reenq_locals);
7771 		INIT_LIST_HEAD(&rq->scx.deferred_reenq_users);
7772 		rq->scx.deferred_irq_work = IRQ_WORK_INIT_HARD(deferred_irq_workfn);
7773 		rq->scx.kick_cpus_irq_work = IRQ_WORK_INIT_HARD(kick_cpus_irq_workfn);
7774 
7775 		if (cpu_online(cpu))
7776 			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
7777 	}
7778 
7779 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
7780 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
7781 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
7782 
7783 #ifdef CONFIG_EXT_SUB_SCHED
7784 	BUG_ON(rhashtable_init(&scx_sched_hash, &scx_sched_hash_params));
7785 #endif	/* CONFIG_EXT_SUB_SCHED */
7786 }
7787 
7788 
7789 /********************************************************************************
7790  * Helpers that can be called from the BPF scheduler.
7791  */
7792 static bool scx_vet_enq_flags(struct scx_sched *sch, u64 dsq_id, u64 *enq_flags)
7793 {
7794 	bool is_local = dsq_id == SCX_DSQ_LOCAL ||
7795 		(dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON;
7796 
7797 	if (*enq_flags & SCX_ENQ_IMMED) {
7798 		if (unlikely(!is_local)) {
7799 			scx_error(sch, "SCX_ENQ_IMMED on a non-local DSQ 0x%llx", dsq_id);
7800 			return false;
7801 		}
7802 	} else if ((sch->ops.flags & SCX_OPS_ALWAYS_ENQ_IMMED) && is_local) {
7803 		*enq_flags |= SCX_ENQ_IMMED;
7804 	}
7805 
7806 	return true;
7807 }
7808 
7809 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p,
7810 				    u64 dsq_id, u64 *enq_flags)
7811 {
7812 	if (!scx_kf_allowed(sch, SCX_KF_ENQUEUE | SCX_KF_DISPATCH))
7813 		return false;
7814 
7815 	lockdep_assert_irqs_disabled();
7816 
7817 	if (unlikely(!p)) {
7818 		scx_error(sch, "called with NULL task");
7819 		return false;
7820 	}
7821 
7822 	if (unlikely(*enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
7823 		scx_error(sch, "invalid enq_flags 0x%llx", *enq_flags);
7824 		return false;
7825 	}
7826 
7827 	/* see SCX_EV_INSERT_NOT_OWNED definition */
7828 	if (unlikely(!scx_task_on_sched(sch, p))) {
7829 		__scx_add_event(sch, SCX_EV_INSERT_NOT_OWNED, 1);
7830 		return false;
7831 	}
7832 
7833 	if (!scx_vet_enq_flags(sch, dsq_id, enq_flags))
7834 		return false;
7835 
7836 	return true;
7837 }
7838 
7839 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p,
7840 				  u64 dsq_id, u64 enq_flags)
7841 {
7842 	struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
7843 	struct task_struct *ddsp_task;
7844 
7845 	ddsp_task = __this_cpu_read(direct_dispatch_task);
7846 	if (ddsp_task) {
7847 		mark_direct_dispatch(sch, ddsp_task, p, dsq_id, enq_flags);
7848 		return;
7849 	}
7850 
7851 	if (unlikely(dspc->cursor >= sch->dsp_max_batch)) {
7852 		scx_error(sch, "dispatch buffer overflow");
7853 		return;
7854 	}
7855 
7856 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
7857 		.task = p,
7858 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
7859 		.dsq_id = dsq_id,
7860 		.enq_flags = enq_flags,
7861 	};
7862 }
7863 
7864 __bpf_kfunc_start_defs();
7865 
7866 /**
7867  * scx_bpf_dsq_insert - Insert a task into the FIFO queue of a DSQ
7868  * @p: task_struct to insert
7869  * @dsq_id: DSQ to insert into
7870  * @slice: duration @p can run for in nsecs, 0 to keep the current value
7871  * @enq_flags: SCX_ENQ_*
7872  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7873  *
7874  * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to
7875  * call this function spuriously. Can be called from ops.enqueue(),
7876  * ops.select_cpu(), and ops.dispatch().
7877  *
7878  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
7879  * and @p must match the task being enqueued.
7880  *
7881  * When called from ops.select_cpu(), @enq_flags and @dsp_id are stored, and @p
7882  * will be directly inserted into the corresponding dispatch queue after
7883  * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be
7884  * inserted into the local DSQ of the CPU returned by ops.select_cpu().
7885  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
7886  * task is inserted.
7887  *
7888  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
7889  * and this function can be called upto ops.dispatch_max_batch times to insert
7890  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
7891  * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the
7892  * counter.
7893  *
7894  * This function doesn't have any locking restrictions and may be called under
7895  * BPF locks (in the future when BPF introduces more flexible locking).
7896  *
7897  * @p is allowed to run for @slice. The scheduling path is triggered on slice
7898  * exhaustion. If zero, the current residual slice is maintained. If
7899  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
7900  * scx_bpf_kick_cpu() to trigger scheduling.
7901  *
7902  * Returns %true on successful insertion, %false on failure. On the root
7903  * scheduler, %false return triggers scheduler abort and the caller doesn't need
7904  * to check the return value.
7905  */
7906 __bpf_kfunc bool scx_bpf_dsq_insert___v2(struct task_struct *p, u64 dsq_id,
7907 					 u64 slice, u64 enq_flags,
7908 					 const struct bpf_prog_aux *aux)
7909 {
7910 	struct scx_sched *sch;
7911 
7912 	guard(rcu)();
7913 	sch = scx_prog_sched(aux);
7914 	if (unlikely(!sch))
7915 		return false;
7916 
7917 	if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags))
7918 		return false;
7919 
7920 	if (slice)
7921 		p->scx.slice = slice;
7922 	else
7923 		p->scx.slice = p->scx.slice ?: 1;
7924 
7925 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags);
7926 
7927 	return true;
7928 }
7929 
7930 /*
7931  * COMPAT: Will be removed in v6.23 along with the ___v2 suffix.
7932  */
7933 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id,
7934 				    u64 slice, u64 enq_flags,
7935 				    const struct bpf_prog_aux *aux)
7936 {
7937 	scx_bpf_dsq_insert___v2(p, dsq_id, slice, enq_flags, aux);
7938 }
7939 
7940 static bool scx_dsq_insert_vtime(struct scx_sched *sch, struct task_struct *p,
7941 				 u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
7942 {
7943 	if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags))
7944 		return false;
7945 
7946 	if (slice)
7947 		p->scx.slice = slice;
7948 	else
7949 		p->scx.slice = p->scx.slice ?: 1;
7950 
7951 	p->scx.dsq_vtime = vtime;
7952 
7953 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
7954 
7955 	return true;
7956 }
7957 
7958 struct scx_bpf_dsq_insert_vtime_args {
7959 	/* @p can't be packed together as KF_RCU is not transitive */
7960 	u64			dsq_id;
7961 	u64			slice;
7962 	u64			vtime;
7963 	u64			enq_flags;
7964 };
7965 
7966 /**
7967  * __scx_bpf_dsq_insert_vtime - Arg-wrapped vtime DSQ insertion
7968  * @p: task_struct to insert
7969  * @args: struct containing the rest of the arguments
7970  *       @args->dsq_id: DSQ to insert into
7971  *       @args->slice: duration @p can run for in nsecs, 0 to keep the current value
7972  *       @args->vtime: @p's ordering inside the vtime-sorted queue of the target DSQ
7973  *       @args->enq_flags: SCX_ENQ_*
7974  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7975  *
7976  * Wrapper kfunc that takes arguments via struct to work around BPF's 5 argument
7977  * limit. BPF programs should use scx_bpf_dsq_insert_vtime() which is provided
7978  * as an inline wrapper in common.bpf.h.
7979  *
7980  * Insert @p into the vtime priority queue of the DSQ identified by
7981  * @args->dsq_id. Tasks queued into the priority queue are ordered by
7982  * @args->vtime. All other aspects are identical to scx_bpf_dsq_insert().
7983  *
7984  * @args->vtime ordering is according to time_before64() which considers
7985  * wrapping. A numerically larger vtime may indicate an earlier position in the
7986  * ordering and vice-versa.
7987  *
7988  * A DSQ can only be used as a FIFO or priority queue at any given time and this
7989  * function must not be called on a DSQ which already has one or more FIFO tasks
7990  * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and
7991  * SCX_DSQ_GLOBAL) cannot be used as priority queues.
7992  *
7993  * Returns %true on successful insertion, %false on failure. On the root
7994  * scheduler, %false return triggers scheduler abort and the caller doesn't need
7995  * to check the return value.
7996  */
7997 __bpf_kfunc bool
7998 __scx_bpf_dsq_insert_vtime(struct task_struct *p,
7999 			   struct scx_bpf_dsq_insert_vtime_args *args,
8000 			   const struct bpf_prog_aux *aux)
8001 {
8002 	struct scx_sched *sch;
8003 
8004 	guard(rcu)();
8005 
8006 	sch = scx_prog_sched(aux);
8007 	if (unlikely(!sch))
8008 		return false;
8009 
8010 	return scx_dsq_insert_vtime(sch, p, args->dsq_id, args->slice,
8011 				    args->vtime, args->enq_flags);
8012 }
8013 
8014 /*
8015  * COMPAT: Will be removed in v6.23.
8016  */
8017 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id,
8018 					  u64 slice, u64 vtime, u64 enq_flags)
8019 {
8020 	struct scx_sched *sch;
8021 
8022 	guard(rcu)();
8023 
8024 	sch = rcu_dereference(scx_root);
8025 	if (unlikely(!sch))
8026 		return;
8027 
8028 #ifdef CONFIG_EXT_SUB_SCHED
8029 	/*
8030 	 * Disallow if any sub-scheds are attached. There is no way to tell
8031 	 * which scheduler called us, just error out @p's scheduler.
8032 	 */
8033 	if (unlikely(!list_empty(&sch->children))) {
8034 		scx_error(scx_task_sched(p), "__scx_bpf_dsq_insert_vtime() must be used");
8035 		return;
8036 	}
8037 #endif
8038 
8039 	scx_dsq_insert_vtime(sch, p, dsq_id, slice, vtime, enq_flags);
8040 }
8041 
8042 __bpf_kfunc_end_defs();
8043 
8044 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
8045 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_IMPLICIT_ARGS | KF_RCU)
8046 BTF_ID_FLAGS(func, scx_bpf_dsq_insert___v2, KF_IMPLICIT_ARGS | KF_RCU)
8047 BTF_ID_FLAGS(func, __scx_bpf_dsq_insert_vtime, KF_IMPLICIT_ARGS | KF_RCU)
8048 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU)
8049 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
8050 
8051 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
8052 	.owner			= THIS_MODULE,
8053 	.set			= &scx_kfunc_ids_enqueue_dispatch,
8054 };
8055 
8056 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit,
8057 			 struct task_struct *p, u64 dsq_id, u64 enq_flags)
8058 {
8059 	struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq;
8060 	struct scx_sched *sch = src_dsq->sched;
8061 	struct rq *this_rq, *src_rq, *locked_rq;
8062 	bool dispatched = false;
8063 	bool in_balance;
8064 	unsigned long flags;
8065 
8066 	if (!scx_kf_allowed_if_unlocked() &&
8067 	    !scx_kf_allowed(sch, SCX_KF_DISPATCH))
8068 		return false;
8069 
8070 	if (!scx_vet_enq_flags(sch, dsq_id, &enq_flags))
8071 		return false;
8072 
8073 	/*
8074 	 * If the BPF scheduler keeps calling this function repeatedly, it can
8075 	 * cause similar live-lock conditions as consume_dispatch_q().
8076 	 */
8077 	if (unlikely(READ_ONCE(sch->aborting)))
8078 		return false;
8079 
8080 	if (unlikely(!scx_task_on_sched(sch, p))) {
8081 		scx_error(sch, "scx_bpf_dsq_move[_vtime]() on %s[%d] but the task belongs to a different scheduler",
8082 			  p->comm, p->pid);
8083 	}
8084 
8085 	/*
8086 	 * Can be called from either ops.dispatch() locking this_rq() or any
8087 	 * context where no rq lock is held. If latter, lock @p's task_rq which
8088 	 * we'll likely need anyway.
8089 	 */
8090 	src_rq = task_rq(p);
8091 
8092 	local_irq_save(flags);
8093 	this_rq = this_rq();
8094 	in_balance = this_rq->scx.flags & SCX_RQ_IN_BALANCE;
8095 
8096 	if (in_balance) {
8097 		if (this_rq != src_rq) {
8098 			raw_spin_rq_unlock(this_rq);
8099 			raw_spin_rq_lock(src_rq);
8100 		}
8101 	} else {
8102 		raw_spin_rq_lock(src_rq);
8103 	}
8104 
8105 	locked_rq = src_rq;
8106 	raw_spin_lock(&src_dsq->lock);
8107 
8108 	/* did someone else get to it while we dropped the locks? */
8109 	if (nldsq_cursor_lost_task(&kit->cursor, src_rq, src_dsq, p)) {
8110 		raw_spin_unlock(&src_dsq->lock);
8111 		goto out;
8112 	}
8113 
8114 	/* @p is still on $src_dsq and stable, determine the destination */
8115 	dst_dsq = find_dsq_for_dispatch(sch, this_rq, dsq_id, task_cpu(p));
8116 
8117 	/*
8118 	 * Apply vtime and slice updates before moving so that the new time is
8119 	 * visible before inserting into $dst_dsq. @p is still on $src_dsq but
8120 	 * this is safe as we're locking it.
8121 	 */
8122 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME)
8123 		p->scx.dsq_vtime = kit->vtime;
8124 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE)
8125 		p->scx.slice = kit->slice;
8126 
8127 	/* execute move */
8128 	locked_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq);
8129 	dispatched = true;
8130 out:
8131 	if (in_balance) {
8132 		if (this_rq != locked_rq) {
8133 			raw_spin_rq_unlock(locked_rq);
8134 			raw_spin_rq_lock(this_rq);
8135 		}
8136 	} else {
8137 		raw_spin_rq_unlock_irqrestore(locked_rq, flags);
8138 	}
8139 
8140 	kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE |
8141 			       __SCX_DSQ_ITER_HAS_VTIME);
8142 	return dispatched;
8143 }
8144 
8145 __bpf_kfunc_start_defs();
8146 
8147 /**
8148  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
8149  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8150  *
8151  * Can only be called from ops.dispatch().
8152  */
8153 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(const struct bpf_prog_aux *aux)
8154 {
8155 	struct scx_sched *sch;
8156 
8157 	guard(rcu)();
8158 
8159 	sch = scx_prog_sched(aux);
8160 	if (unlikely(!sch))
8161 		return 0;
8162 
8163 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
8164 		return 0;
8165 
8166 	return sch->dsp_max_batch - __this_cpu_read(sch->pcpu->dsp_ctx.cursor);
8167 }
8168 
8169 /**
8170  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
8171  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8172  *
8173  * Cancel the latest dispatch. Can be called multiple times to cancel further
8174  * dispatches. Can only be called from ops.dispatch().
8175  */
8176 __bpf_kfunc void scx_bpf_dispatch_cancel(const struct bpf_prog_aux *aux)
8177 {
8178 	struct scx_sched *sch;
8179 	struct scx_dsp_ctx *dspc;
8180 
8181 	guard(rcu)();
8182 
8183 	sch = scx_prog_sched(aux);
8184 	if (unlikely(!sch))
8185 		return;
8186 
8187 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
8188 		return;
8189 
8190 	dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
8191 
8192 	if (dspc->cursor > 0)
8193 		dspc->cursor--;
8194 	else
8195 		scx_error(sch, "dispatch buffer underflow");
8196 }
8197 
8198 /**
8199  * scx_bpf_dsq_move_to_local - move a task from a DSQ to the current CPU's local DSQ
8200  * @dsq_id: DSQ to move task from
8201  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8202  * @enq_flags: %SCX_ENQ_*
8203  *
8204  * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's
8205  * local DSQ for execution with @enq_flags applied. Can only be called from
8206  * ops.dispatch().
8207  *
8208  * This function flushes the in-flight dispatches from scx_bpf_dsq_insert()
8209  * before trying to move from the specified DSQ. It may also grab rq locks and
8210  * thus can't be called under any BPF locks.
8211  *
8212  * Returns %true if a task has been moved, %false if there isn't any task to
8213  * move.
8214  */
8215 __bpf_kfunc bool scx_bpf_dsq_move_to_local___v2(u64 dsq_id, u64 enq_flags,
8216 						const struct bpf_prog_aux *aux)
8217 {
8218 	struct scx_dispatch_q *dsq;
8219 	struct scx_sched *sch;
8220 	struct scx_dsp_ctx *dspc;
8221 
8222 	guard(rcu)();
8223 
8224 	sch = scx_prog_sched(aux);
8225 	if (unlikely(!sch))
8226 		return false;
8227 
8228 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
8229 		return false;
8230 
8231 	if (!scx_vet_enq_flags(sch, SCX_DSQ_LOCAL, &enq_flags))
8232 		return false;
8233 
8234 	dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
8235 
8236 	flush_dispatch_buf(sch, dspc->rq);
8237 
8238 	dsq = find_user_dsq(sch, dsq_id);
8239 	if (unlikely(!dsq)) {
8240 		scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id);
8241 		return false;
8242 	}
8243 
8244 	if (consume_dispatch_q(sch, dspc->rq, dsq, enq_flags)) {
8245 		/*
8246 		 * A successfully consumed task can be dequeued before it starts
8247 		 * running while the CPU is trying to migrate other dispatched
8248 		 * tasks. Bump nr_tasks to tell balance_one() to retry on empty
8249 		 * local DSQ.
8250 		 */
8251 		dspc->nr_tasks++;
8252 		return true;
8253 	} else {
8254 		return false;
8255 	}
8256 }
8257 
8258 /*
8259  * COMPAT: ___v2 was introduced in v7.1. Remove this and ___v2 tag in the future.
8260  */
8261 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id, const struct bpf_prog_aux *aux)
8262 {
8263 	return scx_bpf_dsq_move_to_local___v2(dsq_id, 0, aux);
8264 }
8265 
8266 /**
8267  * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs
8268  * @it__iter: DSQ iterator in progress
8269  * @slice: duration the moved task can run for in nsecs
8270  *
8271  * Override the slice of the next task that will be moved from @it__iter using
8272  * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous
8273  * slice duration is kept.
8274  */
8275 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter,
8276 					    u64 slice)
8277 {
8278 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
8279 
8280 	kit->slice = slice;
8281 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE;
8282 }
8283 
8284 /**
8285  * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs
8286  * @it__iter: DSQ iterator in progress
8287  * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ
8288  *
8289  * Override the vtime of the next task that will be moved from @it__iter using
8290  * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice
8291  * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the
8292  * override is ignored and cleared.
8293  */
8294 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter,
8295 					    u64 vtime)
8296 {
8297 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
8298 
8299 	kit->vtime = vtime;
8300 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME;
8301 }
8302 
8303 /**
8304  * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ
8305  * @it__iter: DSQ iterator in progress
8306  * @p: task to transfer
8307  * @dsq_id: DSQ to move @p to
8308  * @enq_flags: SCX_ENQ_*
8309  *
8310  * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ
8311  * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can
8312  * be the destination.
8313  *
8314  * For the transfer to be successful, @p must still be on the DSQ and have been
8315  * queued before the DSQ iteration started. This function doesn't care whether
8316  * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have
8317  * been queued before the iteration started.
8318  *
8319  * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update.
8320  *
8321  * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq
8322  * lock (e.g. BPF timers or SYSCALL programs).
8323  *
8324  * Returns %true if @p has been consumed, %false if @p had already been
8325  * consumed, dequeued, or, for sub-scheds, @dsq_id points to a disallowed local
8326  * DSQ.
8327  */
8328 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter,
8329 				  struct task_struct *p, u64 dsq_id,
8330 				  u64 enq_flags)
8331 {
8332 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
8333 			    p, dsq_id, enq_flags);
8334 }
8335 
8336 /**
8337  * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ
8338  * @it__iter: DSQ iterator in progress
8339  * @p: task to transfer
8340  * @dsq_id: DSQ to move @p to
8341  * @enq_flags: SCX_ENQ_*
8342  *
8343  * Transfer @p which is on the DSQ currently iterated by @it__iter to the
8344  * priority queue of the DSQ specified by @dsq_id. The destination must be a
8345  * user DSQ as only user DSQs support priority queue.
8346  *
8347  * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice()
8348  * and scx_bpf_dsq_move_set_vtime() to update.
8349  *
8350  * All other aspects are identical to scx_bpf_dsq_move(). See
8351  * scx_bpf_dsq_insert_vtime() for more information on @vtime.
8352  */
8353 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter,
8354 					struct task_struct *p, u64 dsq_id,
8355 					u64 enq_flags)
8356 {
8357 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
8358 			    p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
8359 }
8360 
8361 #ifdef CONFIG_EXT_SUB_SCHED
8362 /**
8363  * scx_bpf_sub_dispatch - Trigger dispatching on a child scheduler
8364  * @cgroup_id: cgroup ID of the child scheduler to dispatch
8365  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8366  *
8367  * Allows a parent scheduler to trigger dispatching on one of its direct
8368  * child schedulers. The child scheduler runs its dispatch operation to
8369  * move tasks from dispatch queues to the local runqueue.
8370  *
8371  * Returns: true on success, false if cgroup_id is invalid, not a direct
8372  * child, or caller lacks dispatch permission.
8373  */
8374 __bpf_kfunc bool scx_bpf_sub_dispatch(u64 cgroup_id, const struct bpf_prog_aux *aux)
8375 {
8376 	struct rq *this_rq = this_rq();
8377 	struct scx_sched *parent, *child;
8378 
8379 	guard(rcu)();
8380 	parent = scx_prog_sched(aux);
8381 	if (unlikely(!parent))
8382 		return false;
8383 
8384 	if (!scx_kf_allowed(parent, SCX_KF_DISPATCH))
8385 		return false;
8386 
8387 	child = scx_find_sub_sched(cgroup_id);
8388 
8389 	if (unlikely(!child))
8390 		return false;
8391 
8392 	if (unlikely(scx_parent(child) != parent)) {
8393 		scx_error(parent, "trying to dispatch a distant sub-sched on cgroup %llu",
8394 			  cgroup_id);
8395 		return false;
8396 	}
8397 
8398 	return scx_dispatch_sched(child, this_rq, this_rq->scx.sub_dispatch_prev,
8399 				  true);
8400 }
8401 #endif	/* CONFIG_EXT_SUB_SCHED */
8402 
8403 __bpf_kfunc_end_defs();
8404 
8405 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
8406 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots, KF_IMPLICIT_ARGS)
8407 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel, KF_IMPLICIT_ARGS)
8408 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local, KF_IMPLICIT_ARGS)
8409 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local___v2, KF_IMPLICIT_ARGS)
8410 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
8411 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
8412 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
8413 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
8414 #ifdef CONFIG_EXT_SUB_SCHED
8415 BTF_ID_FLAGS(func, scx_bpf_sub_dispatch, KF_IMPLICIT_ARGS)
8416 #endif
8417 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
8418 
8419 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
8420 	.owner			= THIS_MODULE,
8421 	.set			= &scx_kfunc_ids_dispatch,
8422 };
8423 
8424 __bpf_kfunc_start_defs();
8425 
8426 /**
8427  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
8428  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8429  *
8430  * Iterate over all of the tasks currently enqueued on the local DSQ of the
8431  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
8432  * processed tasks. Can only be called from ops.cpu_release().
8433  */
8434 __bpf_kfunc u32 scx_bpf_reenqueue_local(const struct bpf_prog_aux *aux)
8435 {
8436 	struct scx_sched *sch;
8437 	struct rq *rq;
8438 
8439 	guard(rcu)();
8440 	sch = scx_prog_sched(aux);
8441 	if (unlikely(!sch))
8442 		return 0;
8443 
8444 	if (!scx_kf_allowed(sch, SCX_KF_CPU_RELEASE))
8445 		return 0;
8446 
8447 	rq = cpu_rq(smp_processor_id());
8448 	lockdep_assert_rq_held(rq);
8449 
8450 	return reenq_local(sch, rq, SCX_REENQ_ANY);
8451 }
8452 
8453 __bpf_kfunc_end_defs();
8454 
8455 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
8456 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local, KF_IMPLICIT_ARGS)
8457 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
8458 
8459 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
8460 	.owner			= THIS_MODULE,
8461 	.set			= &scx_kfunc_ids_cpu_release,
8462 };
8463 
8464 __bpf_kfunc_start_defs();
8465 
8466 /**
8467  * scx_bpf_create_dsq - Create a custom DSQ
8468  * @dsq_id: DSQ to create
8469  * @node: NUMA node to allocate from
8470  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8471  *
8472  * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable
8473  * scx callback, and any BPF_PROG_TYPE_SYSCALL prog.
8474  */
8475 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node, const struct bpf_prog_aux *aux)
8476 {
8477 	struct scx_dispatch_q *dsq;
8478 	struct scx_sched *sch;
8479 	s32 ret;
8480 
8481 	if (unlikely(node >= (int)nr_node_ids ||
8482 		     (node < 0 && node != NUMA_NO_NODE)))
8483 		return -EINVAL;
8484 
8485 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN))
8486 		return -EINVAL;
8487 
8488 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
8489 	if (!dsq)
8490 		return -ENOMEM;
8491 
8492 	/*
8493 	 * init_dsq() must be called in GFP_KERNEL context. Init it with NULL
8494 	 * @sch and update afterwards.
8495 	 */
8496 	ret = init_dsq(dsq, dsq_id, NULL);
8497 	if (ret) {
8498 		kfree(dsq);
8499 		return ret;
8500 	}
8501 
8502 	rcu_read_lock();
8503 
8504 	sch = scx_prog_sched(aux);
8505 	if (sch) {
8506 		dsq->sched = sch;
8507 		ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node,
8508 						    dsq_hash_params);
8509 	} else {
8510 		ret = -ENODEV;
8511 	}
8512 
8513 	rcu_read_unlock();
8514 	if (ret) {
8515 		exit_dsq(dsq);
8516 		kfree(dsq);
8517 	}
8518 	return ret;
8519 }
8520 
8521 __bpf_kfunc_end_defs();
8522 
8523 BTF_KFUNCS_START(scx_kfunc_ids_unlocked)
8524 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_IMPLICIT_ARGS | KF_SLEEPABLE)
8525 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
8526 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
8527 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
8528 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
8529 BTF_KFUNCS_END(scx_kfunc_ids_unlocked)
8530 
8531 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = {
8532 	.owner			= THIS_MODULE,
8533 	.set			= &scx_kfunc_ids_unlocked,
8534 };
8535 
8536 __bpf_kfunc_start_defs();
8537 
8538 /**
8539  * scx_bpf_task_set_slice - Set task's time slice
8540  * @p: task of interest
8541  * @slice: time slice to set in nsecs
8542  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8543  *
8544  * Set @p's time slice to @slice. Returns %true on success, %false if the
8545  * calling scheduler doesn't have authority over @p.
8546  */
8547 __bpf_kfunc bool scx_bpf_task_set_slice(struct task_struct *p, u64 slice,
8548 					const struct bpf_prog_aux *aux)
8549 {
8550 	struct scx_sched *sch;
8551 
8552 	guard(rcu)();
8553 	sch = scx_prog_sched(aux);
8554 	if (unlikely(!scx_task_on_sched(sch, p)))
8555 		return false;
8556 
8557 	p->scx.slice = slice;
8558 	return true;
8559 }
8560 
8561 /**
8562  * scx_bpf_task_set_dsq_vtime - Set task's virtual time for DSQ ordering
8563  * @p: task of interest
8564  * @vtime: virtual time to set
8565  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8566  *
8567  * Set @p's virtual time to @vtime. Returns %true on success, %false if the
8568  * calling scheduler doesn't have authority over @p.
8569  */
8570 __bpf_kfunc bool scx_bpf_task_set_dsq_vtime(struct task_struct *p, u64 vtime,
8571 					    const struct bpf_prog_aux *aux)
8572 {
8573 	struct scx_sched *sch;
8574 
8575 	guard(rcu)();
8576 	sch = scx_prog_sched(aux);
8577 	if (unlikely(!scx_task_on_sched(sch, p)))
8578 		return false;
8579 
8580 	p->scx.dsq_vtime = vtime;
8581 	return true;
8582 }
8583 
8584 static void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags)
8585 {
8586 	struct rq *this_rq;
8587 	unsigned long irq_flags;
8588 
8589 	if (!ops_cpu_valid(sch, cpu, NULL))
8590 		return;
8591 
8592 	local_irq_save(irq_flags);
8593 
8594 	this_rq = this_rq();
8595 
8596 	/*
8597 	 * While bypassing for PM ops, IRQ handling may not be online which can
8598 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
8599 	 * IRQ status update. Suppress kicking.
8600 	 */
8601 	if (scx_bypassing(sch, cpu_of(this_rq)))
8602 		goto out;
8603 
8604 	/*
8605 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
8606 	 * rq locks. We can probably be smarter and avoid bouncing if called
8607 	 * from ops which don't hold a rq lock.
8608 	 */
8609 	if (flags & SCX_KICK_IDLE) {
8610 		struct rq *target_rq = cpu_rq(cpu);
8611 
8612 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT)))
8613 			scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
8614 
8615 		if (raw_spin_rq_trylock(target_rq)) {
8616 			if (can_skip_idle_kick(target_rq)) {
8617 				raw_spin_rq_unlock(target_rq);
8618 				goto out;
8619 			}
8620 			raw_spin_rq_unlock(target_rq);
8621 		}
8622 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick_if_idle);
8623 	} else {
8624 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick);
8625 
8626 		if (flags & SCX_KICK_PREEMPT)
8627 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_preempt);
8628 		if (flags & SCX_KICK_WAIT)
8629 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_wait);
8630 	}
8631 
8632 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
8633 out:
8634 	local_irq_restore(irq_flags);
8635 }
8636 
8637 /**
8638  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
8639  * @cpu: cpu to kick
8640  * @flags: %SCX_KICK_* flags
8641  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8642  *
8643  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
8644  * trigger rescheduling on a busy CPU. This can be called from any online
8645  * scx_ops operation and the actual kicking is performed asynchronously through
8646  * an irq work.
8647  */
8648 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags, const struct bpf_prog_aux *aux)
8649 {
8650 	struct scx_sched *sch;
8651 
8652 	guard(rcu)();
8653 	sch = scx_prog_sched(aux);
8654 	if (likely(sch))
8655 		scx_kick_cpu(sch, cpu, flags);
8656 }
8657 
8658 /**
8659  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
8660  * @dsq_id: id of the DSQ
8661  *
8662  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
8663  * -%ENOENT is returned.
8664  */
8665 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id)
8666 {
8667 	struct scx_sched *sch;
8668 	struct scx_dispatch_q *dsq;
8669 	s32 ret;
8670 
8671 	preempt_disable();
8672 
8673 	sch = rcu_dereference_sched(scx_root);
8674 	if (unlikely(!sch)) {
8675 		ret = -ENODEV;
8676 		goto out;
8677 	}
8678 
8679 	if (dsq_id == SCX_DSQ_LOCAL) {
8680 		ret = READ_ONCE(this_rq()->scx.local_dsq.nr);
8681 		goto out;
8682 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
8683 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
8684 
8685 		if (ops_cpu_valid(sch, cpu, NULL)) {
8686 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
8687 			goto out;
8688 		}
8689 	} else {
8690 		dsq = find_user_dsq(sch, dsq_id);
8691 		if (dsq) {
8692 			ret = READ_ONCE(dsq->nr);
8693 			goto out;
8694 		}
8695 	}
8696 	ret = -ENOENT;
8697 out:
8698 	preempt_enable();
8699 	return ret;
8700 }
8701 
8702 /**
8703  * scx_bpf_destroy_dsq - Destroy a custom DSQ
8704  * @dsq_id: DSQ to destroy
8705  *
8706  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
8707  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
8708  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
8709  * which doesn't exist. Can be called from any online scx_ops operations.
8710  */
8711 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id)
8712 {
8713 	struct scx_sched *sch;
8714 
8715 	rcu_read_lock();
8716 	sch = rcu_dereference(scx_root);
8717 	if (sch)
8718 		destroy_dsq(sch, dsq_id);
8719 	rcu_read_unlock();
8720 }
8721 
8722 /**
8723  * bpf_iter_scx_dsq_new - Create a DSQ iterator
8724  * @it: iterator to initialize
8725  * @dsq_id: DSQ to iterate
8726  * @flags: %SCX_DSQ_ITER_*
8727  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8728  *
8729  * Initialize BPF iterator @it which can be used with bpf_for_each() to walk
8730  * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes
8731  * tasks which are already queued when this function is invoked.
8732  */
8733 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id,
8734 				     u64 flags, const struct bpf_prog_aux *aux)
8735 {
8736 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
8737 	struct scx_sched *sch;
8738 
8739 	BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) >
8740 		     sizeof(struct bpf_iter_scx_dsq));
8741 	BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) !=
8742 		     __alignof__(struct bpf_iter_scx_dsq));
8743 	BUILD_BUG_ON(__SCX_DSQ_ITER_ALL_FLAGS &
8744 		     ((1U << __SCX_DSQ_LNODE_PRIV_SHIFT) - 1));
8745 
8746 	/*
8747 	 * next() and destroy() will be called regardless of the return value.
8748 	 * Always clear $kit->dsq.
8749 	 */
8750 	kit->dsq = NULL;
8751 
8752 	sch = scx_prog_sched(aux);
8753 	if (unlikely(!sch))
8754 		return -ENODEV;
8755 
8756 	if (flags & ~__SCX_DSQ_ITER_USER_FLAGS)
8757 		return -EINVAL;
8758 
8759 	kit->dsq = find_user_dsq(sch, dsq_id);
8760 	if (!kit->dsq)
8761 		return -ENOENT;
8762 
8763 	kit->cursor = INIT_DSQ_LIST_CURSOR(kit->cursor, kit->dsq, flags);
8764 
8765 	return 0;
8766 }
8767 
8768 /**
8769  * bpf_iter_scx_dsq_next - Progress a DSQ iterator
8770  * @it: iterator to progress
8771  *
8772  * Return the next task. See bpf_iter_scx_dsq_new().
8773  */
8774 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it)
8775 {
8776 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
8777 
8778 	if (!kit->dsq)
8779 		return NULL;
8780 
8781 	guard(raw_spinlock_irqsave)(&kit->dsq->lock);
8782 
8783 	return nldsq_cursor_next_task(&kit->cursor, kit->dsq);
8784 }
8785 
8786 /**
8787  * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator
8788  * @it: iterator to destroy
8789  *
8790  * Undo scx_iter_scx_dsq_new().
8791  */
8792 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it)
8793 {
8794 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
8795 
8796 	if (!kit->dsq)
8797 		return;
8798 
8799 	if (!list_empty(&kit->cursor.node)) {
8800 		unsigned long flags;
8801 
8802 		raw_spin_lock_irqsave(&kit->dsq->lock, flags);
8803 		list_del_init(&kit->cursor.node);
8804 		raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
8805 	}
8806 	kit->dsq = NULL;
8807 }
8808 
8809 /**
8810  * scx_bpf_dsq_peek - Lockless peek at the first element.
8811  * @dsq_id: DSQ to examine.
8812  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8813  *
8814  * Read the first element in the DSQ. This is semantically equivalent to using
8815  * the DSQ iterator, but is lockfree. Of course, like any lockless operation,
8816  * this provides only a point-in-time snapshot, and the contents may change
8817  * by the time any subsequent locking operation reads the queue.
8818  *
8819  * Returns the pointer, or NULL indicates an empty queue OR internal error.
8820  */
8821 __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id,
8822 						 const struct bpf_prog_aux *aux)
8823 {
8824 	struct scx_sched *sch;
8825 	struct scx_dispatch_q *dsq;
8826 
8827 	sch = scx_prog_sched(aux);
8828 	if (unlikely(!sch))
8829 		return NULL;
8830 
8831 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) {
8832 		scx_error(sch, "peek disallowed on builtin DSQ 0x%llx", dsq_id);
8833 		return NULL;
8834 	}
8835 
8836 	dsq = find_user_dsq(sch, dsq_id);
8837 	if (unlikely(!dsq)) {
8838 		scx_error(sch, "peek on non-existent DSQ 0x%llx", dsq_id);
8839 		return NULL;
8840 	}
8841 
8842 	return rcu_dereference(dsq->first_task);
8843 }
8844 
8845 /**
8846  * scx_bpf_dsq_reenq - Re-enqueue tasks on a DSQ
8847  * @dsq_id: DSQ to re-enqueue
8848  * @reenq_flags: %SCX_RENQ_*
8849  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8850  *
8851  * Iterate over all of the tasks currently enqueued on the DSQ identified by
8852  * @dsq_id, and re-enqueue them in the BPF scheduler. The following DSQs are
8853  * supported:
8854  *
8855  * - Local DSQs (%SCX_DSQ_LOCAL or %SCX_DSQ_LOCAL_ON | $cpu)
8856  * - User DSQs
8857  *
8858  * Re-enqueues are performed asynchronously. Can be called from anywhere.
8859  */
8860 __bpf_kfunc void scx_bpf_dsq_reenq(u64 dsq_id, u64 reenq_flags,
8861 				   const struct bpf_prog_aux *aux)
8862 {
8863 	struct scx_sched *sch;
8864 	struct scx_dispatch_q *dsq;
8865 
8866 	guard(preempt)();
8867 
8868 	sch = scx_prog_sched(aux);
8869 	if (unlikely(!sch))
8870 		return;
8871 
8872 	if (unlikely(reenq_flags & ~__SCX_REENQ_USER_MASK)) {
8873 		scx_error(sch, "invalid SCX_REENQ flags 0x%llx", reenq_flags);
8874 		return;
8875 	}
8876 
8877 	/* not specifying any filter bits is the same as %SCX_REENQ_ANY */
8878 	if (!(reenq_flags & __SCX_REENQ_FILTER_MASK))
8879 		reenq_flags |= SCX_REENQ_ANY;
8880 
8881 	dsq = find_dsq_for_dispatch(sch, this_rq(), dsq_id, smp_processor_id());
8882 	schedule_dsq_reenq(sch, dsq, reenq_flags, scx_locked_rq());
8883 }
8884 
8885 /**
8886  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
8887  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8888  *
8889  * Iterate over all of the tasks currently enqueued on the local DSQ of the
8890  * caller's CPU, and re-enqueue them in the BPF scheduler. Can be called from
8891  * anywhere.
8892  *
8893  * This is now a special case of scx_bpf_dsq_reenq() and may be removed in the
8894  * future.
8895  */
8896 __bpf_kfunc void scx_bpf_reenqueue_local___v2(const struct bpf_prog_aux *aux)
8897 {
8898 	scx_bpf_dsq_reenq(SCX_DSQ_LOCAL, 0, aux);
8899 }
8900 
8901 __bpf_kfunc_end_defs();
8902 
8903 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
8904 			 size_t line_size, char *fmt, unsigned long long *data,
8905 			 u32 data__sz)
8906 {
8907 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
8908 	s32 ret;
8909 
8910 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
8911 	    (data__sz && !data)) {
8912 		scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz);
8913 		return -EINVAL;
8914 	}
8915 
8916 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
8917 	if (ret < 0) {
8918 		scx_error(sch, "failed to read data fields (%d)", ret);
8919 		return ret;
8920 	}
8921 
8922 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
8923 				  &bprintf_data);
8924 	if (ret < 0) {
8925 		scx_error(sch, "format preparation failed (%d)", ret);
8926 		return ret;
8927 	}
8928 
8929 	ret = bstr_printf(line_buf, line_size, fmt,
8930 			  bprintf_data.bin_args);
8931 	bpf_bprintf_cleanup(&bprintf_data);
8932 	if (ret < 0) {
8933 		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
8934 		return ret;
8935 	}
8936 
8937 	return ret;
8938 }
8939 
8940 static s32 bstr_format(struct scx_sched *sch, struct scx_bstr_buf *buf,
8941 		       char *fmt, unsigned long long *data, u32 data__sz)
8942 {
8943 	return __bstr_format(sch, buf->data, buf->line, sizeof(buf->line),
8944 			     fmt, data, data__sz);
8945 }
8946 
8947 __bpf_kfunc_start_defs();
8948 
8949 /**
8950  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
8951  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
8952  * @fmt: error message format string
8953  * @data: format string parameters packaged using ___bpf_fill() macro
8954  * @data__sz: @data len, must end in '__sz' for the verifier
8955  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8956  *
8957  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
8958  * disabling.
8959  */
8960 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
8961 				   unsigned long long *data, u32 data__sz,
8962 				   const struct bpf_prog_aux *aux)
8963 {
8964 	struct scx_sched *sch;
8965 	unsigned long flags;
8966 
8967 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
8968 	sch = scx_prog_sched(aux);
8969 	if (likely(sch) &&
8970 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
8971 		scx_exit(sch, SCX_EXIT_UNREG_BPF, exit_code, "%s", scx_exit_bstr_buf.line);
8972 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
8973 }
8974 
8975 /**
8976  * scx_bpf_error_bstr - Indicate fatal error
8977  * @fmt: error message format string
8978  * @data: format string parameters packaged using ___bpf_fill() macro
8979  * @data__sz: @data len, must end in '__sz' for the verifier
8980  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8981  *
8982  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
8983  * disabling.
8984  */
8985 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
8986 				    u32 data__sz, const struct bpf_prog_aux *aux)
8987 {
8988 	struct scx_sched *sch;
8989 	unsigned long flags;
8990 
8991 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
8992 	sch = scx_prog_sched(aux);
8993 	if (likely(sch) &&
8994 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
8995 		scx_exit(sch, SCX_EXIT_ERROR_BPF, 0, "%s", scx_exit_bstr_buf.line);
8996 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
8997 }
8998 
8999 /**
9000  * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler
9001  * @fmt: format string
9002  * @data: format string parameters packaged using ___bpf_fill() macro
9003  * @data__sz: @data len, must end in '__sz' for the verifier
9004  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9005  *
9006  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
9007  * dump_task() to generate extra debug dump specific to the BPF scheduler.
9008  *
9009  * The extra dump may be multiple lines. A single line may be split over
9010  * multiple calls. The last line is automatically terminated.
9011  */
9012 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
9013 				   u32 data__sz, const struct bpf_prog_aux *aux)
9014 {
9015 	struct scx_sched *sch;
9016 	struct scx_dump_data *dd = &scx_dump_data;
9017 	struct scx_bstr_buf *buf = &dd->buf;
9018 	s32 ret;
9019 
9020 	guard(rcu)();
9021 
9022 	sch = scx_prog_sched(aux);
9023 	if (unlikely(!sch))
9024 		return;
9025 
9026 	if (raw_smp_processor_id() != dd->cpu) {
9027 		scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends");
9028 		return;
9029 	}
9030 
9031 	/* append the formatted string to the line buf */
9032 	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
9033 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
9034 	if (ret < 0) {
9035 		dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
9036 			  dd->prefix, fmt, data, data__sz, ret);
9037 		return;
9038 	}
9039 
9040 	dd->cursor += ret;
9041 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
9042 
9043 	if (!dd->cursor)
9044 		return;
9045 
9046 	/*
9047 	 * If the line buf overflowed or ends in a newline, flush it into the
9048 	 * dump. This is to allow the caller to generate a single line over
9049 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
9050 	 * the line buf, the only case which can lead to an unexpected
9051 	 * truncation is when the caller keeps generating newlines in the middle
9052 	 * instead of the end consecutively. Don't do that.
9053 	 */
9054 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
9055 		ops_dump_flush();
9056 }
9057 
9058 /**
9059  * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU
9060  * @cpu: CPU of interest
9061  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9062  *
9063  * Return the maximum relative capacity of @cpu in relation to the most
9064  * performant CPU in the system. The return value is in the range [1,
9065  * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur().
9066  */
9067 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu, const struct bpf_prog_aux *aux)
9068 {
9069 	struct scx_sched *sch;
9070 
9071 	guard(rcu)();
9072 
9073 	sch = scx_prog_sched(aux);
9074 	if (likely(sch) && ops_cpu_valid(sch, cpu, NULL))
9075 		return arch_scale_cpu_capacity(cpu);
9076 	else
9077 		return SCX_CPUPERF_ONE;
9078 }
9079 
9080 /**
9081  * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU
9082  * @cpu: CPU of interest
9083  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9084  *
9085  * Return the current relative performance of @cpu in relation to its maximum.
9086  * The return value is in the range [1, %SCX_CPUPERF_ONE].
9087  *
9088  * The current performance level of a CPU in relation to the maximum performance
9089  * available in the system can be calculated as follows:
9090  *
9091  *   scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE
9092  *
9093  * The result is in the range [1, %SCX_CPUPERF_ONE].
9094  */
9095 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu, const struct bpf_prog_aux *aux)
9096 {
9097 	struct scx_sched *sch;
9098 
9099 	guard(rcu)();
9100 
9101 	sch = scx_prog_sched(aux);
9102 	if (likely(sch) && ops_cpu_valid(sch, cpu, NULL))
9103 		return arch_scale_freq_capacity(cpu);
9104 	else
9105 		return SCX_CPUPERF_ONE;
9106 }
9107 
9108 /**
9109  * scx_bpf_cpuperf_set - Set the relative performance target of a CPU
9110  * @cpu: CPU of interest
9111  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
9112  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9113  *
9114  * Set the target performance level of @cpu to @perf. @perf is in linear
9115  * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the
9116  * schedutil cpufreq governor chooses the target frequency.
9117  *
9118  * The actual performance level chosen, CPU grouping, and the overhead and
9119  * latency of the operations are dependent on the hardware and cpufreq driver in
9120  * use. Consult hardware and cpufreq documentation for more information. The
9121  * current performance level can be monitored using scx_bpf_cpuperf_cur().
9122  */
9123 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf, const struct bpf_prog_aux *aux)
9124 {
9125 	struct scx_sched *sch;
9126 
9127 	guard(rcu)();
9128 
9129 	sch = scx_prog_sched(aux);
9130 	if (unlikely(!sch))
9131 		return;
9132 
9133 	if (unlikely(perf > SCX_CPUPERF_ONE)) {
9134 		scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu);
9135 		return;
9136 	}
9137 
9138 	if (ops_cpu_valid(sch, cpu, NULL)) {
9139 		struct rq *rq = cpu_rq(cpu), *locked_rq = scx_locked_rq();
9140 		struct rq_flags rf;
9141 
9142 		/*
9143 		 * When called with an rq lock held, restrict the operation
9144 		 * to the corresponding CPU to prevent ABBA deadlocks.
9145 		 */
9146 		if (locked_rq && rq != locked_rq) {
9147 			scx_error(sch, "Invalid target CPU %d", cpu);
9148 			return;
9149 		}
9150 
9151 		/*
9152 		 * If no rq lock is held, allow to operate on any CPU by
9153 		 * acquiring the corresponding rq lock.
9154 		 */
9155 		if (!locked_rq) {
9156 			rq_lock_irqsave(rq, &rf);
9157 			update_rq_clock(rq);
9158 		}
9159 
9160 		rq->scx.cpuperf_target = perf;
9161 		cpufreq_update_util(rq, 0);
9162 
9163 		if (!locked_rq)
9164 			rq_unlock_irqrestore(rq, &rf);
9165 	}
9166 }
9167 
9168 /**
9169  * scx_bpf_nr_node_ids - Return the number of possible node IDs
9170  *
9171  * All valid node IDs in the system are smaller than the returned value.
9172  */
9173 __bpf_kfunc u32 scx_bpf_nr_node_ids(void)
9174 {
9175 	return nr_node_ids;
9176 }
9177 
9178 /**
9179  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
9180  *
9181  * All valid CPU IDs in the system are smaller than the returned value.
9182  */
9183 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
9184 {
9185 	return nr_cpu_ids;
9186 }
9187 
9188 /**
9189  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
9190  */
9191 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
9192 {
9193 	return cpu_possible_mask;
9194 }
9195 
9196 /**
9197  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
9198  */
9199 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
9200 {
9201 	return cpu_online_mask;
9202 }
9203 
9204 /**
9205  * scx_bpf_put_cpumask - Release a possible/online cpumask
9206  * @cpumask: cpumask to release
9207  */
9208 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
9209 {
9210 	/*
9211 	 * Empty function body because we aren't actually acquiring or releasing
9212 	 * a reference to a global cpumask, which is read-only in the caller and
9213 	 * is never released. The acquire / release semantics here are just used
9214 	 * to make the cpumask is a trusted pointer in the caller.
9215 	 */
9216 }
9217 
9218 /**
9219  * scx_bpf_task_running - Is task currently running?
9220  * @p: task of interest
9221  */
9222 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
9223 {
9224 	return task_rq(p)->curr == p;
9225 }
9226 
9227 /**
9228  * scx_bpf_task_cpu - CPU a task is currently associated with
9229  * @p: task of interest
9230  */
9231 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
9232 {
9233 	return task_cpu(p);
9234 }
9235 
9236 /**
9237  * scx_bpf_cpu_rq - Fetch the rq of a CPU
9238  * @cpu: CPU of the rq
9239  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9240  */
9241 __bpf_kfunc struct rq *scx_bpf_cpu_rq(s32 cpu, const struct bpf_prog_aux *aux)
9242 {
9243 	struct scx_sched *sch;
9244 
9245 	guard(rcu)();
9246 
9247 	sch = scx_prog_sched(aux);
9248 	if (unlikely(!sch))
9249 		return NULL;
9250 
9251 	if (!ops_cpu_valid(sch, cpu, NULL))
9252 		return NULL;
9253 
9254 	if (!sch->warned_deprecated_rq) {
9255 		printk_deferred(KERN_WARNING "sched_ext: %s() is deprecated; "
9256 				"use scx_bpf_locked_rq() when holding rq lock "
9257 				"or scx_bpf_cpu_curr() to read remote curr safely.\n", __func__);
9258 		sch->warned_deprecated_rq = true;
9259 	}
9260 
9261 	return cpu_rq(cpu);
9262 }
9263 
9264 /**
9265  * scx_bpf_locked_rq - Return the rq currently locked by SCX
9266  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9267  *
9268  * Returns the rq if a rq lock is currently held by SCX.
9269  * Otherwise emits an error and returns NULL.
9270  */
9271 __bpf_kfunc struct rq *scx_bpf_locked_rq(const struct bpf_prog_aux *aux)
9272 {
9273 	struct scx_sched *sch;
9274 	struct rq *rq;
9275 
9276 	guard(preempt)();
9277 
9278 	sch = scx_prog_sched(aux);
9279 	if (unlikely(!sch))
9280 		return NULL;
9281 
9282 	rq = scx_locked_rq();
9283 	if (!rq) {
9284 		scx_error(sch, "accessing rq without holding rq lock");
9285 		return NULL;
9286 	}
9287 
9288 	return rq;
9289 }
9290 
9291 /**
9292  * scx_bpf_cpu_curr - Return remote CPU's curr task
9293  * @cpu: CPU of interest
9294  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9295  *
9296  * Callers must hold RCU read lock (KF_RCU).
9297  */
9298 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_aux *aux)
9299 {
9300 	struct scx_sched *sch;
9301 
9302 	guard(rcu)();
9303 
9304 	sch = scx_prog_sched(aux);
9305 	if (unlikely(!sch))
9306 		return NULL;
9307 
9308 	if (!ops_cpu_valid(sch, cpu, NULL))
9309 		return NULL;
9310 
9311 	return rcu_dereference(cpu_rq(cpu)->curr);
9312 }
9313 
9314 /**
9315  * scx_bpf_now - Returns a high-performance monotonically non-decreasing
9316  * clock for the current CPU. The clock returned is in nanoseconds.
9317  *
9318  * It provides the following properties:
9319  *
9320  * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently
9321  *  to account for execution time and track tasks' runtime properties.
9322  *  Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which
9323  *  eventually reads a hardware timestamp counter -- is neither performant nor
9324  *  scalable. scx_bpf_now() aims to provide a high-performance clock by
9325  *  using the rq clock in the scheduler core whenever possible.
9326  *
9327  * 2) High enough resolution for the BPF scheduler use cases: In most BPF
9328  *  scheduler use cases, the required clock resolution is lower than the most
9329  *  accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically
9330  *  uses the rq clock in the scheduler core whenever it is valid. It considers
9331  *  that the rq clock is valid from the time the rq clock is updated
9332  *  (update_rq_clock) until the rq is unlocked (rq_unpin_lock).
9333  *
9334  * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now()
9335  *  guarantees the clock never goes backward when comparing them in the same
9336  *  CPU. On the other hand, when comparing clocks in different CPUs, there
9337  *  is no such guarantee -- the clock can go backward. It provides a
9338  *  monotonically *non-decreasing* clock so that it would provide the same
9339  *  clock values in two different scx_bpf_now() calls in the same CPU
9340  *  during the same period of when the rq clock is valid.
9341  */
9342 __bpf_kfunc u64 scx_bpf_now(void)
9343 {
9344 	struct rq *rq;
9345 	u64 clock;
9346 
9347 	preempt_disable();
9348 
9349 	rq = this_rq();
9350 	if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) {
9351 		/*
9352 		 * If the rq clock is valid, use the cached rq clock.
9353 		 *
9354 		 * Note that scx_bpf_now() is re-entrant between a process
9355 		 * context and an interrupt context (e.g., timer interrupt).
9356 		 * However, we don't need to consider the race between them
9357 		 * because such race is not observable from a caller.
9358 		 */
9359 		clock = READ_ONCE(rq->scx.clock);
9360 	} else {
9361 		/*
9362 		 * Otherwise, return a fresh rq clock.
9363 		 *
9364 		 * The rq clock is updated outside of the rq lock.
9365 		 * In this case, keep the updated rq clock invalid so the next
9366 		 * kfunc call outside the rq lock gets a fresh rq clock.
9367 		 */
9368 		clock = sched_clock_cpu(cpu_of(rq));
9369 	}
9370 
9371 	preempt_enable();
9372 
9373 	return clock;
9374 }
9375 
9376 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events)
9377 {
9378 	struct scx_event_stats *e_cpu;
9379 	int cpu;
9380 
9381 	/* Aggregate per-CPU event counters into @events. */
9382 	memset(events, 0, sizeof(*events));
9383 	for_each_possible_cpu(cpu) {
9384 		e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats;
9385 		scx_agg_event(events, e_cpu, SCX_EV_SELECT_CPU_FALLBACK);
9386 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
9387 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_KEEP_LAST);
9388 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_EXITING);
9389 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
9390 		scx_agg_event(events, e_cpu, SCX_EV_REENQ_IMMED);
9391 		scx_agg_event(events, e_cpu, SCX_EV_REENQ_LOCAL_REPEAT);
9392 		scx_agg_event(events, e_cpu, SCX_EV_REFILL_SLICE_DFL);
9393 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DURATION);
9394 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DISPATCH);
9395 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_ACTIVATE);
9396 		scx_agg_event(events, e_cpu, SCX_EV_INSERT_NOT_OWNED);
9397 	}
9398 }
9399 
9400 /*
9401  * scx_bpf_events - Get a system-wide event counter to
9402  * @events: output buffer from a BPF program
9403  * @events__sz: @events len, must end in '__sz'' for the verifier
9404  */
9405 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events,
9406 				size_t events__sz)
9407 {
9408 	struct scx_sched *sch;
9409 	struct scx_event_stats e_sys;
9410 
9411 	rcu_read_lock();
9412 	sch = rcu_dereference(scx_root);
9413 	if (sch)
9414 		scx_read_events(sch, &e_sys);
9415 	else
9416 		memset(&e_sys, 0, sizeof(e_sys));
9417 	rcu_read_unlock();
9418 
9419 	/*
9420 	 * We cannot entirely trust a BPF-provided size since a BPF program
9421 	 * might be compiled against a different vmlinux.h, of which
9422 	 * scx_event_stats would be larger (a newer vmlinux.h) or smaller
9423 	 * (an older vmlinux.h). Hence, we use the smaller size to avoid
9424 	 * memory corruption.
9425 	 */
9426 	events__sz = min(events__sz, sizeof(*events));
9427 	memcpy(events, &e_sys, events__sz);
9428 }
9429 
9430 #ifdef CONFIG_CGROUP_SCHED
9431 /**
9432  * scx_bpf_task_cgroup - Return the sched cgroup of a task
9433  * @p: task of interest
9434  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9435  *
9436  * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with
9437  * from the scheduler's POV. SCX operations should use this function to
9438  * determine @p's current cgroup as, unlike following @p->cgroups,
9439  * @p->sched_task_group is protected by @p's rq lock and thus atomic w.r.t. all
9440  * rq-locked operations. Can be called on the parameter tasks of rq-locked
9441  * operations. The restriction guarantees that @p's rq is locked by the caller.
9442  */
9443 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p,
9444 					       const struct bpf_prog_aux *aux)
9445 {
9446 	struct task_group *tg = p->sched_task_group;
9447 	struct cgroup *cgrp = &cgrp_dfl_root.cgrp;
9448 	struct scx_sched *sch;
9449 
9450 	guard(rcu)();
9451 
9452 	sch = scx_prog_sched(aux);
9453 	if (unlikely(!sch))
9454 		goto out;
9455 
9456 	if (!scx_kf_allowed_on_arg_tasks(sch, __SCX_KF_RQ_LOCKED, p))
9457 		goto out;
9458 
9459 	cgrp = tg_cgrp(tg);
9460 
9461 out:
9462 	cgroup_get(cgrp);
9463 	return cgrp;
9464 }
9465 #endif	/* CONFIG_CGROUP_SCHED */
9466 
9467 __bpf_kfunc_end_defs();
9468 
9469 BTF_KFUNCS_START(scx_kfunc_ids_any)
9470 BTF_ID_FLAGS(func, scx_bpf_task_set_slice, KF_IMPLICIT_ARGS | KF_RCU);
9471 BTF_ID_FLAGS(func, scx_bpf_task_set_dsq_vtime, KF_IMPLICIT_ARGS | KF_RCU);
9472 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
9473 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued)
9474 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq)
9475 BTF_ID_FLAGS(func, scx_bpf_dsq_peek, KF_IMPLICIT_ARGS | KF_RCU_PROTECTED | KF_RET_NULL)
9476 BTF_ID_FLAGS(func, scx_bpf_dsq_reenq, KF_IMPLICIT_ARGS)
9477 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local___v2, KF_IMPLICIT_ARGS)
9478 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_IMPLICIT_ARGS | KF_ITER_NEW | KF_RCU_PROTECTED)
9479 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
9480 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
9481 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_IMPLICIT_ARGS)
9482 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_IMPLICIT_ARGS)
9483 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_IMPLICIT_ARGS)
9484 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS)
9485 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS)
9486 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
9487 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
9488 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
9489 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
9490 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
9491 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
9492 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
9493 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
9494 BTF_ID_FLAGS(func, scx_bpf_cpu_rq, KF_IMPLICIT_ARGS)
9495 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL)
9496 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
9497 BTF_ID_FLAGS(func, scx_bpf_now)
9498 BTF_ID_FLAGS(func, scx_bpf_events)
9499 #ifdef CONFIG_CGROUP_SCHED
9500 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_IMPLICIT_ARGS | KF_RCU | KF_ACQUIRE)
9501 #endif
9502 BTF_KFUNCS_END(scx_kfunc_ids_any)
9503 
9504 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
9505 	.owner			= THIS_MODULE,
9506 	.set			= &scx_kfunc_ids_any,
9507 };
9508 
9509 static int __init scx_init(void)
9510 {
9511 	int ret;
9512 
9513 	/*
9514 	 * kfunc registration can't be done from init_sched_ext_class() as
9515 	 * register_btf_kfunc_id_set() needs most of the system to be up.
9516 	 *
9517 	 * Some kfuncs are context-sensitive and can only be called from
9518 	 * specific SCX ops. They are grouped into BTF sets accordingly.
9519 	 * Unfortunately, BPF currently doesn't have a way of enforcing such
9520 	 * restrictions. Eventually, the verifier should be able to enforce
9521 	 * them. For now, register them the same and make each kfunc explicitly
9522 	 * check using scx_kf_allowed().
9523 	 */
9524 	if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
9525 					     &scx_kfunc_set_enqueue_dispatch)) ||
9526 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
9527 					     &scx_kfunc_set_dispatch)) ||
9528 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
9529 					     &scx_kfunc_set_cpu_release)) ||
9530 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
9531 					     &scx_kfunc_set_unlocked)) ||
9532 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
9533 					     &scx_kfunc_set_unlocked)) ||
9534 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
9535 					     &scx_kfunc_set_any)) ||
9536 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
9537 					     &scx_kfunc_set_any)) ||
9538 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
9539 					     &scx_kfunc_set_any))) {
9540 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
9541 		return ret;
9542 	}
9543 
9544 	ret = scx_idle_init();
9545 	if (ret) {
9546 		pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret);
9547 		return ret;
9548 	}
9549 
9550 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops);
9551 	if (ret) {
9552 		pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret);
9553 		return ret;
9554 	}
9555 
9556 	ret = register_pm_notifier(&scx_pm_notifier);
9557 	if (ret) {
9558 		pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret);
9559 		return ret;
9560 	}
9561 
9562 	scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj);
9563 	if (!scx_kset) {
9564 		pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n");
9565 		return -ENOMEM;
9566 	}
9567 
9568 	ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group);
9569 	if (ret < 0) {
9570 		pr_err("sched_ext: Failed to add global attributes\n");
9571 		return ret;
9572 	}
9573 
9574 	if (!alloc_cpumask_var(&scx_bypass_lb_donee_cpumask, GFP_KERNEL) ||
9575 	    !alloc_cpumask_var(&scx_bypass_lb_resched_cpumask, GFP_KERNEL)) {
9576 		pr_err("sched_ext: Failed to allocate cpumasks\n");
9577 		return -ENOMEM;
9578 	}
9579 
9580 	return 0;
9581 }
9582 __initcall(scx_init);
9583