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