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