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