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