xref: /linux/kernel/sched/ext/ext.c (revision 85cdaca6970028bf6f544c355c90035586836ddf)
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 /*
2778  * One user of this function is scx_bpf_dispatch() which can be called
2779  * recursively as sub-sched dispatches nest. Always inline to reduce stack usage
2780  * from the call frame.
2781  */
2782 static __always_inline bool
2783 scx_dispatch_sched(struct scx_sched *sch, struct rq *rq,
2784 		   struct task_struct *prev, bool nested)
2785 {
2786 	struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
2787 	int nr_loops = SCX_DSP_MAX_LOOPS;
2788 	s32 cpu = cpu_of(rq);
2789 	bool prev_on_sch = (prev->sched_class == &ext_sched_class) &&
2790 		scx_task_on_sched(sch, prev);
2791 
2792 	if (consume_global_dsq(sch, rq))
2793 		return true;
2794 
2795 	if (bypass_dsp_enabled(sch)) {
2796 		/* if @sch is bypassing, only the bypass DSQs are active */
2797 		if (scx_bypassing(sch, cpu))
2798 			return consume_dispatch_q(sch, rq, bypass_dsq(sch, cpu), 0);
2799 
2800 #ifdef CONFIG_EXT_SUB_SCHED
2801 		/*
2802 		 * If @sch isn't bypassing but its children are, @sch is
2803 		 * responsible for making forward progress for both its own
2804 		 * tasks that aren't bypassing and the bypassing descendants'
2805 		 * tasks. The following implements a simple built-in behavior -
2806 		 * let each CPU try to run the bypass DSQ every Nth time.
2807 		 *
2808 		 * Later, if necessary, we can add an ops flag to suppress the
2809 		 * auto-consumption and a kfunc to consume the bypass DSQ and,
2810 		 * so that the BPF scheduler can fully control scheduling of
2811 		 * bypassed tasks.
2812 		 */
2813 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
2814 
2815 		if (!(pcpu->bypass_host_seq++ % SCX_BYPASS_HOST_NTH) &&
2816 		    consume_dispatch_q(sch, rq, bypass_dsq(sch, cpu), 0)) {
2817 			__scx_add_event(sch, SCX_EV_SUB_BYPASS_DISPATCH, 1);
2818 			return true;
2819 		}
2820 #endif	/* CONFIG_EXT_SUB_SCHED */
2821 	}
2822 
2823 	if (unlikely(!SCX_HAS_OP(sch, dispatch)) || !scx_rq_online(rq))
2824 		return false;
2825 
2826 	dspc->rq = rq;
2827 
2828 	/*
2829 	 * The dispatch loop. Because flush_dispatch_buf() may drop the rq lock,
2830 	 * the local DSQ might still end up empty after a successful
2831 	 * ops.dispatch(). If the local DSQ is empty even after ops.dispatch()
2832 	 * produced some tasks, retry. The BPF scheduler may depend on this
2833 	 * looping behavior to simplify its implementation.
2834 	 */
2835 	do {
2836 		dspc->nr_tasks = 0;
2837 
2838 		if (nested) {
2839 			SCX_CALL_OP(sch, dispatch, rq, scx_cpu_arg(cpu),
2840 				    prev_on_sch ? prev : NULL);
2841 		} else {
2842 			/* stash @prev so that nested invocations can access it */
2843 			rq->scx.sub_dispatch_prev = prev;
2844 			SCX_CALL_OP(sch, dispatch, rq, scx_cpu_arg(cpu),
2845 				    prev_on_sch ? prev : NULL);
2846 			rq->scx.sub_dispatch_prev = NULL;
2847 		}
2848 
2849 		flush_dispatch_buf(sch, rq);
2850 
2851 		if ((prev->scx.flags & SCX_TASK_QUEUED) && prev->scx.slice) {
2852 			rq->scx.flags |= SCX_RQ_BAL_KEEP;
2853 			return true;
2854 		}
2855 		if (rq->scx.local_dsq.nr)
2856 			return true;
2857 		if (consume_global_dsq(sch, rq))
2858 			return true;
2859 
2860 		/*
2861 		 * ops.dispatch() can trap us in this loop by repeatedly
2862 		 * dispatching ineligible tasks. Break out once in a while to
2863 		 * allow the watchdog to run. As IRQ can't be enabled in
2864 		 * balance(), we want to complete this scheduling cycle and then
2865 		 * start a new one. IOW, we want to call resched_curr() on the
2866 		 * next, most likely idle, task, not the current one. Use
2867 		 * __scx_bpf_kick_cpu() for deferred kicking.
2868 		 */
2869 		if (unlikely(!--nr_loops)) {
2870 			scx_kick_cpu(sch, cpu, 0);
2871 			break;
2872 		}
2873 	} while (dspc->nr_tasks);
2874 
2875 	/*
2876 	 * Prevent the CPU from going idle while bypassed descendants have tasks
2877 	 * queued. Without this fallback, bypassed tasks could stall if the host
2878 	 * scheduler's ops.dispatch() doesn't yield any tasks.
2879 	 */
2880 	if (bypass_dsp_enabled(sch))
2881 		return consume_dispatch_q(sch, rq, bypass_dsq(sch, cpu), 0);
2882 
2883 	return false;
2884 }
2885 
2886 static int balance_one(struct rq *rq, struct task_struct *prev)
2887 {
2888 	struct scx_sched *sch = scx_root;
2889 	s32 cpu = cpu_of(rq);
2890 
2891 	lockdep_assert_rq_held(rq);
2892 	rq->scx.flags |= SCX_RQ_IN_BALANCE;
2893 	rq->scx.flags &= ~SCX_RQ_BAL_KEEP;
2894 
2895 	if ((sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) &&
2896 	    unlikely(rq->scx.cpu_released)) {
2897 		/*
2898 		 * If the previous sched_class for the current CPU was not SCX,
2899 		 * notify the BPF scheduler that it again has control of the
2900 		 * core. This callback complements ->cpu_release(), which is
2901 		 * emitted in switch_class().
2902 		 */
2903 		if (sch->ops.cpu_acquire)
2904 			SCX_CALL_OP(sch, cpu_acquire, rq, cpu, NULL);
2905 		rq->scx.cpu_released = false;
2906 	}
2907 
2908 	if (prev->sched_class == &ext_sched_class) {
2909 		update_curr_scx(rq);
2910 
2911 		/*
2912 		 * If @prev is runnable & has slice left, it has priority and
2913 		 * fetching more just increases latency for the fetched tasks.
2914 		 * Tell pick_task_scx() to keep running @prev. If the BPF
2915 		 * scheduler wants to handle this explicitly, it should
2916 		 * implement ->cpu_release().
2917 		 *
2918 		 * See scx_disable_workfn() for the explanation on the bypassing
2919 		 * test.
2920 		 */
2921 		if ((prev->scx.flags & SCX_TASK_QUEUED) && prev->scx.slice &&
2922 		    !scx_bypassing(sch, cpu)) {
2923 			rq->scx.flags |= SCX_RQ_BAL_KEEP;
2924 			goto has_tasks;
2925 		}
2926 	}
2927 
2928 	/* if there already are tasks to run, nothing to do */
2929 	if (rq->scx.local_dsq.nr)
2930 		goto has_tasks;
2931 
2932 	if (scx_dispatch_sched(sch, rq, prev, false))
2933 		goto has_tasks;
2934 
2935 	/*
2936 	 * Didn't find another task to run. Keep running @prev unless
2937 	 * %SCX_OPS_ENQ_LAST is in effect.
2938 	 */
2939 	if ((prev->scx.flags & SCX_TASK_QUEUED) &&
2940 	    (!(sch->ops.flags & SCX_OPS_ENQ_LAST) || scx_bypassing(sch, cpu))) {
2941 		rq->scx.flags |= SCX_RQ_BAL_KEEP;
2942 		__scx_add_event(sch, SCX_EV_DISPATCH_KEEP_LAST, 1);
2943 		goto has_tasks;
2944 	}
2945 	rq->scx.flags &= ~SCX_RQ_IN_BALANCE;
2946 	return false;
2947 
2948 has_tasks:
2949 	/*
2950 	 * @rq may have extra IMMED tasks without reenq scheduled:
2951 	 *
2952 	 * - rq_is_open() can't reliably tell when and how slice is going to be
2953 	 *   modified for $curr and allows IMMED tasks to be queued while
2954 	 *   dispatch is in progress.
2955 	 *
2956 	 * - A non-IMMED HEAD task can get queued in front of an IMMED task
2957 	 *   between the IMMED queueing and the subsequent scheduling event.
2958 	 */
2959 	if (unlikely(rq->scx.local_dsq.nr > 1 && rq->scx.nr_immed))
2960 		schedule_reenq_local(rq, 0);
2961 
2962 	rq->scx.flags &= ~SCX_RQ_IN_BALANCE;
2963 	return true;
2964 }
2965 
2966 static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first)
2967 {
2968 	struct scx_sched *sch = scx_task_sched(p);
2969 
2970 	if (p->scx.flags & SCX_TASK_QUEUED) {
2971 		/*
2972 		 * Core-sched might decide to execute @p before it is
2973 		 * dispatched. Call ops_dequeue() to notify the BPF scheduler.
2974 		 */
2975 		ops_dequeue(rq, p, SCX_DEQ_CORE_SCHED_EXEC);
2976 		dispatch_dequeue(rq, p);
2977 	}
2978 
2979 	p->se.exec_start = rq_clock_task(rq);
2980 
2981 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2982 	if (SCX_HAS_OP(sch, running) && (p->scx.flags & SCX_TASK_QUEUED))
2983 		SCX_CALL_OP_TASK(sch, running, rq, p);
2984 
2985 	clr_task_runnable(p, true);
2986 
2987 	/*
2988 	 * @p is getting newly scheduled or got kicked after someone updated its
2989 	 * slice. Update SCX_RQ_CAN_STOP_TICK to reflect whether the tick can be
2990 	 * stopped. See scx_can_stop_tick().
2991 	 *
2992 	 * Moreover, refresh the load_avgs just when transitioning in and out of
2993 	 * nohz. In the future, we might want to add a mechanism to update
2994 	 * load_avgs periodically on tick-stopped CPUs.
2995 	 */
2996 	if (p->scx.slice == SCX_SLICE_INF) {
2997 		if (!(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) {
2998 			/*
2999 			 * Bypass mode always assigns finite slices, so @p
3000 			 * can't have an infinite slice while bypassing.
3001 			 * Therefore, sched_update_tick_dependency() can safely
3002 			 * evaluate the outgoing task.
3003 			 */
3004 			rq->scx.flags |= SCX_RQ_CAN_STOP_TICK;
3005 			sched_update_tick_dependency(rq);
3006 
3007 			update_other_load_avgs(rq);
3008 		}
3009 	} else {
3010 		if (rq->scx.flags & SCX_RQ_CAN_STOP_TICK) {
3011 			rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK;
3012 			update_other_load_avgs(rq);
3013 		}
3014 
3015 		/*
3016 		 * @rq still references the outgoing scheduling context. A finite
3017 		 * slice is sufficient by itself to require the tick.
3018 		 */
3019 		if (tick_nohz_full_cpu(cpu_of(rq)))
3020 			tick_nohz_dep_set_cpu(cpu_of(rq), TICK_DEP_BIT_SCHED);
3021 	}
3022 }
3023 
3024 static enum scx_cpu_preempt_reason
3025 preempt_reason_from_class(const struct sched_class *class)
3026 {
3027 	if (class == &stop_sched_class)
3028 		return SCX_CPU_PREEMPT_STOP;
3029 	if (class == &dl_sched_class)
3030 		return SCX_CPU_PREEMPT_DL;
3031 	if (class == &rt_sched_class)
3032 		return SCX_CPU_PREEMPT_RT;
3033 	return SCX_CPU_PREEMPT_UNKNOWN;
3034 }
3035 
3036 static void switch_class(struct rq *rq, struct task_struct *next)
3037 {
3038 	struct scx_sched *sch = scx_root;
3039 	const struct sched_class *next_class = next->sched_class;
3040 
3041 	if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT))
3042 		return;
3043 
3044 	/*
3045 	 * The callback is conceptually meant to convey that the CPU is no
3046 	 * longer under the control of SCX. Therefore, don't invoke the callback
3047 	 * if the next class is below SCX (in which case the BPF scheduler has
3048 	 * actively decided not to schedule any tasks on the CPU).
3049 	 */
3050 	if (sched_class_above(&ext_sched_class, next_class))
3051 		return;
3052 
3053 	/*
3054 	 * At this point we know that SCX was preempted by a higher priority
3055 	 * sched_class, so invoke the ->cpu_release() callback if we have not
3056 	 * done so already. We only send the callback once between SCX being
3057 	 * preempted, and it regaining control of the CPU.
3058 	 *
3059 	 * ->cpu_release() complements ->cpu_acquire(), which is emitted the
3060 	 *  next time that balance_one() is invoked.
3061 	 */
3062 	if (!rq->scx.cpu_released) {
3063 		if (sch->ops.cpu_release) {
3064 			struct scx_cpu_release_args args = {
3065 				.reason = preempt_reason_from_class(next_class),
3066 				.task = next,
3067 			};
3068 
3069 			SCX_CALL_OP(sch, cpu_release, rq, cpu_of(rq), &args);
3070 		}
3071 		rq->scx.cpu_released = true;
3072 	}
3073 }
3074 
3075 static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
3076 			      struct task_struct *next)
3077 {
3078 	struct scx_sched *sch = scx_task_sched(p);
3079 
3080 	/* see kick_sync_wait_bal_cb() */
3081 	smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
3082 
3083 	update_curr_scx(rq);
3084 
3085 	/* see dequeue_task_scx() on why we skip when !QUEUED */
3086 	if (SCX_HAS_OP(sch, stopping) && (p->scx.flags & SCX_TASK_QUEUED))
3087 		SCX_CALL_OP_TASK(sch, stopping, rq, p, true);
3088 
3089 	if (p->scx.flags & SCX_TASK_QUEUED) {
3090 		set_task_runnable(rq, p);
3091 
3092 		/*
3093 		 * If @p has slice left and is being put, @p is getting
3094 		 * preempted by a higher priority scheduler class or core-sched
3095 		 * forcing a different task. Leave it at the head of the local
3096 		 * DSQ unless it was an IMMED task. IMMED tasks should not
3097 		 * linger on a busy CPU, reenqueue them to the BPF scheduler.
3098 		 */
3099 		if (p->scx.slice && !scx_bypassing(sch, cpu_of(rq))) {
3100 			if (p->scx.flags & SCX_TASK_IMMED) {
3101 				p->scx.flags |= SCX_TASK_REENQ_PREEMPTED;
3102 				do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
3103 				p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
3104 			} else {
3105 				dispatch_enqueue(sch, rq, &rq->scx.local_dsq, p, SCX_ENQ_HEAD);
3106 			}
3107 			goto switch_class;
3108 		}
3109 
3110 		/*
3111 		 * If @p is runnable but we're about to enter a lower
3112 		 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell
3113 		 * ops.enqueue() that @p is the only one available for this cpu,
3114 		 * which should trigger an explicit follow-up scheduling event.
3115 		 *
3116 		 * Core scheduling can force this CPU idle while @p stays
3117 		 * runnable. @p's cookie then won't match the core's, so skip
3118 		 * the warning in that case.
3119 		 */
3120 		if (next && sched_class_above(&ext_sched_class, next->sched_class)) {
3121 			WARN_ON_ONCE(sched_cpu_cookie_match(rq, p) &&
3122 				     !(sch->ops.flags & SCX_OPS_ENQ_LAST));
3123 			do_enqueue_task(rq, p, SCX_ENQ_LAST, -1);
3124 		} else {
3125 			do_enqueue_task(rq, p, 0, -1);
3126 		}
3127 	}
3128 
3129 switch_class:
3130 	if (next && next->sched_class != &ext_sched_class)
3131 		switch_class(rq, next);
3132 }
3133 
3134 static void kick_sync_wait_bal_cb(struct rq *rq)
3135 {
3136 	struct scx_kick_syncs __rcu *ks = __this_cpu_read(scx_kick_syncs);
3137 	unsigned long *ksyncs = rcu_dereference_sched(ks)->syncs;
3138 	bool waited;
3139 	s32 cpu;
3140 
3141 	/*
3142 	 * Drop rq lock and enable IRQs while waiting. IRQs must be enabled
3143 	 * — a target CPU may be waiting for us to process an IPI (e.g. TLB
3144 	 * flush) while we wait for its kick_sync to advance.
3145 	 *
3146 	 * Also, keep advancing our own kick_sync so that new kick_sync waits
3147 	 * targeting us, which can start after we drop the lock, cannot form
3148 	 * cyclic dependencies.
3149 	 */
3150 retry:
3151 	waited = false;
3152 	for_each_cpu(cpu, rq->scx.cpus_to_sync) {
3153 		/*
3154 		 * smp_load_acquire() pairs with smp_store_release() on
3155 		 * kick_sync updates on the target CPUs.
3156 		 */
3157 		if (cpu == cpu_of(rq) ||
3158 		    smp_load_acquire(&cpu_rq(cpu)->scx.kick_sync) != ksyncs[cpu]) {
3159 			cpumask_clear_cpu(cpu, rq->scx.cpus_to_sync);
3160 			continue;
3161 		}
3162 
3163 		raw_spin_rq_unlock_irq(rq);
3164 		while (READ_ONCE(cpu_rq(cpu)->scx.kick_sync) == ksyncs[cpu]) {
3165 			smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
3166 			cpu_relax();
3167 		}
3168 		raw_spin_rq_lock_irq(rq);
3169 		waited = true;
3170 	}
3171 
3172 	if (waited)
3173 		goto retry;
3174 }
3175 
3176 static struct task_struct *first_local_task(struct rq *rq)
3177 {
3178 	return list_first_entry_or_null(&rq->scx.local_dsq.list,
3179 					struct task_struct, scx.dsq_list.node);
3180 }
3181 
3182 static struct task_struct *
3183 do_pick_task_scx(struct rq *rq, struct rq_flags *rf, bool force_scx)
3184 {
3185 	struct task_struct *prev = rq->curr;
3186 	bool keep_prev;
3187 	struct task_struct *p;
3188 
3189 	/* see kick_sync_wait_bal_cb() */
3190 	smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
3191 
3192 	rq_modified_begin(rq, &ext_sched_class);
3193 
3194 	rq_unpin_lock(rq, rf);
3195 	balance_one(rq, prev);
3196 	rq_repin_lock(rq, rf);
3197 	maybe_queue_balance_callback(rq);
3198 
3199 	/*
3200 	 * Defer to a balance callback which can drop rq lock and enable
3201 	 * IRQs. Waiting directly in the pick path would deadlock against
3202 	 * CPUs sending us IPIs (e.g. TLB flushes) while we wait for them.
3203 	 */
3204 	if (unlikely(rq->scx.kick_sync_pending)) {
3205 		rq->scx.kick_sync_pending = false;
3206 		queue_balance_callback(rq, &rq->scx.kick_sync_bal_cb,
3207 				       kick_sync_wait_bal_cb);
3208 	}
3209 
3210 	/*
3211 	 * If any higher-priority sched class enqueued a runnable task on
3212 	 * this rq during balance_one(), abort and return RETRY_TASK, so
3213 	 * that the scheduler loop can restart.
3214 	 *
3215 	 * If @force_scx is true, always try to pick a SCHED_EXT task,
3216 	 * regardless of any higher-priority sched classes activity.
3217 	 */
3218 	if (!force_scx && rq_modified_above(rq, &ext_sched_class))
3219 		return RETRY_TASK;
3220 
3221 	keep_prev = rq->scx.flags & SCX_RQ_BAL_KEEP;
3222 	if (unlikely(keep_prev &&
3223 		     prev->sched_class != &ext_sched_class)) {
3224 		WARN_ON_ONCE(scx_enable_state() == SCX_ENABLED);
3225 		keep_prev = false;
3226 	}
3227 
3228 	/*
3229 	 * If balance_one() is telling us to keep running @prev, replenish slice
3230 	 * if necessary and keep running @prev. Otherwise, pop the first one
3231 	 * from the local DSQ.
3232 	 */
3233 	if (keep_prev) {
3234 		p = prev;
3235 		if (!p->scx.slice)
3236 			refill_task_slice_dfl(scx_task_sched(p), p);
3237 	} else {
3238 		p = first_local_task(rq);
3239 		if (!p)
3240 			return NULL;
3241 
3242 		if (unlikely(!p->scx.slice)) {
3243 			struct scx_sched *sch = scx_task_sched(p);
3244 
3245 			if (!scx_bypassing(sch, cpu_of(rq)) &&
3246 			    !sch->warned_zero_slice) {
3247 				printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in %s()\n",
3248 						p->comm, p->pid, __func__);
3249 				sch->warned_zero_slice = true;
3250 			}
3251 			refill_task_slice_dfl(sch, p);
3252 		}
3253 	}
3254 
3255 	return p;
3256 }
3257 
3258 static struct task_struct *pick_task_scx(struct rq *rq, struct rq_flags *rf)
3259 {
3260 	return do_pick_task_scx(rq, rf, false);
3261 }
3262 
3263 /*
3264  * Select the next task to run from the ext scheduling class.
3265  *
3266  * Use do_pick_task_scx() directly with @force_scx enabled, since the
3267  * dl_server must always select a sched_ext task.
3268  */
3269 static struct task_struct *
3270 ext_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
3271 {
3272 	if (!scx_enabled())
3273 		return NULL;
3274 
3275 	return do_pick_task_scx(dl_se->rq, rf, true);
3276 }
3277 
3278 /*
3279  * Initialize the ext server deadline entity.
3280  */
3281 void ext_server_init(struct rq *rq)
3282 {
3283 	struct sched_dl_entity *dl_se = &rq->ext_server;
3284 
3285 	init_dl_entity(dl_se);
3286 
3287 	dl_server_init(dl_se, rq, ext_server_pick_task);
3288 }
3289 
3290 #ifdef CONFIG_SCHED_CORE
3291 /**
3292  * scx_prio_less - Task ordering for core-sched
3293  * @a: task A
3294  * @b: task B
3295  * @in_fi: in forced idle state
3296  *
3297  * Core-sched is implemented as an additional scheduling layer on top of the
3298  * usual sched_class'es and needs to find out the expected task ordering. For
3299  * SCX, core-sched calls this function to interrogate the task ordering.
3300  *
3301  * Unless overridden by ops.core_sched_before(), @p->scx.core_sched_at is used
3302  * to implement the default task ordering. The older the timestamp, the higher
3303  * priority the task - the global FIFO ordering matching the default scheduling
3304  * behavior.
3305  *
3306  * When ops.core_sched_before() is enabled, @p->scx.core_sched_at is used to
3307  * implement FIFO ordering within each local DSQ. See pick_task_scx().
3308  */
3309 bool scx_prio_less(const struct task_struct *a, const struct task_struct *b,
3310 		   bool in_fi)
3311 {
3312 	struct scx_sched *sch_a = scx_task_sched(a);
3313 	struct scx_sched *sch_b = scx_task_sched(b);
3314 
3315 	/*
3316 	 * The const qualifiers are dropped from task_struct pointers when
3317 	 * calling ops.core_sched_before(). Accesses are controlled by the
3318 	 * verifier.
3319 	 */
3320 	if (sch_a == sch_b && SCX_HAS_OP(sch_a, core_sched_before) &&
3321 	    !scx_bypassing(sch_a, task_cpu(a)))
3322 		return SCX_CALL_OP_2TASKS_RET(sch_a, core_sched_before,
3323 					      task_rq(a),
3324 					      (struct task_struct *)a,
3325 					      (struct task_struct *)b);
3326 	else
3327 		return time_after64(a->scx.core_sched_at, b->scx.core_sched_at);
3328 }
3329 #endif	/* CONFIG_SCHED_CORE */
3330 
3331 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags)
3332 {
3333 	struct scx_sched *sch = scx_task_sched(p);
3334 	bool bypassing;
3335 
3336 	/*
3337 	 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it
3338 	 * can be a good migration opportunity with low cache and memory
3339 	 * footprint. Returning a CPU different than @prev_cpu triggers
3340 	 * immediate rq migration. However, for SCX, as the current rq
3341 	 * association doesn't dictate where the task is going to run, this
3342 	 * doesn't fit well. If necessary, we can later add a dedicated method
3343 	 * which can decide to preempt self to force it through the regular
3344 	 * scheduling path.
3345 	 */
3346 	if (unlikely(wake_flags & WF_EXEC))
3347 		return prev_cpu;
3348 
3349 	bypassing = scx_bypassing(sch, task_cpu(p));
3350 	if (likely(SCX_HAS_OP(sch, select_cpu)) && !bypassing) {
3351 		s32 cpu;
3352 		struct task_struct **ddsp_taskp;
3353 
3354 		ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
3355 		WARN_ON_ONCE(*ddsp_taskp);
3356 		*ddsp_taskp = p;
3357 
3358 		this_rq()->scx.in_select_cpu = true;
3359 		cpu = SCX_CALL_OP_TASK_RET(sch, select_cpu, NULL, p,
3360 					   scx_cpu_arg(prev_cpu), wake_flags);
3361 		cpu = scx_cpu_ret(sch, cpu);
3362 		this_rq()->scx.in_select_cpu = false;
3363 		p->scx.selected_cpu = cpu;
3364 		*ddsp_taskp = NULL;
3365 		if (scx_cpu_valid(sch, cpu, "from ops.select_cpu()"))
3366 			return cpu;
3367 		else
3368 			return prev_cpu;
3369 	} else {
3370 		s32 cpu;
3371 
3372 		cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, NULL, 0);
3373 		if (cpu >= 0) {
3374 			refill_task_slice_dfl(sch, p);
3375 			p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL;
3376 		} else {
3377 			cpu = prev_cpu;
3378 		}
3379 		p->scx.selected_cpu = cpu;
3380 
3381 		if (bypassing)
3382 			__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
3383 		return cpu;
3384 	}
3385 }
3386 
3387 static void task_woken_scx(struct rq *rq, struct task_struct *p)
3388 {
3389 	run_deferred(rq);
3390 }
3391 
3392 static void set_cpus_allowed_scx(struct task_struct *p,
3393 				 struct affinity_context *ac)
3394 {
3395 	struct scx_sched *sch = scx_task_sched(p);
3396 
3397 	set_cpus_allowed_common(p, ac);
3398 
3399 	if (task_dead_and_done(p))
3400 		return;
3401 
3402 	/*
3403 	 * The effective cpumask is stored in @p->cpus_ptr which may temporarily
3404 	 * differ from the configured one in @p->cpus_mask. Always tell the bpf
3405 	 * scheduler the effective one.
3406 	 *
3407 	 * Fine-grained memory write control is enforced by BPF making the const
3408 	 * designation pointless. Cast it away when calling the operation.
3409 	 */
3410 	if (SCX_HAS_OP(sch, set_cpumask))
3411 		scx_call_op_set_cpumask(sch, task_rq(p), p, (struct cpumask *)p->cpus_ptr);
3412 }
3413 
3414 static void handle_hotplug(struct rq *rq, bool online)
3415 {
3416 	struct scx_sched *sch = scx_root;
3417 	s32 cpu = cpu_of(rq);
3418 
3419 	atomic_long_inc(&scx_hotplug_seq);
3420 
3421 	/*
3422 	 * scx_root updates are protected by cpus_read_lock() and will stay
3423 	 * stable here. Note that we can't depend on scx_enabled() test as the
3424 	 * hotplug ops need to be enabled before __scx_enabled is set.
3425 	 */
3426 	if (unlikely(!sch))
3427 		return;
3428 
3429 	if (scx_enabled())
3430 		scx_idle_update_selcpu_topology(&sch->ops);
3431 
3432 	if (online && SCX_HAS_OP(sch, cpu_online))
3433 		SCX_CALL_OP(sch, cpu_online, NULL, scx_cpu_arg(cpu));
3434 	else if (!online && SCX_HAS_OP(sch, cpu_offline))
3435 		SCX_CALL_OP(sch, cpu_offline, NULL, scx_cpu_arg(cpu));
3436 	else
3437 		scx_exit(sch, SCX_EXIT_UNREG_KERN,
3438 			 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
3439 			 "cpu %d going %s, exiting scheduler", cpu,
3440 			 online ? "online" : "offline");
3441 }
3442 
3443 void scx_rq_activate(struct rq *rq)
3444 {
3445 	handle_hotplug(rq, true);
3446 }
3447 
3448 void scx_rq_deactivate(struct rq *rq)
3449 {
3450 	handle_hotplug(rq, false);
3451 }
3452 
3453 static void rq_online_scx(struct rq *rq)
3454 {
3455 	rq->scx.flags |= SCX_RQ_ONLINE;
3456 }
3457 
3458 static void rq_offline_scx(struct rq *rq)
3459 {
3460 	rq->scx.flags &= ~SCX_RQ_ONLINE;
3461 }
3462 
3463 static bool check_rq_for_timeouts(struct rq *rq)
3464 {
3465 	struct scx_sched *sch;
3466 	struct task_struct *p;
3467 	struct rq_flags rf;
3468 	bool timed_out = false;
3469 
3470 	rq_lock_irqsave(rq, &rf);
3471 	sch = rcu_dereference_bh(scx_root);
3472 	if (unlikely(!sch))
3473 		goto out_unlock;
3474 
3475 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) {
3476 		struct scx_sched *sch = scx_task_sched(p);
3477 		unsigned long last_runnable = p->scx.runnable_at;
3478 
3479 		if (unlikely(time_after(jiffies,
3480 					last_runnable + READ_ONCE(sch->watchdog_timeout)))) {
3481 			u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable);
3482 
3483 			__scx_exit(sch, SCX_EXIT_ERROR_STALL, 0, cpu_of(rq),
3484 				   "%s[%d] failed to run for %u.%03us",
3485 				   p->comm, p->pid, dur_ms / 1000,
3486 				   dur_ms % 1000);
3487 			timed_out = true;
3488 			break;
3489 		}
3490 	}
3491 out_unlock:
3492 	rq_unlock_irqrestore(rq, &rf);
3493 	return timed_out;
3494 }
3495 
3496 static void scx_watchdog_workfn(struct work_struct *work)
3497 {
3498 	unsigned long intv;
3499 	int cpu;
3500 
3501 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
3502 
3503 	for_each_online_cpu(cpu) {
3504 		if (unlikely(check_rq_for_timeouts(cpu_rq(cpu))))
3505 			break;
3506 
3507 		cond_resched();
3508 	}
3509 
3510 	intv = READ_ONCE(scx_watchdog_interval);
3511 	if (intv < ULONG_MAX)
3512 		queue_delayed_work(system_dfl_wq, to_delayed_work(work), intv);
3513 }
3514 
3515 void scx_tick(struct rq *rq)
3516 {
3517 	struct scx_sched *root;
3518 	unsigned long last_check;
3519 
3520 	if (!scx_enabled())
3521 		return;
3522 
3523 	root = rcu_dereference_bh(scx_root);
3524 	if (unlikely(!root))
3525 		return;
3526 
3527 	last_check = READ_ONCE(scx_watchdog_timestamp);
3528 	if (unlikely(time_after(jiffies,
3529 				last_check + READ_ONCE(root->watchdog_timeout)))) {
3530 		u32 dur_ms = jiffies_to_msecs(jiffies - last_check);
3531 
3532 		scx_exit(root, SCX_EXIT_ERROR_STALL, 0,
3533 			 "watchdog failed to check in for %u.%03us",
3534 			 dur_ms / 1000, dur_ms % 1000);
3535 	}
3536 
3537 	update_other_load_avgs(rq);
3538 }
3539 
3540 static void task_tick_scx(struct rq *rq, struct task_struct *curr, int queued)
3541 {
3542 	struct scx_sched *sch = scx_task_sched(curr);
3543 
3544 	update_curr_scx(rq);
3545 
3546 	/*
3547 	 * While disabling, always resched and refresh core-sched timestamp as
3548 	 * we can't trust the slice management or ops.core_sched_before().
3549 	 */
3550 	if (scx_bypassing(sch, cpu_of(rq))) {
3551 		curr->scx.slice = 0;
3552 		touch_core_sched(rq, curr);
3553 	} else if (SCX_HAS_OP(sch, tick)) {
3554 		SCX_CALL_OP_TASK(sch, tick, rq, curr);
3555 	}
3556 
3557 	if (!curr->scx.slice)
3558 		resched_curr(rq);
3559 }
3560 
3561 #ifdef CONFIG_EXT_GROUP_SCHED
3562 static struct cgroup *tg_cgrp(struct task_group *tg)
3563 {
3564 	/*
3565 	 * If CGROUP_SCHED is disabled, @tg is NULL. If @tg is an autogroup,
3566 	 * @tg->css.cgroup is NULL. In both cases, @tg can be treated as the
3567 	 * root cgroup.
3568 	 */
3569 	if (tg && tg->css.cgroup)
3570 		return tg->css.cgroup;
3571 	else
3572 		return &cgrp_dfl_root.cgrp;
3573 }
3574 
3575 #define SCX_INIT_TASK_ARGS_CGROUP(tg)		.cgroup = tg_cgrp(tg),
3576 
3577 #else	/* CONFIG_EXT_GROUP_SCHED */
3578 
3579 #define SCX_INIT_TASK_ARGS_CGROUP(tg)
3580 
3581 #endif	/* CONFIG_EXT_GROUP_SCHED */
3582 
3583 static int __scx_init_task(struct scx_sched *sch, struct task_struct *p, bool fork)
3584 {
3585 	int ret;
3586 
3587 	p->scx.disallow = false;
3588 
3589 	if (SCX_HAS_OP(sch, init_task)) {
3590 		struct scx_init_task_args args = {
3591 			SCX_INIT_TASK_ARGS_CGROUP(task_group(p))
3592 			.fork = fork,
3593 		};
3594 
3595 		ret = SCX_CALL_OP_RET(sch, init_task, NULL, p, &args);
3596 		if (unlikely(ret)) {
3597 			ret = ops_sanitize_err(sch, "init_task", ret);
3598 			return ret;
3599 		}
3600 	}
3601 
3602 	if (p->scx.disallow) {
3603 		if (unlikely(scx_parent(sch))) {
3604 			scx_error(sch, "non-root ops.init_task() set task->scx.disallow for %s[%d]",
3605 				  p->comm, p->pid);
3606 		} else if (unlikely(fork)) {
3607 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] during fork",
3608 				  p->comm, p->pid);
3609 		} else if (unlikely(scx_enable_state() != SCX_ENABLING)) {
3610 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] outside the enable path",
3611 				  p->comm, p->pid);
3612 		} else {
3613 			struct rq *rq;
3614 			struct rq_flags rf;
3615 
3616 			rq = task_rq_lock(p, &rf);
3617 
3618 			/*
3619 			 * We're in the load path and @p->policy will be applied
3620 			 * right after. Reverting @p->policy here and rejecting
3621 			 * %SCHED_EXT transitions from scx_check_setscheduler()
3622 			 * guarantees that if ops.init_task() sets @p->disallow,
3623 			 * @p can never be in SCX.
3624 			 */
3625 			if (p->policy == SCHED_EXT) {
3626 				p->policy = SCHED_NORMAL;
3627 				atomic_long_inc(&scx_nr_rejected);
3628 			}
3629 
3630 			task_rq_unlock(rq, p, &rf);
3631 		}
3632 	}
3633 
3634 	return 0;
3635 }
3636 
3637 static void __scx_enable_task(struct scx_sched *sch, struct task_struct *p)
3638 {
3639 	struct rq *rq = task_rq(p);
3640 	u32 weight;
3641 
3642 	lockdep_assert_rq_held(rq);
3643 
3644 	/*
3645 	 * Verify the task is not in BPF scheduler's custody. If flag
3646 	 * transitions are consistent, the flag should always be clear
3647 	 * here.
3648 	 */
3649 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_IN_CUSTODY);
3650 
3651 	/*
3652 	 * Set the weight before calling ops.enable() so that the scheduler
3653 	 * doesn't see a stale value if they inspect the task struct.
3654 	 */
3655 	if (task_has_idle_policy(p))
3656 		weight = WEIGHT_IDLEPRIO;
3657 	else
3658 		weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO];
3659 
3660 	p->scx.weight = sched_weight_to_cgroup(weight);
3661 
3662 	if (SCX_HAS_OP(sch, enable))
3663 		SCX_CALL_OP_TASK(sch, enable, rq, p);
3664 
3665 	if (SCX_HAS_OP(sch, set_weight))
3666 		SCX_CALL_OP_TASK(sch, set_weight, rq, p, p->scx.weight);
3667 }
3668 
3669 static void scx_enable_task(struct scx_sched *sch, struct task_struct *p)
3670 {
3671 	__scx_enable_task(sch, p);
3672 	scx_set_task_state(p, SCX_TASK_ENABLED);
3673 }
3674 
3675 static void scx_disable_task(struct scx_sched *sch, struct task_struct *p)
3676 {
3677 	struct rq *rq = task_rq(p);
3678 
3679 	lockdep_assert_rq_held(rq);
3680 	WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED);
3681 
3682 	clear_direct_dispatch(p);
3683 
3684 	if (SCX_HAS_OP(sch, disable))
3685 		SCX_CALL_OP_TASK(sch, disable, rq, p);
3686 	scx_set_task_state(p, SCX_TASK_READY);
3687 
3688 	/*
3689 	 * Reset the SCX-managed fields when @p leaves the BPF scheduler's
3690 	 * control, after ops.disable() has observed their final values.
3691 	 */
3692 	p->scx.dsq_vtime = 0;
3693 	p->scx.slice = 0;
3694 
3695 	/*
3696 	 * Verify the task is not in BPF scheduler's custody. If flag
3697 	 * transitions are consistent, the flag should always be clear
3698 	 * here.
3699 	 */
3700 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_IN_CUSTODY);
3701 }
3702 
3703 static void __scx_disable_and_exit_task(struct scx_sched *sch,
3704 					struct task_struct *p)
3705 {
3706 	struct scx_exit_task_args args = {
3707 		.cancelled = false,
3708 	};
3709 
3710 	lockdep_assert_held(&p->pi_lock);
3711 	lockdep_assert_rq_held(task_rq(p));
3712 
3713 	switch (scx_get_task_state(p)) {
3714 	case SCX_TASK_NONE:
3715 		return;
3716 	case SCX_TASK_INIT:
3717 		args.cancelled = true;
3718 		break;
3719 	case SCX_TASK_READY:
3720 		break;
3721 	case SCX_TASK_ENABLED:
3722 		scx_disable_task(sch, p);
3723 		break;
3724 	default:
3725 		WARN_ON_ONCE(true);
3726 		return;
3727 	}
3728 
3729 	if (SCX_HAS_OP(sch, exit_task))
3730 		SCX_CALL_OP_TASK(sch, exit_task, task_rq(p), p, &args);
3731 }
3732 
3733 /*
3734  * Undo a completed __scx_init_task(sch, p, false) when scx_enable_task() never
3735  * ran. The task state has not been transitioned, so this mirrors the
3736  * SCX_TASK_INIT branch in __scx_disable_and_exit_task().
3737  */
3738 static void scx_sub_init_cancel_task(struct scx_sched *sch, struct task_struct *p)
3739 {
3740 	struct scx_exit_task_args args = { .cancelled = true };
3741 
3742 	lockdep_assert_held(&p->pi_lock);
3743 	lockdep_assert_rq_held(task_rq(p));
3744 
3745 	if (SCX_HAS_OP(sch, exit_task))
3746 		SCX_CALL_OP_TASK(sch, exit_task, task_rq(p), p, &args);
3747 }
3748 
3749 static void scx_disable_and_exit_task(struct scx_sched *sch,
3750 				      struct task_struct *p)
3751 {
3752 	__scx_disable_and_exit_task(sch, p);
3753 
3754 	/*
3755 	 * If set, @p exited between __scx_init_task() and scx_enable_task() in
3756 	 * scx_sub_enable() and is initialized for both the associated sched and
3757 	 * its parent. Exit for the child too - scx_enable_task() never ran for
3758 	 * it, so undo only init_task. The flag is only set on the sub-enable
3759 	 * path, so it's always clear when @p arrives here in %SCX_TASK_NONE.
3760 	 */
3761 	if (p->scx.flags & SCX_TASK_SUB_INIT) {
3762 		if (!WARN_ON_ONCE(!scx_enabling_sub_sched))
3763 			scx_sub_init_cancel_task(scx_enabling_sub_sched, p);
3764 		p->scx.flags &= ~SCX_TASK_SUB_INIT;
3765 	}
3766 
3767 	scx_set_task_sched(p, NULL);
3768 	scx_set_task_state(p, SCX_TASK_NONE);
3769 }
3770 
3771 void init_scx_entity(struct sched_ext_entity *scx)
3772 {
3773 	memset(scx, 0, sizeof(*scx));
3774 	INIT_LIST_HEAD(&scx->dsq_list.node);
3775 	RB_CLEAR_NODE(&scx->dsq_priq);
3776 	scx->sticky_cpu = -1;
3777 	scx->holding_cpu = -1;
3778 	INIT_LIST_HEAD(&scx->runnable_node);
3779 	scx->runnable_at = jiffies;
3780 	scx->ddsp_dsq_id = SCX_DSQ_INVALID;
3781 	scx->slice = SCX_SLICE_DFL;
3782 }
3783 
3784 /* See scx_tid_alloc / scx_tid_cursor. */
3785 static u64 scx_alloc_tid(void)
3786 {
3787 	struct scx_tid_alloc *ta;
3788 
3789 	guard(preempt)();
3790 	ta = this_cpu_ptr(&scx_tid_alloc);
3791 
3792 	if (unlikely(ta->next >= ta->end)) {
3793 		ta->next = atomic64_fetch_add(SCX_TID_CHUNK, &scx_tid_cursor);
3794 		ta->end = ta->next + SCX_TID_CHUNK;
3795 	}
3796 	return ta->next++;
3797 }
3798 
3799 static void scx_tid_hash_insert(struct task_struct *p)
3800 {
3801 	int ret;
3802 
3803 	lockdep_assert_held(&scx_tasks_lock);
3804 
3805 	ret = rhashtable_lookup_insert_fast(&scx_tid_hash,
3806 					    &p->scx.tid_hash_node,
3807 					    scx_tid_hash_params);
3808 	WARN_ON_ONCE(ret);
3809 }
3810 
3811 void scx_pre_fork(struct task_struct *p)
3812 {
3813 	/*
3814 	 * BPF scheduler enable/disable paths want to be able to iterate and
3815 	 * update all tasks which can become complex when racing forks. As
3816 	 * enable/disable are very cold paths, let's use a percpu_rwsem to
3817 	 * exclude forks.
3818 	 */
3819 	percpu_down_read(&scx_fork_rwsem);
3820 }
3821 
3822 int scx_fork(struct task_struct *p, struct kernel_clone_args *kargs)
3823 {
3824 	s32 ret;
3825 
3826 	percpu_rwsem_assert_held(&scx_fork_rwsem);
3827 
3828 	p->scx.tid = scx_alloc_tid();
3829 
3830 	if (scx_init_task_enabled) {
3831 #ifdef CONFIG_EXT_SUB_SCHED
3832 		struct scx_sched *sch = kargs->cset->dfl_cgrp->scx_sched;
3833 #else
3834 		struct scx_sched *sch = scx_root;
3835 #endif
3836 		scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
3837 		ret = __scx_init_task(sch, p, true);
3838 		if (unlikely(ret)) {
3839 			scx_set_task_state(p, SCX_TASK_NONE);
3840 			return ret;
3841 		}
3842 		scx_set_task_state(p, SCX_TASK_INIT);
3843 		scx_set_task_sched(p, sch);
3844 	}
3845 
3846 	return 0;
3847 }
3848 
3849 void scx_post_fork(struct task_struct *p)
3850 {
3851 	if (scx_init_task_enabled) {
3852 		scx_set_task_state(p, SCX_TASK_READY);
3853 
3854 		/*
3855 		 * Enable the task immediately if it's running on sched_ext.
3856 		 * Otherwise, it'll be enabled in switching_to_scx() if and
3857 		 * when it's ever configured to run with a SCHED_EXT policy.
3858 		 */
3859 		if (p->sched_class == &ext_sched_class) {
3860 			struct rq_flags rf;
3861 			struct rq *rq;
3862 
3863 			rq = task_rq_lock(p, &rf);
3864 			scx_enable_task(scx_task_sched(p), p);
3865 			task_rq_unlock(rq, p, &rf);
3866 		}
3867 	}
3868 
3869 	scoped_guard(raw_spinlock_irq, &scx_tasks_lock) {
3870 		list_add_tail(&p->scx.tasks_node, &scx_tasks);
3871 		if (scx_tid_to_task_enabled())
3872 			scx_tid_hash_insert(p);
3873 	}
3874 
3875 	percpu_up_read(&scx_fork_rwsem);
3876 }
3877 
3878 void scx_cancel_fork(struct task_struct *p)
3879 {
3880 	if (scx_enabled()) {
3881 		struct rq *rq;
3882 		struct rq_flags rf;
3883 
3884 		rq = task_rq_lock(p, &rf);
3885 		WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY);
3886 		scx_disable_and_exit_task(scx_task_sched(p), p);
3887 		task_rq_unlock(rq, p, &rf);
3888 	}
3889 
3890 	percpu_up_read(&scx_fork_rwsem);
3891 }
3892 
3893 /**
3894  * task_dead_and_done - Is a task dead and done running?
3895  * @p: target task
3896  *
3897  * Once sched_ext_dead() removes the dead task from scx_tasks and exits it, the
3898  * task no longer exists from SCX's POV. However, certain sched_class ops may be
3899  * invoked on these dead tasks leading to failures - e.g. sched_setscheduler()
3900  * may try to switch a task which finished sched_ext_dead() back into SCX
3901  * triggering invalid SCX task state transitions and worse.
3902  *
3903  * Once a task has finished the final switch, sched_ext_dead() is the only thing
3904  * that needs to happen on the task. Use this test to short-circuit sched_class
3905  * operations which may be called on dead tasks.
3906  */
3907 static bool task_dead_and_done(struct task_struct *p)
3908 {
3909 	struct rq *rq = task_rq(p);
3910 
3911 	lockdep_assert_rq_held(rq);
3912 
3913 	/*
3914 	 * In do_task_dead(), a dying task sets %TASK_DEAD with preemption
3915 	 * disabled and __schedule(). If @p has %TASK_DEAD set and off CPU, @p
3916 	 * won't ever run again.
3917 	 */
3918 	return unlikely(READ_ONCE(p->__state) == TASK_DEAD) &&
3919 		!task_on_cpu(rq, p);
3920 }
3921 
3922 void sched_ext_dead(struct task_struct *p)
3923 {
3924 	/*
3925 	 * By the time control reaches here, @p has %TASK_DEAD set, switched out
3926 	 * for the last time and then dropped the rq lock - task_dead_and_done()
3927 	 * should be returning %true nullifying the straggling sched_class ops.
3928 	 * Remove from scx_tasks and exit @p.
3929 	 */
3930 	scoped_guard(raw_spinlock_irqsave, &scx_tasks_lock) {
3931 		list_del_init(&p->scx.tasks_node);
3932 		if (scx_tid_to_task_enabled())
3933 			rhashtable_remove_fast(&scx_tid_hash,
3934 					       &p->scx.tid_hash_node,
3935 					       scx_tid_hash_params);
3936 	}
3937 
3938 	/*
3939 	 * @p is off scx_tasks and wholly ours. scx_root_enable()'s READY ->
3940 	 * ENABLED transitions can't race us. Disable ops for @p.
3941 	 *
3942 	 * %SCX_TASK_DEAD synchronizes against cgroup task iteration - see
3943 	 * scx_task_iter_next_locked(). NONE tasks need no marking: cgroup
3944 	 * iteration is only used from sub-sched paths, which require root
3945 	 * enabled. Root enable transitions every live task to at least READY.
3946 	 *
3947 	 * %INIT_BEGIN means ops.init_task() is running for @p. Don't call
3948 	 * into ops; transition to %DEAD so the post-init recheck unwinds
3949 	 * via scx_sub_init_cancel_task().
3950 	 */
3951 	if (scx_get_task_state(p) != SCX_TASK_NONE) {
3952 		struct rq_flags rf;
3953 		struct rq *rq;
3954 
3955 		rq = task_rq_lock(p, &rf);
3956 		if (scx_get_task_state(p) != SCX_TASK_INIT_BEGIN)
3957 			scx_disable_and_exit_task(scx_task_sched(p), p);
3958 		scx_set_task_state(p, SCX_TASK_DEAD);
3959 		task_rq_unlock(rq, p, &rf);
3960 	}
3961 }
3962 
3963 static void reweight_task_scx(struct rq *rq, struct task_struct *p,
3964 			      const struct load_weight *lw)
3965 {
3966 	struct scx_sched *sch = scx_task_sched(p);
3967 
3968 	lockdep_assert_rq_held(task_rq(p));
3969 
3970 	if (task_dead_and_done(p))
3971 		return;
3972 
3973 	/*
3974 	 * When switching sched_class away from SCX, reweight_task_scx()
3975 	 * is called _after_ scx_disable_task(). Skip calling ops.set_weight()
3976 	 * since the BPF scheduler may have already forgotten the task in
3977 	 * ops.disable().
3978 	 * p->scx.weight will be recalculated in scx_enable_task() if the task
3979 	 * ever returns to SCX class.
3980 	 */
3981 	if (scx_get_task_state(p) != SCX_TASK_ENABLED)
3982 		return;
3983 
3984 	p->scx.weight = sched_weight_to_cgroup(scale_load_down(lw->weight));
3985 	if (SCX_HAS_OP(sch, set_weight))
3986 		SCX_CALL_OP_TASK(sch, set_weight, rq, p, p->scx.weight);
3987 }
3988 
3989 static void prio_changed_scx(struct rq *rq, struct task_struct *p, u64 oldprio)
3990 {
3991 }
3992 
3993 static void switching_to_scx(struct rq *rq, struct task_struct *p)
3994 {
3995 	struct scx_sched *sch = scx_task_sched(p);
3996 
3997 	if (task_dead_and_done(p))
3998 		return;
3999 
4000 	scx_enable_task(sch, p);
4001 
4002 	/*
4003 	 * set_cpus_allowed_scx() is not called while @p is associated with a
4004 	 * different scheduler class. Keep the BPF scheduler up-to-date.
4005 	 */
4006 	if (SCX_HAS_OP(sch, set_cpumask))
4007 		scx_call_op_set_cpumask(sch, rq, p, (struct cpumask *)p->cpus_ptr);
4008 }
4009 
4010 static void switched_from_scx(struct rq *rq, struct task_struct *p)
4011 {
4012 	if (task_dead_and_done(p))
4013 		return;
4014 
4015 	/*
4016 	 * %NONE means SCX is no longer tracking @p at the task level (e.g.
4017 	 * scx_fail_parent() handed @p back to the parent at NONE pending the
4018 	 * parent's own teardown). There is nothing to disable; calling
4019 	 * scx_disable_task() would WARN on the non-%ENABLED state and trigger a
4020 	 * NONE -> READY validation failure.
4021 	 */
4022 	if (scx_get_task_state(p) == SCX_TASK_NONE)
4023 		return;
4024 
4025 	scx_disable_task(scx_task_sched(p), p);
4026 }
4027 
4028 static void switched_to_scx(struct rq *rq, struct task_struct *p) {}
4029 
4030 int scx_check_setscheduler(struct task_struct *p, int policy)
4031 {
4032 	lockdep_assert_rq_held(task_rq(p));
4033 
4034 	/* if disallow, reject transitioning into SCX */
4035 	if (scx_enabled() && READ_ONCE(p->scx.disallow) &&
4036 	    p->policy != policy && policy == SCHED_EXT)
4037 		return -EACCES;
4038 
4039 	return 0;
4040 }
4041 
4042 static void process_ddsp_deferred_locals(struct rq *rq)
4043 {
4044 	struct task_struct *p;
4045 
4046 	lockdep_assert_rq_held(rq);
4047 
4048 	/*
4049 	 * Now that @rq can be unlocked, execute the deferred enqueueing of
4050 	 * tasks directly dispatched to the local DSQs of other CPUs. See
4051 	 * direct_dispatch(). Keep popping from the head instead of using
4052 	 * list_for_each_entry_safe() as dispatch_local_dsq() may unlock @rq
4053 	 * temporarily.
4054 	 */
4055 	while ((p = list_first_entry_or_null(&rq->scx.ddsp_deferred_locals,
4056 				struct task_struct, scx.dsq_list.node))) {
4057 		struct scx_sched *sch = scx_task_sched(p);
4058 		struct scx_dispatch_q *dsq;
4059 		u64 dsq_id = p->scx.ddsp_dsq_id;
4060 		u64 enq_flags = p->scx.ddsp_enq_flags;
4061 
4062 		list_del_init(&p->scx.dsq_list.node);
4063 		clear_direct_dispatch(p);
4064 
4065 		dsq = find_dsq_for_dispatch(sch, rq, dsq_id, task_cpu(p));
4066 		if (!WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL))
4067 			dispatch_to_local_dsq(sch, rq, dsq, p, enq_flags);
4068 	}
4069 }
4070 
4071 /*
4072  * Determine whether @p should be reenqueued from a local DSQ.
4073  *
4074  * @reenq_flags is mutable and accumulates state across the DSQ walk:
4075  *
4076  * - %SCX_REENQ_TSR_NOT_FIRST: Set after the first task is visited. "First"
4077  *   tracks position in the DSQ list, not among IMMED tasks. A non-IMMED task at
4078  *   the head consumes the first slot.
4079  *
4080  * - %SCX_REENQ_TSR_RQ_OPEN: Set by reenq_local() before the walk if
4081  *   rq_is_open() is true.
4082  *
4083  * An IMMED task is kept (returns %false) only if it's the first task in the DSQ
4084  * AND the current task is done — i.e. it will execute immediately. All other
4085  * IMMED tasks are reenqueued. This means if a non-IMMED task sits at the head,
4086  * every IMMED task behind it gets reenqueued.
4087  *
4088  * Reenqueued tasks go through ops.enqueue() with %SCX_ENQ_REENQ |
4089  * %SCX_TASK_REENQ_IMMED. If the BPF scheduler dispatches back to the same local
4090  * DSQ with %SCX_ENQ_IMMED while the CPU is still unavailable, this triggers
4091  * another reenq cycle. Repetitions are bounded by %SCX_REENQ_LOCAL_MAX_REPEAT
4092  * in process_deferred_reenq_locals().
4093  */
4094 static bool local_task_should_reenq(struct task_struct *p, u64 *reenq_flags, u32 *reason)
4095 {
4096 	bool first;
4097 
4098 	first = !(*reenq_flags & SCX_REENQ_TSR_NOT_FIRST);
4099 	*reenq_flags |= SCX_REENQ_TSR_NOT_FIRST;
4100 
4101 	*reason = SCX_TASK_REENQ_KFUNC;
4102 
4103 	if ((p->scx.flags & SCX_TASK_IMMED) &&
4104 	    (!first || !(*reenq_flags & SCX_REENQ_TSR_RQ_OPEN))) {
4105 		__scx_add_event(scx_task_sched(p), SCX_EV_REENQ_IMMED, 1);
4106 		*reason = SCX_TASK_REENQ_IMMED;
4107 		return true;
4108 	}
4109 
4110 	return *reenq_flags & SCX_REENQ_ANY;
4111 }
4112 
4113 static u32 reenq_local(struct scx_sched *sch, struct rq *rq, u64 reenq_flags)
4114 {
4115 	LIST_HEAD(tasks);
4116 	u32 nr_enqueued = 0;
4117 	struct task_struct *p, *n;
4118 
4119 	lockdep_assert_rq_held(rq);
4120 
4121 	if (WARN_ON_ONCE(reenq_flags & __SCX_REENQ_TSR_MASK))
4122 		reenq_flags &= ~__SCX_REENQ_TSR_MASK;
4123 	if (rq_is_open(rq, 0))
4124 		reenq_flags |= SCX_REENQ_TSR_RQ_OPEN;
4125 
4126 	/*
4127 	 * The BPF scheduler may choose to dispatch tasks back to
4128 	 * @rq->scx.local_dsq. Move all candidate tasks off to a private list
4129 	 * first to avoid processing the same tasks repeatedly.
4130 	 */
4131 	list_for_each_entry_safe(p, n, &rq->scx.local_dsq.list,
4132 				 scx.dsq_list.node) {
4133 		struct scx_sched *task_sch = scx_task_sched(p);
4134 		u32 reason;
4135 
4136 		/*
4137 		 * If @p is being migrated, @p's current CPU may not agree with
4138 		 * its allowed CPUs and the migration_cpu_stop is about to
4139 		 * deactivate and re-activate @p anyway. Skip re-enqueueing.
4140 		 *
4141 		 * While racing sched property changes may also dequeue and
4142 		 * re-enqueue a migrating task while its current CPU and allowed
4143 		 * CPUs disagree, they use %ENQUEUE_RESTORE which is bypassed to
4144 		 * the current local DSQ for running tasks and thus are not
4145 		 * visible to the BPF scheduler.
4146 		 */
4147 		if (p->migration_pending)
4148 			continue;
4149 
4150 		if (!scx_is_descendant(task_sch, sch))
4151 			continue;
4152 
4153 		if (!local_task_should_reenq(p, &reenq_flags, &reason))
4154 			continue;
4155 
4156 		dispatch_dequeue(rq, p);
4157 
4158 		if (WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK))
4159 			p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
4160 		p->scx.flags |= reason;
4161 
4162 		list_add_tail(&p->scx.dsq_list.node, &tasks);
4163 	}
4164 
4165 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
4166 		list_del_init(&p->scx.dsq_list.node);
4167 
4168 		do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
4169 
4170 		p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
4171 		nr_enqueued++;
4172 	}
4173 
4174 	return nr_enqueued;
4175 }
4176 
4177 static void process_deferred_reenq_locals(struct rq *rq)
4178 {
4179 	u64 seq = ++rq->scx.deferred_reenq_locals_seq;
4180 
4181 	lockdep_assert_rq_held(rq);
4182 
4183 	while (true) {
4184 		struct scx_sched *sch;
4185 		u64 reenq_flags;
4186 		bool skip = false;
4187 
4188 		scoped_guard (raw_spinlock, &rq->scx.deferred_reenq_lock) {
4189 			struct scx_deferred_reenq_local *drl =
4190 				list_first_entry_or_null(&rq->scx.deferred_reenq_locals,
4191 							 struct scx_deferred_reenq_local,
4192 							 node);
4193 			struct scx_sched_pcpu *sch_pcpu;
4194 
4195 			if (!drl)
4196 				return;
4197 
4198 			sch_pcpu = container_of(drl, struct scx_sched_pcpu,
4199 						deferred_reenq_local);
4200 			sch = sch_pcpu->sch;
4201 
4202 			reenq_flags = drl->flags;
4203 			WRITE_ONCE(drl->flags, 0);
4204 			list_del_init(&drl->node);
4205 
4206 			if (likely(drl->seq != seq)) {
4207 				drl->seq = seq;
4208 				drl->cnt = 0;
4209 			} else {
4210 				if (unlikely(++drl->cnt > SCX_REENQ_LOCAL_MAX_REPEAT)) {
4211 					scx_error(sch, "SCX_ENQ_REENQ on SCX_DSQ_LOCAL repeated %u times",
4212 						  drl->cnt);
4213 					skip = true;
4214 				}
4215 
4216 				__scx_add_event(sch, SCX_EV_REENQ_LOCAL_REPEAT, 1);
4217 			}
4218 		}
4219 
4220 		if (!skip) {
4221 			/* see schedule_dsq_reenq() */
4222 			smp_mb();
4223 
4224 			reenq_local(sch, rq, reenq_flags);
4225 		}
4226 	}
4227 }
4228 
4229 static bool user_task_should_reenq(struct task_struct *p, u64 reenq_flags, u32 *reason)
4230 {
4231 	*reason = SCX_TASK_REENQ_KFUNC;
4232 	return reenq_flags & SCX_REENQ_ANY;
4233 }
4234 
4235 static void reenq_user(struct rq *rq, struct scx_dispatch_q *dsq, u64 reenq_flags)
4236 {
4237 	struct rq *locked_rq = rq;
4238 	struct scx_sched *sch = dsq->sched;
4239 	struct scx_dsq_list_node cursor = INIT_DSQ_LIST_CURSOR(cursor, dsq, 0);
4240 	struct task_struct *p;
4241 	s32 nr_enqueued = 0;
4242 
4243 	lockdep_assert_rq_held(rq);
4244 
4245 	raw_spin_lock(&dsq->lock);
4246 
4247 	while (likely(!READ_ONCE(sch->bypass_depth))) {
4248 		struct rq *task_rq;
4249 		u32 reason;
4250 
4251 		p = nldsq_cursor_next_task(&cursor, dsq);
4252 		if (!p)
4253 			break;
4254 
4255 		if (!user_task_should_reenq(p, reenq_flags, &reason))
4256 			continue;
4257 
4258 		task_rq = task_rq(p);
4259 
4260 		if (locked_rq != task_rq) {
4261 			if (locked_rq)
4262 				raw_spin_rq_unlock(locked_rq);
4263 			if (unlikely(!raw_spin_rq_trylock(task_rq))) {
4264 				raw_spin_unlock(&dsq->lock);
4265 				raw_spin_rq_lock(task_rq);
4266 				raw_spin_lock(&dsq->lock);
4267 			}
4268 			locked_rq = task_rq;
4269 
4270 			/* did we lose @p while switching locks? */
4271 			if (nldsq_cursor_lost_task(&cursor, task_rq, dsq, p))
4272 				continue;
4273 		}
4274 
4275 		/* @p is on @dsq, its rq and @dsq are locked */
4276 		dispatch_dequeue_locked(p, dsq);
4277 		raw_spin_unlock(&dsq->lock);
4278 
4279 		if (WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK))
4280 			p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
4281 		p->scx.flags |= reason;
4282 
4283 		do_enqueue_task(task_rq, p, SCX_ENQ_REENQ, -1);
4284 
4285 		p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK;
4286 
4287 		if (!(++nr_enqueued % SCX_TASK_ITER_BATCH)) {
4288 			raw_spin_rq_unlock(locked_rq);
4289 			locked_rq = NULL;
4290 			cpu_relax();
4291 		}
4292 
4293 		raw_spin_lock(&dsq->lock);
4294 	}
4295 
4296 	list_del_init(&cursor.node);
4297 	raw_spin_unlock(&dsq->lock);
4298 
4299 	if (locked_rq != rq) {
4300 		if (locked_rq)
4301 			raw_spin_rq_unlock(locked_rq);
4302 		raw_spin_rq_lock(rq);
4303 	}
4304 }
4305 
4306 static void process_deferred_reenq_users(struct rq *rq)
4307 {
4308 	lockdep_assert_rq_held(rq);
4309 
4310 	while (true) {
4311 		struct scx_dispatch_q *dsq;
4312 		u64 reenq_flags;
4313 
4314 		scoped_guard (raw_spinlock, &rq->scx.deferred_reenq_lock) {
4315 			struct scx_deferred_reenq_user *dru =
4316 				list_first_entry_or_null(&rq->scx.deferred_reenq_users,
4317 							 struct scx_deferred_reenq_user,
4318 							 node);
4319 			struct scx_dsq_pcpu *dsq_pcpu;
4320 
4321 			if (!dru)
4322 				return;
4323 
4324 			dsq_pcpu = container_of(dru, struct scx_dsq_pcpu,
4325 						deferred_reenq_user);
4326 			dsq = dsq_pcpu->dsq;
4327 			reenq_flags = dru->flags;
4328 			WRITE_ONCE(dru->flags, 0);
4329 			list_del_init(&dru->node);
4330 		}
4331 
4332 		/* see schedule_dsq_reenq() */
4333 		smp_mb();
4334 
4335 		BUG_ON(dsq->id & SCX_DSQ_FLAG_BUILTIN);
4336 		reenq_user(rq, dsq, reenq_flags);
4337 	}
4338 }
4339 
4340 static void run_deferred(struct rq *rq)
4341 {
4342 	process_ddsp_deferred_locals(rq);
4343 
4344 	if (!list_empty(&rq->scx.deferred_reenq_locals))
4345 		process_deferred_reenq_locals(rq);
4346 
4347 	if (!list_empty(&rq->scx.deferred_reenq_users))
4348 		process_deferred_reenq_users(rq);
4349 }
4350 
4351 #ifdef CONFIG_NO_HZ_FULL
4352 bool scx_can_stop_tick(struct rq *rq)
4353 {
4354 	struct task_struct *p = rq->curr;
4355 	struct scx_sched *sch = scx_task_sched(p);
4356 
4357 	if (p->sched_class != &ext_sched_class)
4358 		return true;
4359 
4360 	/*
4361 	 * @rq->curr may still reference an outgoing EXT task after it has been
4362 	 * dequeued. If no EXT tasks are accounted on @rq, ignore its stale
4363 	 * slice state. If another task is dispatched from a DSQ,
4364 	 * set_next_task_scx() will update the dependency for the incoming task.
4365 	 */
4366 	if (!rq->scx.nr_running)
4367 		return true;
4368 
4369 	if (scx_bypassing(sch, cpu_of(rq)))
4370 		return false;
4371 
4372 	/*
4373 	 * @rq can dispatch from different DSQs, so we can't tell whether it
4374 	 * needs the tick or not by looking at nr_running. Allow stopping ticks
4375 	 * iff the BPF scheduler indicated so. See set_next_task_scx().
4376 	 */
4377 	return rq->scx.flags & SCX_RQ_CAN_STOP_TICK;
4378 }
4379 #endif
4380 
4381 #ifdef CONFIG_EXT_GROUP_SCHED
4382 
4383 DEFINE_STATIC_PERCPU_RWSEM(scx_cgroup_ops_rwsem);
4384 static bool scx_cgroup_enabled;
4385 
4386 void scx_tg_init(struct task_group *tg)
4387 {
4388 	tg->scx.weight = CGROUP_WEIGHT_DFL;
4389 	tg->scx.bw_period_us = default_bw_period_us();
4390 	tg->scx.bw_quota_us = RUNTIME_INF;
4391 	tg->scx.idle = false;
4392 }
4393 
4394 int scx_tg_online(struct task_group *tg)
4395 {
4396 	struct scx_sched *sch = scx_root;
4397 	int ret = 0;
4398 
4399 	WARN_ON_ONCE(tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED));
4400 
4401 	if (scx_cgroup_enabled) {
4402 		if (SCX_HAS_OP(sch, cgroup_init)) {
4403 			struct scx_cgroup_init_args args =
4404 				{ .weight = tg->scx.weight,
4405 				  .bw_period_us = tg->scx.bw_period_us,
4406 				  .bw_quota_us = tg->scx.bw_quota_us,
4407 				  .bw_burst_us = tg->scx.bw_burst_us };
4408 
4409 			ret = SCX_CALL_OP_RET(sch, cgroup_init,
4410 					      NULL, tg->css.cgroup, &args);
4411 			if (ret)
4412 				ret = ops_sanitize_err(sch, "cgroup_init", ret);
4413 		}
4414 		if (ret == 0)
4415 			tg->scx.flags |= SCX_TG_ONLINE | SCX_TG_INITED;
4416 	} else {
4417 		tg->scx.flags |= SCX_TG_ONLINE;
4418 	}
4419 
4420 	return ret;
4421 }
4422 
4423 void scx_tg_offline(struct task_group *tg)
4424 {
4425 	struct scx_sched *sch = scx_root;
4426 
4427 	WARN_ON_ONCE(!(tg->scx.flags & SCX_TG_ONLINE));
4428 
4429 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_exit) &&
4430 	    (tg->scx.flags & SCX_TG_INITED))
4431 		SCX_CALL_OP(sch, cgroup_exit, NULL, tg->css.cgroup);
4432 	tg->scx.flags &= ~(SCX_TG_ONLINE | SCX_TG_INITED);
4433 }
4434 
4435 int scx_cgroup_can_attach(struct cgroup_taskset *tset)
4436 {
4437 	struct scx_sched *sch = scx_root;
4438 	struct cgroup_subsys_state *css;
4439 	struct task_struct *p;
4440 	int ret;
4441 
4442 	if (!scx_cgroup_enabled)
4443 		return 0;
4444 
4445 	cgroup_taskset_for_each(p, css, tset) {
4446 		struct cgroup *from = tg_cgrp(task_group(p));
4447 		struct cgroup *to = tg_cgrp(css_tg(css));
4448 
4449 		WARN_ON_ONCE(p->scx.cgrp_moving_from);
4450 
4451 		/*
4452 		 * sched_move_task() omits identity migrations. Let's match the
4453 		 * behavior so that ops.cgroup_prep_move() and ops.cgroup_move()
4454 		 * always match one-to-one.
4455 		 */
4456 		if (from == to)
4457 			continue;
4458 
4459 		if (SCX_HAS_OP(sch, cgroup_prep_move)) {
4460 			ret = SCX_CALL_OP_RET(sch, cgroup_prep_move, NULL,
4461 					      p, from, css->cgroup);
4462 			if (ret)
4463 				goto err;
4464 		}
4465 
4466 		p->scx.cgrp_moving_from = from;
4467 	}
4468 
4469 	return 0;
4470 
4471 err:
4472 	cgroup_taskset_for_each(p, css, tset) {
4473 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
4474 		    p->scx.cgrp_moving_from)
4475 			SCX_CALL_OP(sch, cgroup_cancel_move, NULL,
4476 				    p, p->scx.cgrp_moving_from, css->cgroup);
4477 		p->scx.cgrp_moving_from = NULL;
4478 	}
4479 
4480 	return ops_sanitize_err(sch, "cgroup_prep_move", ret);
4481 }
4482 
4483 void scx_cgroup_move_task(struct task_struct *p)
4484 {
4485 	struct scx_sched *sch = scx_root;
4486 
4487 	if (!scx_cgroup_enabled)
4488 		return;
4489 
4490 	/*
4491 	 * scx_cgroup_can_attach() sets cgrp_moving_from only when the task's
4492 	 * cgroup changes. Migration keys off css rather than cgroup identity,
4493 	 * so it can hand an unchanged-cgroup task here with cgrp_moving_from
4494 	 * NULL. Nothing to report to the BPF scheduler then, so skip it and
4495 	 * keep prep_move and move paired.
4496 	 */
4497 	if (SCX_HAS_OP(sch, cgroup_move) && p->scx.cgrp_moving_from)
4498 		SCX_CALL_OP_TASK(sch, cgroup_move, task_rq(p),
4499 				 p, p->scx.cgrp_moving_from,
4500 				 tg_cgrp(task_group(p)));
4501 	p->scx.cgrp_moving_from = NULL;
4502 }
4503 
4504 void scx_cgroup_cancel_attach(struct cgroup_taskset *tset)
4505 {
4506 	struct scx_sched *sch = scx_root;
4507 	struct cgroup_subsys_state *css;
4508 	struct task_struct *p;
4509 
4510 	if (!scx_cgroup_enabled)
4511 		return;
4512 
4513 	cgroup_taskset_for_each(p, css, tset) {
4514 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
4515 		    p->scx.cgrp_moving_from)
4516 			SCX_CALL_OP(sch, cgroup_cancel_move, NULL,
4517 				    p, p->scx.cgrp_moving_from, css->cgroup);
4518 		p->scx.cgrp_moving_from = NULL;
4519 	}
4520 }
4521 
4522 void scx_group_set_weight(struct task_group *tg, unsigned long weight)
4523 {
4524 	struct scx_sched *sch;
4525 
4526 	percpu_down_read(&scx_cgroup_ops_rwsem);
4527 	sch = scx_root;
4528 
4529 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_weight) &&
4530 	    tg->scx.weight != weight)
4531 		SCX_CALL_OP(sch, cgroup_set_weight, NULL, tg_cgrp(tg), weight);
4532 
4533 	tg->scx.weight = weight;
4534 
4535 	percpu_up_read(&scx_cgroup_ops_rwsem);
4536 }
4537 
4538 void scx_group_set_idle(struct task_group *tg, bool idle)
4539 {
4540 	struct scx_sched *sch;
4541 
4542 	percpu_down_read(&scx_cgroup_ops_rwsem);
4543 	sch = scx_root;
4544 
4545 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_idle))
4546 		SCX_CALL_OP(sch, cgroup_set_idle, NULL, tg_cgrp(tg), idle);
4547 
4548 	/* Update the task group's idle state */
4549 	tg->scx.idle = idle;
4550 
4551 	percpu_up_read(&scx_cgroup_ops_rwsem);
4552 }
4553 
4554 void scx_group_set_bandwidth(struct task_group *tg,
4555 			     u64 period_us, u64 quota_us, u64 burst_us)
4556 {
4557 	struct scx_sched *sch;
4558 
4559 	percpu_down_read(&scx_cgroup_ops_rwsem);
4560 	sch = scx_root;
4561 
4562 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_bandwidth) &&
4563 	    (tg->scx.bw_period_us != period_us ||
4564 	     tg->scx.bw_quota_us != quota_us ||
4565 	     tg->scx.bw_burst_us != burst_us))
4566 		SCX_CALL_OP(sch, cgroup_set_bandwidth, NULL,
4567 			    tg_cgrp(tg), period_us, quota_us, burst_us);
4568 
4569 	tg->scx.bw_period_us = period_us;
4570 	tg->scx.bw_quota_us = quota_us;
4571 	tg->scx.bw_burst_us = burst_us;
4572 
4573 	percpu_up_read(&scx_cgroup_ops_rwsem);
4574 }
4575 #endif	/* CONFIG_EXT_GROUP_SCHED */
4576 
4577 #if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED)
4578 static struct cgroup *root_cgroup(void)
4579 {
4580 	return &cgrp_dfl_root.cgrp;
4581 }
4582 
4583 /*
4584  * cgroup_lock() must nest outside the rwsem write side: a writer waiting
4585  * for cgroup_mutex deadlocks with cgroup teardown, which holds it while
4586  * draining a set_* file write blocked on the rwsem behind the writer.
4587  */
4588 static void scx_cgroup_lock(void)
4589 {
4590 	cgroup_lock();
4591 #ifdef CONFIG_EXT_GROUP_SCHED
4592 	percpu_down_write(&scx_cgroup_ops_rwsem);
4593 #endif
4594 }
4595 
4596 static void scx_cgroup_unlock(void)
4597 {
4598 #ifdef CONFIG_EXT_GROUP_SCHED
4599 	percpu_up_write(&scx_cgroup_ops_rwsem);
4600 #endif
4601 	cgroup_unlock();
4602 }
4603 #else	/* CONFIG_EXT_GROUP_SCHED || CONFIG_EXT_SUB_SCHED */
4604 static inline struct cgroup *root_cgroup(void) { return NULL; }
4605 static inline void scx_cgroup_lock(void) {}
4606 static inline void scx_cgroup_unlock(void) {}
4607 #endif	/* CONFIG_EXT_GROUP_SCHED || CONFIG_EXT_SUB_SCHED */
4608 
4609 #ifdef CONFIG_EXT_SUB_SCHED
4610 static struct cgroup *sch_cgroup(struct scx_sched *sch)
4611 {
4612 	return sch->cgrp;
4613 }
4614 
4615 /* for each descendant of @cgrp including self, set ->scx_sched to @sch */
4616 static void set_cgroup_sched(struct cgroup *cgrp, struct scx_sched *sch)
4617 {
4618 	struct cgroup *pos;
4619 	struct cgroup_subsys_state *css;
4620 
4621 	cgroup_for_each_live_descendant_pre(pos, css, cgrp)
4622 		rcu_assign_pointer(pos->scx_sched, sch);
4623 }
4624 #else	/* CONFIG_EXT_SUB_SCHED */
4625 static inline struct cgroup *sch_cgroup(struct scx_sched *sch) { return NULL; }
4626 static inline void set_cgroup_sched(struct cgroup *cgrp, struct scx_sched *sch) {}
4627 #endif	/* CONFIG_EXT_SUB_SCHED */
4628 
4629 /*
4630  * Omitted operations:
4631  *
4632  * - migrate_task_rq: Unnecessary as task to cpu mapping is transient.
4633  *
4634  * - task_fork/dead: We need fork/dead notifications for all tasks regardless of
4635  *   their current sched_class. Call them directly from sched core instead.
4636  */
4637 DEFINE_SCHED_CLASS(ext) = {
4638 	.enqueue_task		= enqueue_task_scx,
4639 	.dequeue_task		= dequeue_task_scx,
4640 	.yield_task		= yield_task_scx,
4641 	.yield_to_task		= yield_to_task_scx,
4642 
4643 	.wakeup_preempt		= wakeup_preempt_scx,
4644 
4645 	.pick_task		= pick_task_scx,
4646 
4647 	.put_prev_task		= put_prev_task_scx,
4648 	.set_next_task		= set_next_task_scx,
4649 
4650 	.select_task_rq		= select_task_rq_scx,
4651 	.task_woken		= task_woken_scx,
4652 	.set_cpus_allowed	= set_cpus_allowed_scx,
4653 
4654 	.rq_online		= rq_online_scx,
4655 	.rq_offline		= rq_offline_scx,
4656 
4657 	.task_tick		= task_tick_scx,
4658 
4659 	.switching_to		= switching_to_scx,
4660 	.switched_from		= switched_from_scx,
4661 	.switched_to		= switched_to_scx,
4662 	.reweight_task		= reweight_task_scx,
4663 	.prio_changed		= prio_changed_scx,
4664 
4665 	.update_curr		= update_curr_scx,
4666 
4667 #ifdef CONFIG_UCLAMP_TASK
4668 	.uclamp_enabled		= 1,
4669 #endif
4670 };
4671 
4672 static s32 init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id,
4673 		    struct scx_sched *sch)
4674 {
4675 	s32 cpu;
4676 
4677 	memset(dsq, 0, sizeof(*dsq));
4678 
4679 	raw_spin_lock_init(&dsq->lock);
4680 	INIT_LIST_HEAD(&dsq->list);
4681 	dsq->id = dsq_id;
4682 	dsq->sched = sch;
4683 
4684 	dsq->pcpu = alloc_percpu(struct scx_dsq_pcpu);
4685 	if (!dsq->pcpu)
4686 		return -ENOMEM;
4687 
4688 	for_each_possible_cpu(cpu) {
4689 		struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu, cpu);
4690 
4691 		pcpu->dsq = dsq;
4692 		INIT_LIST_HEAD(&pcpu->deferred_reenq_user.node);
4693 	}
4694 
4695 	return 0;
4696 }
4697 
4698 static void exit_dsq(struct scx_dispatch_q *dsq)
4699 {
4700 	s32 cpu;
4701 
4702 	for_each_possible_cpu(cpu) {
4703 		struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu, cpu);
4704 		struct scx_deferred_reenq_user *dru = &pcpu->deferred_reenq_user;
4705 		struct rq *rq = cpu_rq(cpu);
4706 
4707 		/*
4708 		 * There must have been a RCU grace period since the last
4709 		 * insertion and @dsq should be off the deferred list by now.
4710 		 */
4711 		if (WARN_ON_ONCE(!list_empty(&dru->node))) {
4712 			guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
4713 			list_del_init(&dru->node);
4714 		}
4715 	}
4716 
4717 	free_percpu(dsq->pcpu);
4718 }
4719 
4720 static void free_dsq_rcufn(struct rcu_head *rcu)
4721 {
4722 	struct scx_dispatch_q *dsq = container_of(rcu, struct scx_dispatch_q, rcu);
4723 
4724 	exit_dsq(dsq);
4725 	kfree(dsq);
4726 }
4727 
4728 static void free_dsq_irq_workfn(struct irq_work *irq_work)
4729 {
4730 	struct llist_node *to_free = llist_del_all(&dsqs_to_free);
4731 	struct scx_dispatch_q *dsq, *tmp_dsq;
4732 
4733 	llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node)
4734 		call_rcu(&dsq->rcu, free_dsq_rcufn);
4735 }
4736 
4737 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn);
4738 
4739 static void destroy_dsq(struct scx_sched *sch, u64 dsq_id)
4740 {
4741 	struct scx_dispatch_q *dsq;
4742 	unsigned long flags;
4743 
4744 	rcu_read_lock();
4745 
4746 	dsq = find_user_dsq(sch, dsq_id);
4747 	if (!dsq)
4748 		goto out_unlock_rcu;
4749 
4750 	raw_spin_lock_irqsave(&dsq->lock, flags);
4751 
4752 	if (dsq->nr) {
4753 		scx_error(sch, "attempting to destroy in-use dsq 0x%016llx (nr=%u)",
4754 			  dsq->id, dsq->nr);
4755 		goto out_unlock_dsq;
4756 	}
4757 
4758 	if (rhashtable_remove_fast(&sch->dsq_hash, &dsq->hash_node,
4759 				   dsq_hash_params))
4760 		goto out_unlock_dsq;
4761 
4762 	/*
4763 	 * Mark dead by invalidating ->id to prevent dispatch_enqueue() from
4764 	 * queueing more tasks. As this function can be called from anywhere,
4765 	 * freeing is bounced through an irq work to avoid nesting RCU
4766 	 * operations inside scheduler locks.
4767 	 */
4768 	dsq->id = SCX_DSQ_INVALID;
4769 	if (llist_add(&dsq->free_node, &dsqs_to_free))
4770 		irq_work_queue(&free_dsq_irq_work);
4771 
4772 out_unlock_dsq:
4773 	raw_spin_unlock_irqrestore(&dsq->lock, flags);
4774 out_unlock_rcu:
4775 	rcu_read_unlock();
4776 }
4777 
4778 #ifdef CONFIG_EXT_GROUP_SCHED
4779 static void scx_cgroup_exit(struct scx_sched *sch)
4780 {
4781 	struct cgroup_subsys_state *css;
4782 
4783 	scx_cgroup_enabled = false;
4784 
4785 	/*
4786 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
4787 	 * cgroups and exit all the inited ones, all online cgroups are exited.
4788 	 */
4789 	css_for_each_descendant_post(css, &root_task_group.css) {
4790 		struct task_group *tg = css_tg(css);
4791 
4792 		if (!(tg->scx.flags & SCX_TG_INITED))
4793 			continue;
4794 		tg->scx.flags &= ~SCX_TG_INITED;
4795 
4796 		if (!sch->ops.cgroup_exit)
4797 			continue;
4798 
4799 		SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup);
4800 	}
4801 }
4802 
4803 static int scx_cgroup_init(struct scx_sched *sch)
4804 {
4805 	struct cgroup_subsys_state *css;
4806 	int ret;
4807 
4808 	/*
4809 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
4810 	 * cgroups and init, all online cgroups are initialized.
4811 	 */
4812 	css_for_each_descendant_pre(css, &root_task_group.css) {
4813 		struct task_group *tg = css_tg(css);
4814 		struct scx_cgroup_init_args args = {
4815 			.weight = tg->scx.weight,
4816 			.bw_period_us = tg->scx.bw_period_us,
4817 			.bw_quota_us = tg->scx.bw_quota_us,
4818 			.bw_burst_us = tg->scx.bw_burst_us,
4819 		};
4820 
4821 		if ((tg->scx.flags &
4822 		     (SCX_TG_ONLINE | SCX_TG_INITED)) != SCX_TG_ONLINE)
4823 			continue;
4824 
4825 		if (!sch->ops.cgroup_init) {
4826 			tg->scx.flags |= SCX_TG_INITED;
4827 			continue;
4828 		}
4829 
4830 		ret = SCX_CALL_OP_RET(sch, cgroup_init, NULL,
4831 				      css->cgroup, &args);
4832 		if (ret) {
4833 			scx_error(sch, "ops.cgroup_init() failed (%d)", ret);
4834 			return ret;
4835 		}
4836 		tg->scx.flags |= SCX_TG_INITED;
4837 	}
4838 
4839 	WARN_ON_ONCE(scx_cgroup_enabled);
4840 	scx_cgroup_enabled = true;
4841 
4842 	return 0;
4843 }
4844 
4845 #else
4846 static void scx_cgroup_exit(struct scx_sched *sch) {}
4847 static int scx_cgroup_init(struct scx_sched *sch) { return 0; }
4848 #endif
4849 
4850 
4851 /********************************************************************************
4852  * Sysfs interface and ops enable/disable.
4853  */
4854 
4855 #define SCX_ATTR(_name)								\
4856 	static struct kobj_attribute scx_attr_##_name = {			\
4857 		.attr = { .name = __stringify(_name), .mode = 0444 },		\
4858 		.show = scx_attr_##_name##_show,				\
4859 	}
4860 
4861 static ssize_t scx_attr_state_show(struct kobject *kobj,
4862 				   struct kobj_attribute *ka, char *buf)
4863 {
4864 	return sysfs_emit(buf, "%s\n", scx_enable_state_str[scx_enable_state()]);
4865 }
4866 SCX_ATTR(state);
4867 
4868 static ssize_t scx_attr_switch_all_show(struct kobject *kobj,
4869 					struct kobj_attribute *ka, char *buf)
4870 {
4871 	return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all));
4872 }
4873 SCX_ATTR(switch_all);
4874 
4875 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj,
4876 					 struct kobj_attribute *ka, char *buf)
4877 {
4878 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected));
4879 }
4880 SCX_ATTR(nr_rejected);
4881 
4882 static ssize_t scx_attr_hotplug_seq_show(struct kobject *kobj,
4883 					 struct kobj_attribute *ka, char *buf)
4884 {
4885 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_hotplug_seq));
4886 }
4887 SCX_ATTR(hotplug_seq);
4888 
4889 static ssize_t scx_attr_enable_seq_show(struct kobject *kobj,
4890 					struct kobj_attribute *ka, char *buf)
4891 {
4892 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_enable_seq));
4893 }
4894 SCX_ATTR(enable_seq);
4895 
4896 static struct attribute *scx_global_attrs[] = {
4897 	&scx_attr_state.attr,
4898 	&scx_attr_switch_all.attr,
4899 	&scx_attr_nr_rejected.attr,
4900 	&scx_attr_hotplug_seq.attr,
4901 	&scx_attr_enable_seq.attr,
4902 	NULL,
4903 };
4904 
4905 static const struct attribute_group scx_global_attr_group = {
4906 	.attrs = scx_global_attrs,
4907 };
4908 
4909 static void free_pnode(struct scx_sched_pnode *pnode);
4910 static void free_exit_info(struct scx_exit_info *ei);
4911 
4912 static s32 scx_set_cmask_scratch_alloc(struct scx_sched *sch)
4913 {
4914 	size_t size = struct_size_t(struct scx_cmask, bits,
4915 				    SCX_CMASK_NR_WORDS(num_possible_cpus()));
4916 	int cpu;
4917 
4918 	if (!sch->is_cid_type || !sch->arena_pool)
4919 		return 0;
4920 
4921 	sch->set_cmask_scratch = alloc_percpu(struct scx_cmask *);
4922 	if (!sch->set_cmask_scratch)
4923 		return -ENOMEM;
4924 
4925 	for_each_possible_cpu(cpu) {
4926 		struct scx_cmask **slot = per_cpu_ptr(sch->set_cmask_scratch, cpu);
4927 
4928 		*slot = scx_arena_alloc(sch, size);
4929 		if (!*slot)
4930 			return -ENOMEM;
4931 		scx_cmask_init(*slot, 0, num_possible_cpus());
4932 	}
4933 	return 0;
4934 }
4935 
4936 static void scx_set_cmask_scratch_free(struct scx_sched *sch)
4937 {
4938 	size_t size = struct_size_t(struct scx_cmask, bits,
4939 				    SCX_CMASK_NR_WORDS(num_possible_cpus()));
4940 	int cpu;
4941 
4942 	if (!sch->set_cmask_scratch)
4943 		return;
4944 
4945 	for_each_possible_cpu(cpu) {
4946 		struct scx_cmask **slot = per_cpu_ptr(sch->set_cmask_scratch, cpu);
4947 
4948 		scx_arena_free(sch, *slot, size);
4949 	}
4950 	free_percpu(sch->set_cmask_scratch);
4951 	sch->set_cmask_scratch = NULL;
4952 }
4953 
4954 static void scx_sched_free_rcu_work(struct work_struct *work)
4955 {
4956 	struct rcu_work *rcu_work = to_rcu_work(work);
4957 	struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work);
4958 	struct rhashtable_iter rht_iter;
4959 	struct scx_dispatch_q *dsq;
4960 	int cpu, node;
4961 
4962 	irq_work_sync(&sch->disable_irq_work);
4963 	kthread_destroy_worker(sch->helper);
4964 	timer_shutdown_sync(&sch->bypass_lb_timer);
4965 	free_cpumask_var(sch->bypass_lb_donee_cpumask);
4966 	free_cpumask_var(sch->bypass_lb_resched_cpumask);
4967 
4968 #ifdef CONFIG_EXT_SUB_SCHED
4969 	kfree(sch->cgrp_path);
4970 	if (sch_cgroup(sch))
4971 		cgroup_put(sch_cgroup(sch));
4972 	if (sch->sub_kset)
4973 		kobject_put(&sch->sub_kset->kobj);
4974 	if (scx_parent(sch))
4975 		kobject_put(&scx_parent(sch)->kobj);
4976 #endif	/* CONFIG_EXT_SUB_SCHED */
4977 
4978 	for_each_possible_cpu(cpu) {
4979 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
4980 
4981 		/*
4982 		 * $sch would have entered bypass mode before the RCU grace
4983 		 * period. As that blocks new deferrals, all
4984 		 * deferred_reenq_local_node's must be off-list by now.
4985 		 */
4986 		WARN_ON_ONCE(!list_empty(&pcpu->deferred_reenq_local.node));
4987 
4988 		exit_dsq(bypass_dsq(sch, cpu));
4989 	}
4990 
4991 	free_percpu(sch->pcpu);
4992 
4993 	for_each_node_state(node, N_POSSIBLE)
4994 		free_pnode(sch->pnode[node]);
4995 	kfree(sch->pnode);
4996 
4997 	rhashtable_walk_enter(&sch->dsq_hash, &rht_iter);
4998 	do {
4999 		rhashtable_walk_start(&rht_iter);
5000 
5001 		while (!IS_ERR_OR_NULL((dsq = rhashtable_walk_next(&rht_iter))))
5002 			destroy_dsq(sch, dsq->id);
5003 
5004 		rhashtable_walk_stop(&rht_iter);
5005 	} while (dsq == ERR_PTR(-EAGAIN));
5006 	rhashtable_walk_exit(&rht_iter);
5007 
5008 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
5009 	free_exit_info(sch->exit_info);
5010 	scx_set_cmask_scratch_free(sch);
5011 	scx_arena_pool_destroy(sch);
5012 	if (sch->arena_map)
5013 		bpf_map_put(sch->arena_map);
5014 	kfree(sch);
5015 }
5016 
5017 static void scx_kobj_release(struct kobject *kobj)
5018 {
5019 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
5020 
5021 	INIT_RCU_WORK(&sch->rcu_work, scx_sched_free_rcu_work);
5022 	queue_rcu_work(system_dfl_wq, &sch->rcu_work);
5023 }
5024 
5025 static ssize_t scx_attr_ops_show(struct kobject *kobj,
5026 				 struct kobj_attribute *ka, char *buf)
5027 {
5028 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
5029 
5030 	return sysfs_emit(buf, "%s\n", sch->ops.name);
5031 }
5032 SCX_ATTR(ops);
5033 
5034 #define scx_attr_event_show(buf, at, events, kind) ({				\
5035 	sysfs_emit_at(buf, at, "%s %llu\n", #kind, (events)->kind);		\
5036 })
5037 
5038 static ssize_t scx_attr_events_show(struct kobject *kobj,
5039 				    struct kobj_attribute *ka, char *buf)
5040 {
5041 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
5042 	struct scx_event_stats events;
5043 	int at = 0;
5044 
5045 	scx_read_events(sch, &events);
5046 	at += scx_attr_event_show(buf, at, &events, SCX_EV_SELECT_CPU_FALLBACK);
5047 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
5048 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_KEEP_LAST);
5049 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_EXITING);
5050 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
5051 	at += scx_attr_event_show(buf, at, &events, SCX_EV_REENQ_IMMED);
5052 	at += scx_attr_event_show(buf, at, &events, SCX_EV_REENQ_LOCAL_REPEAT);
5053 	at += scx_attr_event_show(buf, at, &events, SCX_EV_REFILL_SLICE_DFL);
5054 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DURATION);
5055 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DISPATCH);
5056 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_ACTIVATE);
5057 	at += scx_attr_event_show(buf, at, &events, SCX_EV_INSERT_NOT_OWNED);
5058 	at += scx_attr_event_show(buf, at, &events, SCX_EV_SUB_BYPASS_DISPATCH);
5059 	return at;
5060 }
5061 SCX_ATTR(events);
5062 
5063 static struct attribute *scx_sched_attrs[] = {
5064 	&scx_attr_ops.attr,
5065 	&scx_attr_events.attr,
5066 	NULL,
5067 };
5068 ATTRIBUTE_GROUPS(scx_sched);
5069 
5070 static const struct kobj_type scx_ktype = {
5071 	.release = scx_kobj_release,
5072 	.sysfs_ops = &kobj_sysfs_ops,
5073 	.default_groups = scx_sched_groups,
5074 };
5075 
5076 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
5077 {
5078 	const struct scx_sched *sch;
5079 
5080 	/*
5081 	 * scx_uevent() can be reached by both scx_sched kobjects (scx_ktype)
5082 	 * and sub-scheduler kset kobjects (kset_ktype) through the parent
5083 	 * chain walk. Filter out the latter to avoid invalid casts.
5084 	 */
5085 	if (kobj->ktype != &scx_ktype)
5086 		return 0;
5087 
5088 	sch = container_of(kobj, struct scx_sched, kobj);
5089 
5090 	return add_uevent_var(env, "SCXOPS=%s", sch->ops.name);
5091 }
5092 
5093 static const struct kset_uevent_ops scx_uevent_ops = {
5094 	.uevent = scx_uevent,
5095 };
5096 
5097 /*
5098  * Used by sched_fork() and __setscheduler_prio() to pick the matching
5099  * sched_class. dl/rt are already handled.
5100  */
5101 bool task_should_scx(int policy)
5102 {
5103 	/* if disabled, nothing should be on it */
5104 	if (!scx_enabled())
5105 		return false;
5106 
5107 	/* scx is taking over all SCHED_OTHER and SCHED_EXT tasks */
5108 	if (READ_ONCE(scx_switching_all))
5109 		return true;
5110 
5111 	/*
5112 	 * scx is tearing down - keep new SCHED_EXT tasks out.
5113 	 *
5114 	 * Must come after scx_switching_all test, which serves as a proxy
5115 	 * for __scx_switched_all. While __scx_switched_all is set, we must
5116 	 * return true via the branch above: a fork routed to fair would
5117 	 * stall because next_active_class() skips fair.
5118 	 *
5119 	 * This can develop into a deadlock - scx holds scx_enable_mutex across
5120 	 * kthread_create() in scx_alloc_and_add_sched(); if the new kthread is
5121 	 * the stalled task, the disable path can never grab the mutex to clear
5122 	 * scx_switching_all.
5123 	 */
5124 	if (unlikely(scx_enable_state() == SCX_DISABLING))
5125 		return false;
5126 
5127 	return policy == SCHED_EXT;
5128 }
5129 
5130 bool scx_allow_ttwu_queue(const struct task_struct *p)
5131 {
5132 	struct scx_sched *sch;
5133 
5134 	if (!scx_enabled())
5135 		return true;
5136 
5137 	sch = scx_task_sched(p);
5138 	if (unlikely(!sch))
5139 		return true;
5140 
5141 	if (sch->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP)
5142 		return true;
5143 
5144 	if (unlikely(p->sched_class != &ext_sched_class))
5145 		return true;
5146 
5147 	return false;
5148 }
5149 
5150 /**
5151  * handle_lockup - sched_ext common lockup handler
5152  * @fmt: format string
5153  *
5154  * Called on system stall or lockup condition and initiates abort of sched_ext
5155  * if enabled, which may resolve the reported lockup.
5156  *
5157  * Returns %true if sched_ext is enabled and abort was initiated, which may
5158  * resolve the lockup. %false if sched_ext is not enabled or abort was already
5159  * initiated by someone else.
5160  */
5161 static __printf(1, 2) bool handle_lockup(const char *fmt, ...)
5162 {
5163 	struct scx_sched *sch;
5164 	va_list args;
5165 	bool ret;
5166 
5167 	guard(rcu)();
5168 
5169 	sch = rcu_dereference(scx_root);
5170 	if (unlikely(!sch))
5171 		return false;
5172 
5173 	switch (scx_enable_state()) {
5174 	case SCX_ENABLING:
5175 	case SCX_ENABLED:
5176 		va_start(args, fmt);
5177 		ret = scx_verror(sch, fmt, args);
5178 		va_end(args);
5179 		return ret;
5180 	default:
5181 		return false;
5182 	}
5183 }
5184 
5185 /**
5186  * scx_rcu_cpu_stall - sched_ext RCU CPU stall handler
5187  *
5188  * While there are various reasons why RCU CPU stalls can occur on a system
5189  * that may not be caused by the current BPF scheduler, try kicking out the
5190  * current scheduler in an attempt to recover the system to a good state before
5191  * issuing panics.
5192  *
5193  * Returns %true if sched_ext is enabled and abort was initiated, which may
5194  * resolve the reported RCU stall. %false if sched_ext is not enabled or someone
5195  * else already initiated abort.
5196  */
5197 bool scx_rcu_cpu_stall(void)
5198 {
5199 	return handle_lockup("RCU CPU stall detected!");
5200 }
5201 
5202 /**
5203  * scx_softlockup - sched_ext softlockup handler
5204  * @dur_s: number of seconds of CPU stuck due to soft lockup
5205  *
5206  * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can
5207  * live-lock the system by making many CPUs target the same DSQ to the point
5208  * where soft-lockup detection triggers. This function is called from
5209  * soft-lockup watchdog when the triggering point is close and tries to unjam
5210  * the system and aborting the BPF scheduler.
5211  */
5212 void scx_softlockup(u32 dur_s)
5213 {
5214 	if (!handle_lockup("soft lockup - CPU %d stuck for %us", smp_processor_id(), dur_s))
5215 		return;
5216 
5217 	printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU %d stuck for %us, disabling BPF scheduler\n",
5218 			smp_processor_id(), dur_s);
5219 }
5220 
5221 /*
5222  * scx_hardlockup() runs from NMI and eventually calls scx_claim_exit(),
5223  * which takes scx_sched_lock. scx_sched_lock isn't NMI-safe and grabbing
5224  * it from NMI context can lead to deadlocks. Defer via irq_work; the
5225  * disable path runs off irq_work anyway.
5226  */
5227 static atomic_t scx_hardlockup_cpu = ATOMIC_INIT(-1);
5228 
5229 static void scx_hardlockup_irq_workfn(struct irq_work *work)
5230 {
5231 	int cpu = atomic_xchg(&scx_hardlockup_cpu, -1);
5232 
5233 	if (cpu >= 0 && handle_lockup("hard lockup - CPU %d", cpu))
5234 		printk_deferred(KERN_ERR "sched_ext: Hard lockup - CPU %d, disabling BPF scheduler\n",
5235 				cpu);
5236 }
5237 
5238 static DEFINE_IRQ_WORK(scx_hardlockup_irq_work, scx_hardlockup_irq_workfn);
5239 
5240 /**
5241  * scx_hardlockup - sched_ext hardlockup handler
5242  *
5243  * A poorly behaving BPF scheduler can trigger hard lockup by e.g. putting
5244  * numerous affinitized tasks in a single queue and directing all CPUs at it.
5245  * Try kicking out the current scheduler in an attempt to recover the system to
5246  * a good state before taking more drastic actions.
5247  *
5248  * Queues an irq_work; the handle_lockup() call happens in IRQ context (see
5249  * scx_hardlockup_irq_workfn).
5250  *
5251  * Returns %true if sched_ext is enabled and the work was queued, %false
5252  * otherwise.
5253  */
5254 bool scx_hardlockup(int cpu)
5255 {
5256 	if (!rcu_access_pointer(scx_root))
5257 		return false;
5258 
5259 	atomic_cmpxchg(&scx_hardlockup_cpu, -1, cpu);
5260 	irq_work_queue(&scx_hardlockup_irq_work);
5261 	return true;
5262 }
5263 
5264 static u32 bypass_lb_cpu(struct scx_sched *sch, s32 donor,
5265 			 struct cpumask *donee_mask, struct cpumask *resched_mask,
5266 			 u32 nr_donor_target, u32 nr_donee_target)
5267 {
5268 	struct rq *donor_rq = cpu_rq(donor);
5269 	struct scx_dispatch_q *donor_dsq = bypass_dsq(sch, donor);
5270 	struct task_struct *p, *n;
5271 	struct scx_dsq_list_node cursor = INIT_DSQ_LIST_CURSOR(cursor, donor_dsq, 0);
5272 	s32 delta = READ_ONCE(donor_dsq->nr) - nr_donor_target;
5273 	u32 nr_balanced = 0, min_delta_us;
5274 
5275 	/*
5276 	 * All we want to guarantee is reasonable forward progress. No reason to
5277 	 * fine tune. Assuming every task on @donor_dsq runs their full slice,
5278 	 * consider offloading iff the total queued duration is over the
5279 	 * threshold.
5280 	 */
5281 	min_delta_us = READ_ONCE(scx_bypass_lb_intv_us) / SCX_BYPASS_LB_MIN_DELTA_DIV;
5282 	if (delta < DIV_ROUND_UP(min_delta_us, READ_ONCE(scx_slice_bypass_us)))
5283 		return 0;
5284 
5285 	raw_spin_rq_lock_irq(donor_rq);
5286 	raw_spin_lock(&donor_dsq->lock);
5287 	list_add(&cursor.node, &donor_dsq->list);
5288 resume:
5289 	n = container_of(&cursor, struct task_struct, scx.dsq_list);
5290 	n = nldsq_next_task(donor_dsq, n, false);
5291 
5292 	while ((p = n)) {
5293 		struct scx_dispatch_q *donee_dsq;
5294 		int donee;
5295 
5296 		n = nldsq_next_task(donor_dsq, n, false);
5297 
5298 		if (donor_dsq->nr <= nr_donor_target)
5299 			break;
5300 
5301 		if (cpumask_empty(donee_mask))
5302 			break;
5303 
5304 		/*
5305 		 * If an earlier pass placed @p on @donor_dsq from a different
5306 		 * CPU and the donee hasn't consumed it yet, @p is still on the
5307 		 * previous CPU and task_rq(@p) != @donor_rq. @p can't be moved
5308 		 * without its rq locked. Skip.
5309 		 */
5310 		if (task_rq(p) != donor_rq)
5311 			continue;
5312 
5313 		donee = cpumask_any_and_distribute(donee_mask, p->cpus_ptr);
5314 		if (donee >= nr_cpu_ids)
5315 			continue;
5316 
5317 		donee_dsq = bypass_dsq(sch, donee);
5318 
5319 		/*
5320 		 * $p's rq is not locked but $p's DSQ lock protects its
5321 		 * scheduling properties making this test safe.
5322 		 */
5323 		if (!task_can_run_on_remote_rq(sch, p, cpu_rq(donee), false))
5324 			continue;
5325 
5326 		/*
5327 		 * Moving $p from one non-local DSQ to another. The source rq
5328 		 * and DSQ are already locked. Do an abbreviated dequeue and
5329 		 * then perform enqueue without unlocking $donor_dsq.
5330 		 *
5331 		 * We don't want to drop and reacquire the lock on each
5332 		 * iteration as @donor_dsq can be very long and potentially
5333 		 * highly contended. Donee DSQs are less likely to be contended.
5334 		 * The nested locking is safe as only this LB moves tasks
5335 		 * between bypass DSQs.
5336 		 */
5337 		dispatch_dequeue_locked(p, donor_dsq);
5338 		dispatch_enqueue(sch, cpu_rq(donee), donee_dsq, p, SCX_ENQ_NESTED);
5339 
5340 		/*
5341 		 * $donee might have been idle and need to be woken up. No need
5342 		 * to be clever. Kick every CPU that receives tasks.
5343 		 */
5344 		cpumask_set_cpu(donee, resched_mask);
5345 
5346 		if (READ_ONCE(donee_dsq->nr) >= nr_donee_target)
5347 			cpumask_clear_cpu(donee, donee_mask);
5348 
5349 		nr_balanced++;
5350 		if (!(nr_balanced % SCX_BYPASS_LB_BATCH) && n) {
5351 			list_move_tail(&cursor.node, &n->scx.dsq_list.node);
5352 			raw_spin_unlock(&donor_dsq->lock);
5353 			raw_spin_rq_unlock_irq(donor_rq);
5354 			cpu_relax();
5355 			raw_spin_rq_lock_irq(donor_rq);
5356 			raw_spin_lock(&donor_dsq->lock);
5357 			goto resume;
5358 		}
5359 	}
5360 
5361 	list_del_init(&cursor.node);
5362 	raw_spin_unlock(&donor_dsq->lock);
5363 	raw_spin_rq_unlock_irq(donor_rq);
5364 
5365 	return nr_balanced;
5366 }
5367 
5368 static void bypass_lb_node(struct scx_sched *sch, int node)
5369 {
5370 	const struct cpumask *node_mask = cpumask_of_node(node);
5371 	struct cpumask *donee_mask = sch->bypass_lb_donee_cpumask;
5372 	struct cpumask *resched_mask = sch->bypass_lb_resched_cpumask;
5373 	u32 nr_tasks = 0, nr_cpus = 0, nr_balanced = 0;
5374 	u32 nr_target, nr_donor_target;
5375 	u32 before_min = U32_MAX, before_max = 0;
5376 	u32 after_min = U32_MAX, after_max = 0;
5377 	int cpu;
5378 
5379 	/* count the target tasks and CPUs */
5380 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5381 		u32 nr = READ_ONCE(bypass_dsq(sch, cpu)->nr);
5382 
5383 		nr_tasks += nr;
5384 		nr_cpus++;
5385 
5386 		before_min = min(nr, before_min);
5387 		before_max = max(nr, before_max);
5388 	}
5389 
5390 	if (!nr_cpus)
5391 		return;
5392 
5393 	/*
5394 	 * We don't want CPUs to have more than $nr_donor_target tasks and
5395 	 * balancing to fill donee CPUs upto $nr_target. Once targets are
5396 	 * calculated, find the donee CPUs.
5397 	 */
5398 	nr_target = DIV_ROUND_UP(nr_tasks, nr_cpus);
5399 	nr_donor_target = DIV_ROUND_UP(nr_target * SCX_BYPASS_LB_DONOR_PCT, 100);
5400 
5401 	cpumask_clear(donee_mask);
5402 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5403 		if (READ_ONCE(bypass_dsq(sch, cpu)->nr) < nr_target)
5404 			cpumask_set_cpu(cpu, donee_mask);
5405 	}
5406 
5407 	/* iterate !donee CPUs and see if they should be offloaded */
5408 	cpumask_clear(resched_mask);
5409 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5410 		if (cpumask_empty(donee_mask))
5411 			break;
5412 		if (cpumask_test_cpu(cpu, donee_mask))
5413 			continue;
5414 		if (READ_ONCE(bypass_dsq(sch, cpu)->nr) <= nr_donor_target)
5415 			continue;
5416 
5417 		nr_balanced += bypass_lb_cpu(sch, cpu, donee_mask, resched_mask,
5418 					     nr_donor_target, nr_target);
5419 	}
5420 
5421 	for_each_cpu(cpu, resched_mask)
5422 		resched_cpu(cpu);
5423 
5424 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
5425 		u32 nr = READ_ONCE(bypass_dsq(sch, cpu)->nr);
5426 
5427 		after_min = min(nr, after_min);
5428 		after_max = max(nr, after_max);
5429 
5430 	}
5431 
5432 	trace_sched_ext_bypass_lb(node, nr_cpus, nr_tasks, nr_balanced,
5433 				  before_min, before_max, after_min, after_max);
5434 }
5435 
5436 /*
5437  * In bypass mode, all tasks are put on the per-CPU bypass DSQs. If the machine
5438  * is over-saturated and the BPF scheduler skewed tasks into few CPUs, some
5439  * bypass DSQs can be overloaded. If there are enough tasks to saturate other
5440  * lightly loaded CPUs, such imbalance can lead to very high execution latency
5441  * on the overloaded CPUs and thus to hung tasks and RCU stalls. To avoid such
5442  * outcomes, a simple load balancing mechanism is implemented by the following
5443  * timer which runs periodically while bypass mode is in effect.
5444  */
5445 static void scx_bypass_lb_timerfn(struct timer_list *timer)
5446 {
5447 	struct scx_sched *sch = container_of(timer, struct scx_sched, bypass_lb_timer);
5448 	int node;
5449 	u32 intv_us;
5450 
5451 	if (!bypass_dsp_enabled(sch))
5452 		return;
5453 
5454 	for_each_node_with_cpus(node)
5455 		bypass_lb_node(sch, node);
5456 
5457 	intv_us = READ_ONCE(scx_bypass_lb_intv_us);
5458 	if (intv_us)
5459 		mod_timer(timer, jiffies + usecs_to_jiffies(intv_us));
5460 }
5461 
5462 static bool inc_bypass_depth(struct scx_sched *sch)
5463 {
5464 	lockdep_assert_held(&scx_bypass_lock);
5465 
5466 	WARN_ON_ONCE(sch->bypass_depth < 0);
5467 	WRITE_ONCE(sch->bypass_depth, sch->bypass_depth + 1);
5468 	if (sch->bypass_depth != 1)
5469 		return false;
5470 
5471 	WRITE_ONCE(sch->slice_dfl, READ_ONCE(scx_slice_bypass_us) * NSEC_PER_USEC);
5472 	sch->bypass_timestamp = ktime_get_ns();
5473 	scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1);
5474 	return true;
5475 }
5476 
5477 static bool dec_bypass_depth(struct scx_sched *sch)
5478 {
5479 	lockdep_assert_held(&scx_bypass_lock);
5480 
5481 	WARN_ON_ONCE(sch->bypass_depth < 1);
5482 	WRITE_ONCE(sch->bypass_depth, sch->bypass_depth - 1);
5483 	if (sch->bypass_depth != 0)
5484 		return false;
5485 
5486 	WRITE_ONCE(sch->slice_dfl, SCX_SLICE_DFL);
5487 	scx_add_event(sch, SCX_EV_BYPASS_DURATION,
5488 		      ktime_get_ns() - sch->bypass_timestamp);
5489 	return true;
5490 }
5491 
5492 static void enable_bypass_dsp(struct scx_sched *sch)
5493 {
5494 	struct scx_sched *host = scx_parent(sch) ?: sch;
5495 	u32 intv_us = READ_ONCE(scx_bypass_lb_intv_us);
5496 	s32 ret;
5497 
5498 	/*
5499 	 * @sch->bypass_depth transitioning from 0 to 1 triggers enabling.
5500 	 * Shouldn't stagger.
5501 	 */
5502 	if (WARN_ON_ONCE(test_and_set_bit(0, &sch->bypass_dsp_claim)))
5503 		return;
5504 
5505 	/*
5506 	 * When a sub-sched bypasses, its tasks are queued on the bypass DSQs of
5507 	 * the nearest non-bypassing ancestor or root. As enable_bypass_dsp() is
5508 	 * called iff @sch is not already bypassed due to an ancestor bypassing,
5509 	 * we can assume that the parent is not bypassing and thus will be the
5510 	 * host of the bypass DSQs.
5511 	 *
5512 	 * While the situation may change in the future, the following
5513 	 * guarantees that the nearest non-bypassing ancestor or root has bypass
5514 	 * dispatch enabled while a descendant is bypassing, which is all that's
5515 	 * required.
5516 	 *
5517 	 * bypass_dsp_enabled() test is used to determine whether to enter the
5518 	 * bypass dispatch handling path from both bypassing and hosting scheds.
5519 	 * Bump enable depth on both @sch and bypass dispatch host.
5520 	 */
5521 	ret = atomic_inc_return(&sch->bypass_dsp_enable_depth);
5522 	WARN_ON_ONCE(ret <= 0);
5523 
5524 	if (host != sch) {
5525 		ret = atomic_inc_return(&host->bypass_dsp_enable_depth);
5526 		WARN_ON_ONCE(ret <= 0);
5527 	}
5528 
5529 	/*
5530 	 * The LB timer will stop running if bypass dispatch is disabled. Start
5531 	 * after enabling bypass dispatch.
5532 	 */
5533 	if (intv_us && !timer_pending(&host->bypass_lb_timer))
5534 		mod_timer(&host->bypass_lb_timer,
5535 			  jiffies + usecs_to_jiffies(intv_us));
5536 }
5537 
5538 /* may be called without holding scx_bypass_lock */
5539 static void disable_bypass_dsp(struct scx_sched *sch)
5540 {
5541 	s32 ret;
5542 
5543 	if (!test_and_clear_bit(0, &sch->bypass_dsp_claim))
5544 		return;
5545 
5546 	ret = atomic_dec_return(&sch->bypass_dsp_enable_depth);
5547 	WARN_ON_ONCE(ret < 0);
5548 
5549 	if (scx_parent(sch)) {
5550 		ret = atomic_dec_return(&scx_parent(sch)->bypass_dsp_enable_depth);
5551 		WARN_ON_ONCE(ret < 0);
5552 	}
5553 }
5554 
5555 /**
5556  * scx_bypass - [Un]bypass scx_ops and guarantee forward progress
5557  * @sch: sched to bypass
5558  * @bypass: true for bypass, false for unbypass
5559  *
5560  * Bypassing guarantees that all runnable tasks make forward progress without
5561  * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might
5562  * be held by tasks that the BPF scheduler is forgetting to run, which
5563  * unfortunately also excludes toggling the static branches.
5564  *
5565  * Let's work around by overriding a couple ops and modifying behaviors based on
5566  * the DISABLING state and then cycling the queued tasks through dequeue/enqueue
5567  * to force global FIFO scheduling.
5568  *
5569  * - ops.select_cpu() is ignored and the default select_cpu() is used.
5570  *
5571  * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order.
5572  *   %SCX_OPS_ENQ_LAST is also ignored.
5573  *
5574  * - ops.dispatch() is ignored.
5575  *
5576  * - balance_one() does not set %SCX_RQ_BAL_KEEP on non-zero slice as slice
5577  *   can't be trusted. Whenever a tick triggers, the running task is rotated to
5578  *   the tail of the queue with core_sched_at touched.
5579  *
5580  * - pick_next_task() suppresses zero slice warning.
5581  *
5582  * - scx_kick_cpu() is disabled to avoid irq_work malfunction during PM
5583  *   operations.
5584  *
5585  * - scx_prio_less() reverts to the default core_sched_at order.
5586  */
5587 static void scx_bypass(struct scx_sched *sch, bool bypass)
5588 {
5589 	struct scx_sched *pos;
5590 	unsigned long flags;
5591 	int cpu;
5592 
5593 	raw_spin_lock_irqsave(&scx_bypass_lock, flags);
5594 
5595 	if (bypass) {
5596 		if (!inc_bypass_depth(sch))
5597 			goto unlock;
5598 
5599 		enable_bypass_dsp(sch);
5600 	} else {
5601 		if (!dec_bypass_depth(sch))
5602 			goto unlock;
5603 	}
5604 
5605 	/*
5606 	 * Bypass state is propagated to all descendants - an scx_sched bypasses
5607 	 * if itself or any of its ancestors are in bypass mode.
5608 	 */
5609 	raw_spin_lock(&scx_sched_lock);
5610 	scx_for_each_descendant_pre(pos, sch) {
5611 		if (pos == sch)
5612 			continue;
5613 		if (bypass)
5614 			inc_bypass_depth(pos);
5615 		else
5616 			dec_bypass_depth(pos);
5617 	}
5618 	raw_spin_unlock(&scx_sched_lock);
5619 
5620 	/*
5621 	 * No task property is changing. We just need to make sure all currently
5622 	 * queued tasks are re-queued according to the new scx_bypassing()
5623 	 * state. As an optimization, walk each rq's runnable_list instead of
5624 	 * the scx_tasks list.
5625 	 *
5626 	 * This function can't trust the scheduler and thus can't use
5627 	 * cpus_read_lock(). Walk all possible CPUs instead of online.
5628 	 */
5629 	for_each_possible_cpu(cpu) {
5630 		struct rq *rq = cpu_rq(cpu);
5631 		struct task_struct *p, *n;
5632 
5633 		raw_spin_rq_lock(rq);
5634 		raw_spin_lock(&scx_sched_lock);
5635 
5636 		scx_for_each_descendant_pre(pos, sch) {
5637 			struct scx_sched_pcpu *pcpu = per_cpu_ptr(pos->pcpu, cpu);
5638 
5639 			if (pos->bypass_depth)
5640 				pcpu->flags |= SCX_SCHED_PCPU_BYPASSING;
5641 			else
5642 				pcpu->flags &= ~SCX_SCHED_PCPU_BYPASSING;
5643 		}
5644 
5645 		raw_spin_unlock(&scx_sched_lock);
5646 
5647 		/*
5648 		 * We need to guarantee that no tasks are on the BPF scheduler
5649 		 * while bypassing. Either we see enabled or the enable path
5650 		 * sees scx_bypassing() before moving tasks to SCX.
5651 		 */
5652 		if (!scx_enabled()) {
5653 			raw_spin_rq_unlock(rq);
5654 			continue;
5655 		}
5656 
5657 		/*
5658 		 * The use of list_for_each_entry_safe_reverse() is required
5659 		 * because each task is going to be removed from and added back
5660 		 * to the runnable_list during iteration. Because they're added
5661 		 * to the tail of the list, safe reverse iteration can still
5662 		 * visit all nodes.
5663 		 */
5664 		list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list,
5665 						 scx.runnable_node) {
5666 			if (!scx_is_descendant(scx_task_sched(p), sch))
5667 				continue;
5668 
5669 			/* cycling deq/enq is enough, see the function comment */
5670 			scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
5671 				/* nothing */ ;
5672 			}
5673 		}
5674 
5675 		/* resched to restore ticks and idle state */
5676 		if (cpu_online(cpu) || cpu == smp_processor_id())
5677 			resched_curr(rq);
5678 
5679 		raw_spin_rq_unlock(rq);
5680 	}
5681 
5682 	/* disarming must come after moving all tasks out of the bypass DSQs */
5683 	if (!bypass)
5684 		disable_bypass_dsp(sch);
5685 unlock:
5686 	raw_spin_unlock_irqrestore(&scx_bypass_lock, flags);
5687 }
5688 
5689 static void free_exit_info(struct scx_exit_info *ei)
5690 {
5691 	kvfree(ei->dump);
5692 	kfree(ei->msg);
5693 	kfree(ei->bt);
5694 	kfree(ei);
5695 }
5696 
5697 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
5698 {
5699 	struct scx_exit_info *ei;
5700 
5701 	ei = kzalloc_obj(*ei);
5702 	if (!ei)
5703 		return NULL;
5704 
5705 	ei->exit_cpu = -1;
5706 	ei->bt = kzalloc_objs(ei->bt[0], SCX_EXIT_BT_LEN);
5707 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
5708 	ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL);
5709 
5710 	if (!ei->bt || !ei->msg || !ei->dump) {
5711 		free_exit_info(ei);
5712 		return NULL;
5713 	}
5714 
5715 	return ei;
5716 }
5717 
5718 static const char *scx_exit_reason(enum scx_exit_kind kind)
5719 {
5720 	switch (kind) {
5721 	case SCX_EXIT_UNREG:
5722 		return "unregistered from user space";
5723 	case SCX_EXIT_UNREG_BPF:
5724 		return "unregistered from BPF";
5725 	case SCX_EXIT_UNREG_KERN:
5726 		return "unregistered from the main kernel";
5727 	case SCX_EXIT_SYSRQ:
5728 		return "disabled by sysrq-S";
5729 	case SCX_EXIT_PARENT:
5730 		return "parent exiting";
5731 	case SCX_EXIT_ERROR:
5732 		return "runtime error";
5733 	case SCX_EXIT_ERROR_BPF:
5734 		return "scx_bpf_error";
5735 	case SCX_EXIT_ERROR_STALL:
5736 		return "runnable task stall";
5737 	default:
5738 		return "<UNKNOWN>";
5739 	}
5740 }
5741 
5742 static void free_kick_syncs(void)
5743 {
5744 	int cpu;
5745 
5746 	for_each_possible_cpu(cpu) {
5747 		struct scx_kick_syncs __rcu **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
5748 		struct scx_kick_syncs *to_free;
5749 
5750 		to_free = rcu_replace_pointer(*ksyncs, NULL, true);
5751 		if (to_free)
5752 			kvfree_rcu(to_free, rcu);
5753 	}
5754 }
5755 
5756 static void refresh_watchdog(void)
5757 {
5758 	struct scx_sched *sch;
5759 	unsigned long intv = ULONG_MAX;
5760 
5761 	/* take the shortest timeout and use its half for watchdog interval */
5762 	rcu_read_lock();
5763 	list_for_each_entry_rcu(sch, &scx_sched_all, all)
5764 		intv = max(min(intv, sch->watchdog_timeout / 2), 1);
5765 	rcu_read_unlock();
5766 
5767 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
5768 	WRITE_ONCE(scx_watchdog_interval, intv);
5769 
5770 	if (intv < ULONG_MAX)
5771 		mod_delayed_work(system_dfl_wq, &scx_watchdog_work, intv);
5772 	else
5773 		cancel_delayed_work_sync(&scx_watchdog_work);
5774 }
5775 
5776 static s32 scx_link_sched(struct scx_sched *sch)
5777 {
5778 	const char *err_msg = "";
5779 	s32 ret = 0;
5780 
5781 	scoped_guard(raw_spinlock_irq, &scx_sched_lock) {
5782 #ifdef CONFIG_EXT_SUB_SCHED
5783 		struct scx_sched *parent = scx_parent(sch);
5784 
5785 		if (parent) {
5786 			/*
5787 			 * scx_claim_exit() propagates exit_kind transition to
5788 			 * its sub-scheds while holding scx_sched_lock - either
5789 			 * we can see the parent's non-NONE exit_kind or the
5790 			 * parent can shoot us down.
5791 			 */
5792 			if (atomic_read(&parent->exit_kind) != SCX_EXIT_NONE) {
5793 				err_msg = "parent disabled";
5794 				ret = -ENOENT;
5795 				break;
5796 			}
5797 
5798 			ret = rhashtable_lookup_insert_fast(&scx_sched_hash,
5799 					&sch->hash_node, scx_sched_hash_params);
5800 			if (ret) {
5801 				err_msg = "failed to insert into scx_sched_hash";
5802 				break;
5803 			}
5804 
5805 			list_add_tail(&sch->sibling, &parent->children);
5806 		}
5807 #endif	/* CONFIG_EXT_SUB_SCHED */
5808 
5809 		list_add_tail_rcu(&sch->all, &scx_sched_all);
5810 	}
5811 
5812 	/*
5813 	 * scx_error() takes scx_sched_lock via scx_claim_exit(), so it must run after
5814 	 * the guard above is released.
5815 	 */
5816 	if (ret) {
5817 		scx_error(sch, "%s (%d)", err_msg, ret);
5818 		return ret;
5819 	}
5820 
5821 	refresh_watchdog();
5822 	return 0;
5823 }
5824 
5825 static void scx_unlink_sched(struct scx_sched *sch)
5826 {
5827 	scoped_guard(raw_spinlock_irq, &scx_sched_lock) {
5828 #ifdef CONFIG_EXT_SUB_SCHED
5829 		if (scx_parent(sch)) {
5830 			rhashtable_remove_fast(&scx_sched_hash, &sch->hash_node,
5831 					       scx_sched_hash_params);
5832 			list_del_init(&sch->sibling);
5833 		}
5834 #endif	/* CONFIG_EXT_SUB_SCHED */
5835 		list_del_rcu(&sch->all);
5836 	}
5837 
5838 	refresh_watchdog();
5839 }
5840 
5841 /*
5842  * Called to disable future dumps and wait for in-progress one while disabling
5843  * @sch. Once @sch becomes empty during disable, there's no point in dumping it.
5844  * This prevents calling dump ops on a dead sch.
5845  */
5846 static void scx_disable_dump(struct scx_sched *sch)
5847 {
5848 	guard(raw_spinlock_irqsave)(&scx_dump_lock);
5849 	sch->dump_disabled = true;
5850 }
5851 
5852 static void scx_log_sched_disable(struct scx_sched *sch)
5853 {
5854 	struct scx_exit_info *ei = sch->exit_info;
5855 	const char *type = scx_parent(sch) ? "sub-scheduler" : "scheduler";
5856 
5857 	if (ei->kind >= SCX_EXIT_ERROR) {
5858 		pr_err("sched_ext: BPF %s \"%s\" disabled (%s)\n", type,
5859 		       sch->ops.name, ei->reason);
5860 
5861 		if (ei->msg[0] != '\0')
5862 			pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg);
5863 #ifdef CONFIG_STACKTRACE
5864 		stack_trace_print(ei->bt, ei->bt_len, 2);
5865 #endif
5866 	} else {
5867 		pr_info("sched_ext: BPF %s \"%s\" disabled (%s)\n", type,
5868 			sch->ops.name, ei->reason);
5869 	}
5870 }
5871 
5872 #ifdef CONFIG_EXT_SUB_SCHED
5873 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq);
5874 
5875 static void drain_descendants(struct scx_sched *sch)
5876 {
5877 	/*
5878 	 * Child scheds that finished the critical part of disabling will take
5879 	 * themselves off @sch->children. Wait for it to drain. As propagation
5880 	 * is recursive, empty @sch->children means that all proper descendant
5881 	 * scheds reached unlinking stage.
5882 	 */
5883 	wait_event(scx_unlink_waitq, list_empty(&sch->children));
5884 }
5885 
5886 static void scx_fail_parent(struct scx_sched *sch,
5887 			    struct task_struct *failed, s32 fail_code)
5888 {
5889 	struct scx_sched *parent = scx_parent(sch);
5890 	struct scx_task_iter sti;
5891 	struct task_struct *p;
5892 
5893 	scx_error(parent, "ops.init_task() failed (%d) for %s[%d] while disabling a sub-scheduler",
5894 		  fail_code, failed->comm, failed->pid);
5895 
5896 	/*
5897 	 * Once $parent is bypassed, it's safe to put SCX_TASK_NONE tasks into
5898 	 * it. This may cause downstream failures on the BPF side but $parent is
5899 	 * dying anyway.
5900 	 */
5901 	scx_bypass(parent, true);
5902 
5903 	scx_task_iter_start(&sti, sch->cgrp);
5904 	while ((p = scx_task_iter_next_locked(&sti))) {
5905 		if (scx_task_on_sched(parent, p))
5906 			continue;
5907 
5908 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
5909 			scx_disable_and_exit_task(sch, p);
5910 			scx_set_task_sched(p, parent);
5911 		}
5912 	}
5913 	scx_task_iter_stop(&sti);
5914 }
5915 
5916 static void scx_sub_disable(struct scx_sched *sch)
5917 {
5918 	struct scx_sched *parent = scx_parent(sch);
5919 	struct scx_task_iter sti;
5920 	struct task_struct *p;
5921 	int ret;
5922 
5923 	/*
5924 	 * Guarantee forward progress and wait for descendants to be disabled.
5925 	 * To limit disruptions, $parent is not bypassed. Tasks are fully
5926 	 * prepped and then inserted back into $parent.
5927 	 */
5928 	scx_bypass(sch, true);
5929 	drain_descendants(sch);
5930 
5931 	/*
5932 	 * Here, every runnable task is guaranteed to make forward progress and
5933 	 * we can safely use blocking synchronization constructs. Actually
5934 	 * disable ops.
5935 	 */
5936 	mutex_lock(&scx_enable_mutex);
5937 	percpu_down_write(&scx_fork_rwsem);
5938 	scx_cgroup_lock();
5939 
5940 	/*
5941 	 * An enable that failed before scx_link_sched() never owned a cgroup or
5942 	 * task and won't be waited on by an ancestor's drain_descendants().
5943 	 * Nothing to reparent and walking the tasks can misbehave as the task
5944 	 * ownership invariant (either owned by self or parent) does not hold.
5945 	 */
5946 	if (list_empty(&sch->sibling))
5947 		goto dump;
5948 
5949 	set_cgroup_sched(sch_cgroup(sch), parent);
5950 
5951 	scx_task_iter_start(&sti, sch->cgrp);
5952 	while ((p = scx_task_iter_next_locked(&sti))) {
5953 		struct rq *rq;
5954 		struct rq_flags rf;
5955 
5956 		/* filter out duplicate visits */
5957 		if (scx_task_on_sched(parent, p))
5958 			continue;
5959 
5960 		/*
5961 		 * By the time control reaches here, all linked descendant
5962 		 * schedulers should have been disabled.
5963 		 */
5964 		WARN_ON_ONCE(!scx_task_on_sched(sch, p));
5965 
5966 		/*
5967 		 * @p is pinned by the iter: css_task_iter_next() takes a
5968 		 * reference and holds it until the next iter_next() call, so
5969 		 * @p->usage is guaranteed > 0.
5970 		 */
5971 		get_task_struct(p);
5972 
5973 		scx_task_iter_unlock(&sti);
5974 
5975 		/*
5976 		 * $p is READY or ENABLED on @sch. Initialize for $parent,
5977 		 * disable and exit from @sch, and then switch over to $parent.
5978 		 *
5979 		 * If a task fails to initialize for $parent, the only available
5980 		 * action is disabling $parent too. While this allows disabling
5981 		 * of a child sched to cause the parent scheduler to fail, the
5982 		 * failure can only originate from ops.init_task() of the
5983 		 * parent. A child can't directly affect the parent through its
5984 		 * own failures.
5985 		 */
5986 		ret = __scx_init_task(parent, p, false);
5987 		if (ret) {
5988 			scx_fail_parent(sch, p, ret);
5989 			put_task_struct(p);
5990 			break;
5991 		}
5992 
5993 		rq = task_rq_lock(p, &rf);
5994 
5995 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
5996 			/*
5997 			 * sched_ext_dead() raced us between __scx_init_task()
5998 			 * and this rq lock and ran exit_task() on @sch (the
5999 			 * sched @p was on at that point), not on $parent.
6000 			 * $parent's just-completed init is owed an exit_task()
6001 			 * and we issue it here.
6002 			 */
6003 			scx_sub_init_cancel_task(parent, p);
6004 			task_rq_unlock(rq, p, &rf);
6005 			put_task_struct(p);
6006 			continue;
6007 		}
6008 
6009 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
6010 			/*
6011 			 * $p is initialized for $parent and still attached to
6012 			 * @sch. Disable and exit for @sch, switch over to
6013 			 * $parent and override the state to READY to account
6014 			 * for $p having already been initialized.
6015 			 */
6016 			scx_disable_and_exit_task(sch, p);
6017 			scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
6018 			scx_set_task_state(p, SCX_TASK_INIT);
6019 			scx_set_task_sched(p, parent);
6020 			scx_set_task_state(p, SCX_TASK_READY);
6021 
6022 			/*
6023 			 * A task on a non-ext class, possible under an
6024 			 * %SCX_OPS_SWITCH_PARTIAL root, stays READY and is
6025 			 * enabled by switching_to_scx() if it switches over.
6026 			 */
6027 			if (p->sched_class == &ext_sched_class)
6028 				scx_enable_task(parent, p);
6029 		}
6030 
6031 		task_rq_unlock(rq, p, &rf);
6032 		put_task_struct(p);
6033 	}
6034 	scx_task_iter_stop(&sti);
6035 
6036 dump:
6037 	scx_disable_dump(sch);
6038 
6039 	scx_cgroup_unlock();
6040 	percpu_up_write(&scx_fork_rwsem);
6041 
6042 	/*
6043 	 * All tasks are moved off of @sch but there may still be on-going
6044 	 * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use
6045 	 * the expedited version as ancestors may be waiting in bypass mode.
6046 	 * Also, tell the parent that there is no need to keep running bypass
6047 	 * DSQs for us.
6048 	 */
6049 	synchronize_rcu_expedited();
6050 	disable_bypass_dsp(sch);
6051 
6052 	scx_unlink_sched(sch);
6053 
6054 	mutex_unlock(&scx_enable_mutex);
6055 
6056 	/*
6057 	 * @sch is now unlinked from the parent's children list. Notify and call
6058 	 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called
6059 	 * after unlinking and releasing all locks. See scx_claim_exit().
6060 	 */
6061 	wake_up_all(&scx_unlink_waitq);
6062 
6063 	if (parent->ops.sub_detach && sch->sub_attached) {
6064 		struct scx_sub_detach_args sub_detach_args = {
6065 			.ops = &sch->ops,
6066 			.cgroup_path = sch->cgrp_path,
6067 		};
6068 		SCX_CALL_OP(parent, sub_detach, NULL,
6069 			    &sub_detach_args);
6070 	}
6071 
6072 	scx_log_sched_disable(sch);
6073 
6074 	if (sch->ops.exit)
6075 		SCX_CALL_OP(sch, exit, NULL, sch->exit_info);
6076 	if (sch->sub_kset)
6077 		kobject_del(&sch->sub_kset->kobj);
6078 	kobject_del(&sch->kobj);
6079 }
6080 #else	/* CONFIG_EXT_SUB_SCHED */
6081 static inline void drain_descendants(struct scx_sched *sch) { }
6082 static inline void scx_sub_disable(struct scx_sched *sch) { }
6083 #endif	/* CONFIG_EXT_SUB_SCHED */
6084 
6085 static void scx_root_disable(struct scx_sched *sch)
6086 {
6087 	struct scx_task_iter sti;
6088 	struct task_struct *p;
6089 	bool was_switched_all;
6090 	int cpu;
6091 
6092 	/* guarantee forward progress and wait for descendants to be disabled */
6093 	scx_bypass(sch, true);
6094 	drain_descendants(sch);
6095 
6096 	switch (scx_set_enable_state(SCX_DISABLING)) {
6097 	case SCX_DISABLING:
6098 		WARN_ONCE(true, "sched_ext: duplicate disabling instance?");
6099 		break;
6100 	case SCX_DISABLED:
6101 		pr_warn("sched_ext: ops error detected without ops (%s)\n",
6102 			sch->exit_info->msg);
6103 		WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
6104 		goto done;
6105 	default:
6106 		break;
6107 	}
6108 
6109 	/*
6110 	 * Here, every runnable task is guaranteed to make forward progress and
6111 	 * we can safely use blocking synchronization constructs. Actually
6112 	 * disable ops.
6113 	 */
6114 	mutex_lock(&scx_enable_mutex);
6115 
6116 	was_switched_all = scx_switched_all();
6117 
6118 	static_branch_disable(&__scx_switched_all);
6119 	WRITE_ONCE(scx_switching_all, false);
6120 
6121 	/*
6122 	 * Shut down cgroup support before tasks so that the cgroup attach path
6123 	 * doesn't race against scx_disable_and_exit_task().
6124 	 */
6125 	scx_cgroup_lock();
6126 	scx_cgroup_exit(sch);
6127 	scx_cgroup_unlock();
6128 
6129 	/*
6130 	 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones
6131 	 * must be switched out and exited synchronously.
6132 	 */
6133 	percpu_down_write(&scx_fork_rwsem);
6134 
6135 	scx_init_task_enabled = false;
6136 
6137 	scx_task_iter_start(&sti, NULL);
6138 	while ((p = scx_task_iter_next_locked(&sti))) {
6139 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
6140 		const struct sched_class *old_class = p->sched_class;
6141 		const struct sched_class *new_class = scx_setscheduler_class(p);
6142 
6143 		update_rq_clock(task_rq(p));
6144 
6145 		if (old_class != new_class)
6146 			queue_flags |= DEQUEUE_CLASS;
6147 
6148 		scoped_guard (sched_change, p, queue_flags) {
6149 			p->sched_class = new_class;
6150 		}
6151 
6152 		scx_disable_and_exit_task(scx_task_sched(p), p);
6153 	}
6154 	scx_task_iter_stop(&sti);
6155 
6156 	scx_disable_dump(sch);
6157 
6158 	scx_cgroup_lock();
6159 	set_cgroup_sched(sch_cgroup(sch), NULL);
6160 	scx_cgroup_unlock();
6161 
6162 	percpu_up_write(&scx_fork_rwsem);
6163 
6164 	/*
6165 	 * Invalidate all the rq clocks to prevent getting outdated
6166 	 * rq clocks from a previous scx scheduler.
6167 	 *
6168 	 * Also re-balance the dl_server bandwidth reservations: detach
6169 	 * ext_server (no more sched_ext tasks) and reinstate fair_server if it
6170 	 * was previously detached because we were running in full mode.
6171 	 *
6172 	 * Unlike the enable path, this runs on a recovery path that cannot
6173 	 * fail, so we use dl_server_swap_bw() to atomically free ext_server's
6174 	 * bandwidth and reclaim it for fair_server under the same dl_b lock.
6175 	 *
6176 	 * The swap can still fail with -EBUSY if someone bumped ext_server's
6177 	 * runtime via debugfs between enable and disable; in that narrow case
6178 	 * both servers end up detached and we just WARN.
6179 	 */
6180 	for_each_possible_cpu(cpu) {
6181 		struct rq *rq = cpu_rq(cpu);
6182 
6183 		scx_rq_clock_invalidate(rq);
6184 
6185 		scoped_guard(rq_lock_irqsave, rq) {
6186 			update_rq_clock(rq);
6187 			if (was_switched_all) {
6188 				if (WARN_ON_ONCE(dl_server_swap_bw(&rq->ext_server,
6189 								   &rq->fair_server)))
6190 					pr_warn("failed to re-attach fair_server on CPU %d\n", cpu);
6191 			} else {
6192 				dl_server_detach_bw(&rq->ext_server);
6193 			}
6194 		}
6195 	}
6196 
6197 	/* no task is on scx, turn off all the switches and flush in-progress calls */
6198 	static_branch_disable(&__scx_enabled);
6199 	static_branch_disable(&__scx_is_cid_type);
6200 	if (sch->ops.flags & SCX_OPS_TID_TO_TASK)
6201 		static_branch_disable(&__scx_tid_to_task_enabled);
6202 	bitmap_zero(sch->has_op, SCX_OPI_END);
6203 	scx_idle_disable();
6204 	synchronize_rcu();
6205 	if (sch->ops.flags & SCX_OPS_TID_TO_TASK)
6206 		rhashtable_free_and_destroy(&scx_tid_hash, NULL, NULL);
6207 
6208 	scx_log_sched_disable(sch);
6209 
6210 	if (sch->ops.exit)
6211 		SCX_CALL_OP(sch, exit, NULL, sch->exit_info);
6212 
6213 	scx_unlink_sched(sch);
6214 
6215 	/*
6216 	 * scx_root clearing must be inside cpus_read_lock(). See
6217 	 * handle_hotplug().
6218 	 */
6219 	cpus_read_lock();
6220 	RCU_INIT_POINTER(scx_root, NULL);
6221 	cpus_read_unlock();
6222 
6223 	/*
6224 	 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs
6225 	 * could observe an object of the same name still in the hierarchy when
6226 	 * the next scheduler is loaded.
6227 	 */
6228 #ifdef CONFIG_EXT_SUB_SCHED
6229 	if (sch->sub_kset)
6230 		kobject_del(&sch->sub_kset->kobj);
6231 #endif
6232 	kobject_del(&sch->kobj);
6233 
6234 	free_kick_syncs();
6235 
6236 	mutex_unlock(&scx_enable_mutex);
6237 
6238 	WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
6239 done:
6240 	scx_bypass(sch, false);
6241 }
6242 
6243 /*
6244  * Claim the exit on @sch. The caller must ensure that the helper kthread work
6245  * is kicked before the current task can be preempted. Once exit_kind is
6246  * claimed, scx_error() can no longer trigger, so if the current task gets
6247  * preempted and the BPF scheduler fails to schedule it back, the helper work
6248  * will never be kicked and the whole system can wedge.
6249  */
6250 static bool scx_claim_exit(struct scx_sched *sch, enum scx_exit_kind kind)
6251 {
6252 	int none = SCX_EXIT_NONE;
6253 
6254 	lockdep_assert_preemption_disabled();
6255 
6256 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
6257 		kind = SCX_EXIT_ERROR;
6258 
6259 	if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind))
6260 		return false;
6261 
6262 	/*
6263 	 * Some CPUs may be trapped in the dispatch paths. Set the aborting
6264 	 * flag to break potential live-lock scenarios, ensuring we can
6265 	 * successfully reach scx_bypass().
6266 	 */
6267 	WRITE_ONCE(sch->aborting, true);
6268 
6269 	/*
6270 	 * Propagate exits to descendants immediately. Each has a dedicated
6271 	 * helper kthread and can run in parallel. While most of disabling is
6272 	 * serialized, running them in separate threads allows parallelizing
6273 	 * ops.exit(), which can take arbitrarily long prolonging bypass mode.
6274 	 *
6275 	 * To guarantee forward progress, this propagation must be in-line so
6276 	 * that ->aborting is synchronously asserted for all sub-scheds. The
6277 	 * propagation is also the interlocking point against sub-sched
6278 	 * attachment. See scx_link_sched().
6279 	 *
6280 	 * This doesn't cause recursions as propagation only takes place for
6281 	 * non-propagation exits.
6282 	 */
6283 	if (kind != SCX_EXIT_PARENT) {
6284 		scoped_guard (raw_spinlock_irqsave, &scx_sched_lock) {
6285 			struct scx_sched *pos;
6286 			scx_for_each_descendant_pre(pos, sch)
6287 				scx_disable(pos, SCX_EXIT_PARENT);
6288 		}
6289 	}
6290 
6291 	return true;
6292 }
6293 
6294 static void scx_disable_workfn(struct kthread_work *work)
6295 {
6296 	struct scx_sched *sch = container_of(work, struct scx_sched, disable_work);
6297 	struct scx_exit_info *ei = sch->exit_info;
6298 	int kind;
6299 
6300 	kind = atomic_read(&sch->exit_kind);
6301 	while (true) {
6302 		if (kind == SCX_EXIT_DONE)	/* already disabled? */
6303 			return;
6304 		WARN_ON_ONCE(kind == SCX_EXIT_NONE);
6305 		if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE))
6306 			break;
6307 	}
6308 	ei->kind = kind;
6309 	ei->reason = scx_exit_reason(ei->kind);
6310 
6311 	if (scx_parent(sch))
6312 		scx_sub_disable(sch);
6313 	else
6314 		scx_root_disable(sch);
6315 }
6316 
6317 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind)
6318 {
6319 	guard(preempt)();
6320 	if (scx_claim_exit(sch, kind))
6321 		irq_work_queue(&sch->disable_irq_work);
6322 }
6323 
6324 /**
6325  * scx_flush_disable_work - flush the disable work and wait for it to finish
6326  * @sch: the scheduler
6327  *
6328  * sch->disable_work might still not queued, causing kthread_flush_work()
6329  * as a noop. Syncing the irq_work first is required to guarantee the
6330  * kthread work has been queued before waiting for it.
6331  */
6332 static void scx_flush_disable_work(struct scx_sched *sch)
6333 {
6334 	int kind;
6335 
6336 	do {
6337 		irq_work_sync(&sch->disable_irq_work);
6338 		kthread_flush_work(&sch->disable_work);
6339 		kind = atomic_read(&sch->exit_kind);
6340 	} while (kind != SCX_EXIT_NONE && kind != SCX_EXIT_DONE);
6341 }
6342 
6343 static void dump_newline(struct seq_buf *s)
6344 {
6345 	trace_sched_ext_dump("");
6346 
6347 	/* @s may be zero sized and seq_buf triggers WARN if so */
6348 	if (s->size)
6349 		seq_buf_putc(s, '\n');
6350 }
6351 
6352 static __printf(2, 3) void dump_line(struct seq_buf *s, const char *fmt, ...)
6353 {
6354 	va_list args;
6355 
6356 #ifdef CONFIG_TRACEPOINTS
6357 	if (trace_sched_ext_dump_enabled()) {
6358 		/* protected by scx_dump_lock */
6359 		static char line_buf[SCX_EXIT_MSG_LEN];
6360 
6361 		va_start(args, fmt);
6362 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
6363 		va_end(args);
6364 
6365 		trace_call__sched_ext_dump(line_buf);
6366 	}
6367 #endif
6368 	/* @s may be zero sized and seq_buf triggers WARN if so */
6369 	if (s->size) {
6370 		va_start(args, fmt);
6371 		seq_buf_vprintf(s, fmt, args);
6372 		va_end(args);
6373 
6374 		seq_buf_putc(s, '\n');
6375 	}
6376 }
6377 
6378 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
6379 			     const unsigned long *bt, unsigned int len)
6380 {
6381 	unsigned int i;
6382 
6383 	for (i = 0; i < len; i++)
6384 		dump_line(s, "%s%pS", prefix, (void *)bt[i]);
6385 }
6386 
6387 static void ops_dump_init(struct seq_buf *s, const char *prefix)
6388 {
6389 	struct scx_dump_data *dd = &scx_dump_data;
6390 
6391 	lockdep_assert_irqs_disabled();
6392 
6393 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
6394 	dd->first = true;
6395 	dd->cursor = 0;
6396 	dd->s = s;
6397 	dd->prefix = prefix;
6398 }
6399 
6400 static void ops_dump_flush(void)
6401 {
6402 	struct scx_dump_data *dd = &scx_dump_data;
6403 	char *line = dd->buf.line;
6404 
6405 	if (!dd->cursor)
6406 		return;
6407 
6408 	/*
6409 	 * There's something to flush and this is the first line. Insert a blank
6410 	 * line to distinguish ops dump.
6411 	 */
6412 	if (dd->first) {
6413 		dump_newline(dd->s);
6414 		dd->first = false;
6415 	}
6416 
6417 	/*
6418 	 * There may be multiple lines in $line. Scan and emit each line
6419 	 * separately.
6420 	 */
6421 	while (true) {
6422 		char *end = line;
6423 		char c;
6424 
6425 		while (*end != '\n' && *end != '\0')
6426 			end++;
6427 
6428 		/*
6429 		 * If $line overflowed, it may not have newline at the end.
6430 		 * Always emit with a newline.
6431 		 */
6432 		c = *end;
6433 		*end = '\0';
6434 		dump_line(dd->s, "%s%s", dd->prefix, line);
6435 		if (c == '\0')
6436 			break;
6437 
6438 		/* move to the next line */
6439 		end++;
6440 		if (*end == '\0')
6441 			break;
6442 		line = end;
6443 	}
6444 
6445 	dd->cursor = 0;
6446 }
6447 
6448 static void ops_dump_exit(void)
6449 {
6450 	ops_dump_flush();
6451 	scx_dump_data.cpu = -1;
6452 }
6453 
6454 static void scx_dump_task(struct scx_sched *sch, struct seq_buf *s, struct scx_dump_ctx *dctx,
6455 			  struct rq *rq, struct task_struct *p, char marker)
6456 {
6457 	static unsigned long bt[SCX_EXIT_BT_LEN];
6458 	struct scx_sched *task_sch = scx_task_sched(p);
6459 	const char *own_marker;
6460 	char sch_id_buf[32];
6461 	char dsq_id_buf[19] = "(n/a)";
6462 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
6463 	unsigned int bt_len = 0;
6464 
6465 	own_marker = task_sch == sch ? "*" : "";
6466 
6467 	if (task_sch->level == 0)
6468 		scnprintf(sch_id_buf, sizeof(sch_id_buf), "root");
6469 	else
6470 		scnprintf(sch_id_buf, sizeof(sch_id_buf), "sub%d-%llu",
6471 			  task_sch->level, task_sch->ops.sub_cgroup_id);
6472 
6473 	if (p->scx.dsq)
6474 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
6475 			  (unsigned long long)p->scx.dsq->id);
6476 
6477 	dump_newline(s);
6478 	dump_line(s, " %c%c %s[%d] %s%s %+ldms",
6479 		  marker, task_state_to_char(p), p->comm, p->pid,
6480 		  own_marker, sch_id_buf,
6481 		  jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
6482 	dump_line(s, "      scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu",
6483 		  scx_get_task_state(p) >> SCX_TASK_STATE_SHIFT,
6484 		  p->scx.flags & ~SCX_TASK_STATE_MASK,
6485 		  p->scx.dsq_flags, ops_state & SCX_OPSS_STATE_MASK,
6486 		  ops_state >> SCX_OPSS_QSEQ_SHIFT);
6487 	dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
6488 		  p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
6489 	dump_line(s, "      dsq_vtime=%llu slice=%llu weight=%u",
6490 		  p->scx.dsq_vtime, p->scx.slice, p->scx.weight);
6491 	dump_line(s, "      cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr),
6492 		  p->migration_disabled);
6493 
6494 	if (SCX_HAS_OP(sch, dump_task)) {
6495 		ops_dump_init(s, "    ");
6496 		SCX_CALL_OP(sch, dump_task, rq, dctx, p);
6497 		ops_dump_exit();
6498 	}
6499 
6500 #ifdef CONFIG_STACKTRACE
6501 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
6502 #endif
6503 	if (bt_len) {
6504 		dump_newline(s);
6505 		dump_stack_trace(s, "    ", bt, bt_len);
6506 	}
6507 }
6508 
6509 static void scx_dump_cpu(struct scx_sched *sch, struct seq_buf *s,
6510 			 struct scx_dump_ctx *dctx, int cpu,
6511 			 bool dump_all_tasks)
6512 {
6513 	struct rq *rq = cpu_rq(cpu);
6514 	struct rq_flags rf;
6515 	struct task_struct *p;
6516 	struct seq_buf ns;
6517 	size_t avail, used;
6518 	char *buf;
6519 	bool idle;
6520 
6521 	rq_lock_irqsave(rq, &rf);
6522 
6523 	idle = list_empty(&rq->scx.runnable_list) &&
6524 		rq->curr->sched_class == &idle_sched_class;
6525 
6526 	if (idle && !SCX_HAS_OP(sch, dump_cpu))
6527 		goto next;
6528 
6529 	/*
6530 	 * We don't yet know whether ops.dump_cpu() will produce output
6531 	 * and we may want to skip the default CPU dump if it doesn't.
6532 	 * Use a nested seq_buf to generate the standard dump so that we
6533 	 * can decide whether to commit later.
6534 	 */
6535 	avail = seq_buf_get_buf(s, &buf);
6536 	seq_buf_init(&ns, buf, avail);
6537 
6538 	dump_newline(&ns);
6539 	dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu ksync=%lu",
6540 		  cpu, rq->scx.nr_running, rq->scx.flags,
6541 		  rq->scx.cpu_released, rq->scx.ops_qseq,
6542 		  rq->scx.kick_sync);
6543 	dump_line(&ns, "          curr=%s[%d] class=%ps",
6544 		  rq->curr->comm, rq->curr->pid,
6545 		  rq->curr->sched_class);
6546 	if (!cpumask_empty(rq->scx.cpus_to_kick))
6547 		dump_line(&ns, "  cpus_to_kick   : %*pb",
6548 			  cpumask_pr_args(rq->scx.cpus_to_kick));
6549 	if (!cpumask_empty(rq->scx.cpus_to_kick_if_idle))
6550 		dump_line(&ns, "  idle_to_kick   : %*pb",
6551 			  cpumask_pr_args(rq->scx.cpus_to_kick_if_idle));
6552 	if (!cpumask_empty(rq->scx.cpus_to_preempt))
6553 		dump_line(&ns, "  cpus_to_preempt: %*pb",
6554 			  cpumask_pr_args(rq->scx.cpus_to_preempt));
6555 	if (!cpumask_empty(rq->scx.cpus_to_wait))
6556 		dump_line(&ns, "  cpus_to_wait   : %*pb",
6557 			  cpumask_pr_args(rq->scx.cpus_to_wait));
6558 	if (!cpumask_empty(rq->scx.cpus_to_sync))
6559 		dump_line(&ns, "  cpus_to_sync   : %*pb",
6560 			  cpumask_pr_args(rq->scx.cpus_to_sync));
6561 
6562 	used = seq_buf_used(&ns);
6563 	if (SCX_HAS_OP(sch, dump_cpu)) {
6564 		ops_dump_init(&ns, "  ");
6565 		SCX_CALL_OP(sch, dump_cpu, rq, dctx, scx_cpu_arg(cpu), idle);
6566 		ops_dump_exit();
6567 	}
6568 
6569 	/*
6570 	 * If idle && nothing generated by ops.dump_cpu(), there's
6571 	 * nothing interesting. Skip.
6572 	 */
6573 	if (idle && used == seq_buf_used(&ns))
6574 		goto next;
6575 
6576 	/*
6577 	 * $s may already have overflowed when $ns was created. If so,
6578 	 * calling commit on it will trigger BUG.
6579 	 */
6580 	if (avail) {
6581 		seq_buf_commit(s, seq_buf_used(&ns));
6582 		if (seq_buf_has_overflowed(&ns))
6583 			seq_buf_set_overflow(s);
6584 	}
6585 
6586 	if (rq->curr->sched_class == &ext_sched_class &&
6587 	    (dump_all_tasks || scx_task_on_sched(sch, rq->curr)))
6588 		scx_dump_task(sch, s, dctx, rq, rq->curr, '*');
6589 
6590 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
6591 		if (dump_all_tasks || scx_task_on_sched(sch, p))
6592 			scx_dump_task(sch, s, dctx, rq, p, ' ');
6593 next:
6594 	rq_unlock_irqrestore(rq, &rf);
6595 }
6596 
6597 /*
6598  * Dump scheduler state. If @dump_all_tasks is true, dump all tasks regardless
6599  * of which scheduler they belong to. If false, only dump tasks owned by @sch.
6600  * For SysRq-D dumps, @dump_all_tasks=false since all schedulers are dumped
6601  * separately. For error dumps, @dump_all_tasks=true since only the failing
6602  * scheduler is dumped.
6603  */
6604 static void scx_dump_state(struct scx_sched *sch, struct scx_exit_info *ei,
6605 			   size_t dump_len, bool dump_all_tasks)
6606 {
6607 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
6608 	struct scx_dump_ctx dctx = {
6609 		.kind = ei->kind,
6610 		.exit_code = ei->exit_code,
6611 		.reason = ei->reason,
6612 		.at_ns = ktime_get_ns(),
6613 		.at_jiffies = jiffies,
6614 	};
6615 	struct seq_buf s;
6616 	struct scx_event_stats events;
6617 	int cpu;
6618 
6619 	guard(raw_spinlock_irqsave)(&scx_dump_lock);
6620 
6621 	if (sch->dump_disabled)
6622 		return;
6623 
6624 	seq_buf_init(&s, ei->dump, dump_len);
6625 
6626 #ifdef CONFIG_EXT_SUB_SCHED
6627 	if (sch->level == 0)
6628 		dump_line(&s, "%s: root", sch->ops.name);
6629 	else
6630 		dump_line(&s, "%s: sub%d-%llu %s",
6631 			  sch->ops.name, sch->level, sch->ops.sub_cgroup_id,
6632 			  sch->cgrp_path);
6633 #endif
6634 	if (ei->kind == SCX_EXIT_NONE) {
6635 		dump_line(&s, "Debug dump triggered by %s", ei->reason);
6636 	} else {
6637 		if (ei->exit_cpu >= 0)
6638 			dump_line(&s, "%s[%d] triggered exit kind %d on CPU %d:",
6639 				  current->comm, current->pid, ei->kind,
6640 				  ei->exit_cpu);
6641 		else
6642 			dump_line(&s, "%s[%d] triggered exit kind %d:",
6643 				  current->comm, current->pid, ei->kind);
6644 		dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
6645 		dump_newline(&s);
6646 		dump_line(&s, "Backtrace:");
6647 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
6648 	}
6649 
6650 	if (SCX_HAS_OP(sch, dump)) {
6651 		ops_dump_init(&s, "");
6652 		SCX_CALL_OP(sch, dump, NULL, &dctx);
6653 		ops_dump_exit();
6654 	}
6655 
6656 	dump_newline(&s);
6657 	dump_line(&s, "CPU states");
6658 	dump_line(&s, "----------");
6659 
6660 	/*
6661 	 * Dump the exit CPU first so it isn't lost to dump truncation, then
6662 	 * walk the rest in order, skipping the one already dumped.
6663 	 */
6664 	if (ei->exit_cpu >= 0)
6665 		scx_dump_cpu(sch, &s, &dctx, ei->exit_cpu, dump_all_tasks);
6666 	for_each_possible_cpu(cpu) {
6667 		if (cpu != ei->exit_cpu)
6668 			scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks);
6669 	}
6670 
6671 	dump_newline(&s);
6672 	dump_line(&s, "Event counters");
6673 	dump_line(&s, "--------------");
6674 
6675 	scx_read_events(sch, &events);
6676 	scx_dump_event(s, &events, SCX_EV_SELECT_CPU_FALLBACK);
6677 	scx_dump_event(s, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
6678 	scx_dump_event(s, &events, SCX_EV_DISPATCH_KEEP_LAST);
6679 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_EXITING);
6680 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
6681 	scx_dump_event(s, &events, SCX_EV_REENQ_IMMED);
6682 	scx_dump_event(s, &events, SCX_EV_REENQ_LOCAL_REPEAT);
6683 	scx_dump_event(s, &events, SCX_EV_REFILL_SLICE_DFL);
6684 	scx_dump_event(s, &events, SCX_EV_BYPASS_DURATION);
6685 	scx_dump_event(s, &events, SCX_EV_BYPASS_DISPATCH);
6686 	scx_dump_event(s, &events, SCX_EV_BYPASS_ACTIVATE);
6687 	scx_dump_event(s, &events, SCX_EV_INSERT_NOT_OWNED);
6688 	scx_dump_event(s, &events, SCX_EV_SUB_BYPASS_DISPATCH);
6689 
6690 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
6691 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
6692 		       trunc_marker, sizeof(trunc_marker));
6693 }
6694 
6695 static void scx_disable_irq_workfn(struct irq_work *irq_work)
6696 {
6697 	struct scx_sched *sch = container_of(irq_work, struct scx_sched, disable_irq_work);
6698 	struct scx_exit_info *ei = sch->exit_info;
6699 
6700 	if (ei->kind >= SCX_EXIT_ERROR)
6701 		scx_dump_state(sch, ei, sch->ops.exit_dump_len, true);
6702 
6703 	kthread_queue_work(sch->helper, &sch->disable_work);
6704 }
6705 
6706 bool scx_vexit(struct scx_sched *sch,
6707 	       enum scx_exit_kind kind, s64 exit_code, s32 exit_cpu,
6708 	       const char *fmt, va_list args)
6709 {
6710 	struct scx_exit_info *ei = sch->exit_info;
6711 
6712 	guard(preempt)();
6713 
6714 	if (!scx_claim_exit(sch, kind))
6715 		return false;
6716 
6717 	ei->exit_code = exit_code;
6718 #ifdef CONFIG_STACKTRACE
6719 	if (kind >= SCX_EXIT_ERROR)
6720 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
6721 #endif
6722 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
6723 
6724 	/*
6725 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
6726 	 * in scx_disable_workfn().
6727 	 */
6728 	ei->kind = kind;
6729 	ei->reason = scx_exit_reason(ei->kind);
6730 	ei->exit_cpu = exit_cpu;
6731 
6732 	irq_work_queue(&sch->disable_irq_work);
6733 	return true;
6734 }
6735 
6736 static int alloc_kick_syncs(void)
6737 {
6738 	int cpu;
6739 
6740 	/*
6741 	 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size
6742 	 * can exceed percpu allocator limits on large machines.
6743 	 */
6744 	for_each_possible_cpu(cpu) {
6745 		struct scx_kick_syncs __rcu **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
6746 		struct scx_kick_syncs *new_ksyncs;
6747 
6748 		WARN_ON_ONCE(rcu_access_pointer(*ksyncs));
6749 
6750 		new_ksyncs = kvzalloc_node(struct_size(new_ksyncs, syncs, nr_cpu_ids),
6751 					   GFP_KERNEL, cpu_to_node(cpu));
6752 		if (!new_ksyncs) {
6753 			free_kick_syncs();
6754 			return -ENOMEM;
6755 		}
6756 
6757 		rcu_assign_pointer(*ksyncs, new_ksyncs);
6758 	}
6759 
6760 	return 0;
6761 }
6762 
6763 static void free_pnode(struct scx_sched_pnode *pnode)
6764 {
6765 	if (!pnode)
6766 		return;
6767 	exit_dsq(&pnode->global_dsq);
6768 	kfree(pnode);
6769 }
6770 
6771 static struct scx_sched_pnode *alloc_pnode(struct scx_sched *sch, int node)
6772 {
6773 	struct scx_sched_pnode *pnode;
6774 
6775 	pnode = kzalloc_node(sizeof(*pnode), GFP_KERNEL, node);
6776 	if (!pnode)
6777 		return NULL;
6778 
6779 	if (init_dsq(&pnode->global_dsq, SCX_DSQ_GLOBAL, sch)) {
6780 		kfree(pnode);
6781 		return NULL;
6782 	}
6783 
6784 	return pnode;
6785 }
6786 
6787 /*
6788  * scx_enable() is offloaded to a dedicated system-wide RT kthread to avoid
6789  * starvation. During the READY -> ENABLED task switching loop, the calling
6790  * thread's sched_class gets switched from fair to ext. As fair has higher
6791  * priority than ext, the calling thread can be indefinitely starved under
6792  * fair-class saturation, leading to a system hang.
6793  */
6794 struct scx_enable_cmd {
6795 	struct kthread_work	work;
6796 	union {
6797 		struct sched_ext_ops		*ops;
6798 		struct sched_ext_ops_cid	*ops_cid;
6799 	};
6800 	bool			is_cid_type;
6801 	struct bpf_map		*arena_map;	/* arena ref to transfer to sch */
6802 	int			ret;
6803 };
6804 
6805 /*
6806  * Allocate and initialize a new scx_sched. @cgrp's reference is always
6807  * consumed whether the function succeeds or fails.
6808  */
6809 static struct scx_sched *scx_alloc_and_add_sched(struct scx_enable_cmd *cmd,
6810 						 struct cgroup *cgrp,
6811 						 struct scx_sched *parent)
6812 {
6813 	struct sched_ext_ops *ops = cmd->ops;
6814 	struct scx_sched *sch;
6815 	s32 level = parent ? parent->level + 1 : 0;
6816 	s32 node, cpu, ret, bypass_fail_cpu = nr_cpu_ids;
6817 
6818 	sch = kzalloc_flex(*sch, ancestors, level + 1);
6819 	if (!sch) {
6820 		ret = -ENOMEM;
6821 		goto err_put_cgrp;
6822 	}
6823 
6824 	sch->exit_info = alloc_exit_info(ops->exit_dump_len);
6825 	if (!sch->exit_info) {
6826 		ret = -ENOMEM;
6827 		goto err_free_sch;
6828 	}
6829 
6830 	ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params);
6831 	if (ret < 0)
6832 		goto err_free_ei;
6833 
6834 	sch->pnode = kzalloc_objs(sch->pnode[0], nr_node_ids);
6835 	if (!sch->pnode) {
6836 		ret = -ENOMEM;
6837 		goto err_free_hash;
6838 	}
6839 
6840 	for_each_node_state(node, N_POSSIBLE) {
6841 		sch->pnode[node] = alloc_pnode(sch, node);
6842 		if (!sch->pnode[node]) {
6843 			ret = -ENOMEM;
6844 			goto err_free_pnode;
6845 		}
6846 	}
6847 
6848 	sch->dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
6849 	sch->pcpu = __alloc_percpu(struct_size_t(struct scx_sched_pcpu,
6850 						 dsp_ctx.buf, sch->dsp_max_batch),
6851 				   __alignof__(struct scx_sched_pcpu));
6852 	if (!sch->pcpu) {
6853 		ret = -ENOMEM;
6854 		goto err_free_pnode;
6855 	}
6856 
6857 	for_each_possible_cpu(cpu) {
6858 		ret = init_dsq(bypass_dsq(sch, cpu), SCX_DSQ_BYPASS, sch);
6859 		if (ret) {
6860 			bypass_fail_cpu = cpu;
6861 			goto err_free_pcpu;
6862 		}
6863 	}
6864 
6865 	for_each_possible_cpu(cpu) {
6866 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
6867 
6868 		pcpu->sch = sch;
6869 		INIT_LIST_HEAD(&pcpu->deferred_reenq_local.node);
6870 	}
6871 
6872 	sch->helper = kthread_run_worker(0, "sched_ext_helper");
6873 	if (IS_ERR(sch->helper)) {
6874 		ret = PTR_ERR(sch->helper);
6875 		goto err_free_pcpu;
6876 	}
6877 
6878 	sched_set_fifo(sch->helper->task);
6879 
6880 	if (parent)
6881 		memcpy(sch->ancestors, parent->ancestors,
6882 		       level * sizeof(parent->ancestors[0]));
6883 	sch->ancestors[level] = sch;
6884 	sch->level = level;
6885 
6886 	if (ops->timeout_ms)
6887 		sch->watchdog_timeout = msecs_to_jiffies(ops->timeout_ms);
6888 	else
6889 		sch->watchdog_timeout = SCX_WATCHDOG_MAX_TIMEOUT;
6890 
6891 	sch->slice_dfl = SCX_SLICE_DFL;
6892 	atomic_set(&sch->exit_kind, SCX_EXIT_NONE);
6893 	sch->disable_irq_work = IRQ_WORK_INIT_HARD(scx_disable_irq_workfn);
6894 	kthread_init_work(&sch->disable_work, scx_disable_workfn);
6895 	timer_setup(&sch->bypass_lb_timer, scx_bypass_lb_timerfn, 0);
6896 
6897 	if (!alloc_cpumask_var(&sch->bypass_lb_donee_cpumask, GFP_KERNEL)) {
6898 		ret = -ENOMEM;
6899 		goto err_stop_helper;
6900 	}
6901 	if (!alloc_cpumask_var(&sch->bypass_lb_resched_cpumask, GFP_KERNEL)) {
6902 		ret = -ENOMEM;
6903 		goto err_free_lb_cpumask;
6904 	}
6905 	/*
6906 	 * Copy ops through the right union view. For cid-form the source is
6907 	 * struct sched_ext_ops_cid which lacks the trailing cpu_acquire/
6908 	 * cpu_release; those stay zero from kzalloc.
6909 	 */
6910 	if (cmd->is_cid_type) {
6911 		sch->ops_cid = *cmd->ops_cid;
6912 		sch->is_cid_type = true;
6913 	} else {
6914 		sch->ops = *cmd->ops;
6915 	}
6916 
6917 #ifdef CONFIG_EXT_SUB_SCHED
6918 	char *buf = kzalloc(PATH_MAX, GFP_KERNEL);
6919 	if (!buf) {
6920 		ret = -ENOMEM;
6921 		goto err_free_lb_resched;
6922 	}
6923 	cgroup_path(cgrp, buf, PATH_MAX);
6924 	sch->cgrp_path = kstrdup(buf, GFP_KERNEL);
6925 	kfree(buf);
6926 	if (!sch->cgrp_path) {
6927 		ret = -ENOMEM;
6928 		goto err_free_lb_resched;
6929 	}
6930 
6931 	sch->cgrp = cgrp;
6932 	INIT_LIST_HEAD(&sch->children);
6933 	INIT_LIST_HEAD(&sch->sibling);
6934 #endif	/* CONFIG_EXT_SUB_SCHED */
6935 
6936 	/*
6937 	 * Publishing makes @sch visible to scx_prog_sched() readers. Failure
6938 	 * paths after this point must free @sch through kobject_put() whose
6939 	 * release path defers the actual freeing by an RCU grace period.
6940 	 */
6941 	rcu_assign_pointer(ops->priv, sch);
6942 
6943 	sch->kobj.kset = scx_kset;
6944 	INIT_LIST_HEAD(&sch->all);
6945 
6946 #ifdef CONFIG_EXT_SUB_SCHED
6947 	if (parent) {
6948 		/*
6949 		 * Pin @parent for @sch's lifetime. The kobject hierarchy pins
6950 		 * it only via @parent->sub_kset, which is dropped during
6951 		 * disable. Released in scx_sched_free_rcu_work().
6952 		 */
6953 		kobject_get(&parent->kobj);
6954 		ret = kobject_init_and_add(&sch->kobj, &scx_ktype,
6955 					   &parent->sub_kset->kobj,
6956 					   "sub-%llu", cgroup_id(cgrp));
6957 	} else {
6958 		ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root");
6959 	}
6960 
6961 	if (ret < 0) {
6962 		RCU_INIT_POINTER(ops->priv, NULL);
6963 		kobject_put(&sch->kobj);
6964 		return ERR_PTR(ret);
6965 	}
6966 
6967 	if (ops->sub_attach) {
6968 		sch->sub_kset = kset_create_and_add("sub", NULL, &sch->kobj);
6969 		if (!sch->sub_kset) {
6970 			RCU_INIT_POINTER(ops->priv, NULL);
6971 			kobject_put(&sch->kobj);
6972 			return ERR_PTR(-ENOMEM);
6973 		}
6974 	}
6975 #else	/* CONFIG_EXT_SUB_SCHED */
6976 	ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root");
6977 	if (ret < 0) {
6978 		RCU_INIT_POINTER(ops->priv, NULL);
6979 		kobject_put(&sch->kobj);
6980 		return ERR_PTR(ret);
6981 	}
6982 #endif	/* CONFIG_EXT_SUB_SCHED */
6983 
6984 	/*
6985 	 * Consume the arena_map ref bpf_scx_reg_cid() took. Defer to here so
6986 	 * earlier failure paths leave cmd->arena_map set and bpf_scx_reg_cid
6987 	 * drops the ref. After this point, sch owns the ref and any cleanup
6988 	 * runs through scx_sched_free_rcu_work() which puts it.
6989 	 */
6990 	sch->arena_map = cmd->arena_map;
6991 	/* BPF arena is only available on MMU && 64BIT */
6992 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
6993 	if (sch->arena_map)
6994 		sch->arena_kern_base = bpf_arena_map_kern_vm_start(sch->arena_map);
6995 #endif
6996 	cmd->arena_map = NULL;
6997 	return sch;
6998 
6999 #ifdef CONFIG_EXT_SUB_SCHED
7000 err_free_lb_resched:
7001 	free_cpumask_var(sch->bypass_lb_resched_cpumask);
7002 #endif
7003 err_free_lb_cpumask:
7004 	free_cpumask_var(sch->bypass_lb_donee_cpumask);
7005 err_stop_helper:
7006 	kthread_destroy_worker(sch->helper);
7007 err_free_pcpu:
7008 	for_each_possible_cpu(cpu) {
7009 		if (cpu == bypass_fail_cpu)
7010 			break;
7011 		exit_dsq(bypass_dsq(sch, cpu));
7012 	}
7013 	free_percpu(sch->pcpu);
7014 err_free_pnode:
7015 	for_each_node_state(node, N_POSSIBLE)
7016 		free_pnode(sch->pnode[node]);
7017 	kfree(sch->pnode);
7018 err_free_hash:
7019 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
7020 err_free_ei:
7021 	free_exit_info(sch->exit_info);
7022 err_free_sch:
7023 	kfree(sch);
7024 err_put_cgrp:
7025 #ifdef CONFIG_EXT_SUB_SCHED
7026 	cgroup_put(cgrp);
7027 #endif
7028 	return ERR_PTR(ret);
7029 }
7030 
7031 static int check_hotplug_seq(struct scx_sched *sch,
7032 			      const struct sched_ext_ops *ops)
7033 {
7034 	unsigned long long global_hotplug_seq;
7035 
7036 	/*
7037 	 * If a hotplug event has occurred between when a scheduler was
7038 	 * initialized, and when we were able to attach, exit and notify user
7039 	 * space about it.
7040 	 */
7041 	if (ops->hotplug_seq) {
7042 		global_hotplug_seq = atomic_long_read(&scx_hotplug_seq);
7043 		if (ops->hotplug_seq != global_hotplug_seq) {
7044 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
7045 				 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
7046 				 "expected hotplug seq %llu did not match actual %llu",
7047 				 ops->hotplug_seq, global_hotplug_seq);
7048 			return -EBUSY;
7049 		}
7050 	}
7051 
7052 	return 0;
7053 }
7054 
7055 static int validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
7056 {
7057 	/*
7058 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
7059 	 * ops.enqueue() callback isn't implemented.
7060 	 */
7061 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
7062 		scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
7063 		return -EINVAL;
7064 	}
7065 
7066 	/*
7067 	 * SCX_OPS_TID_TO_TASK is enabled by the root scheduler. A sub-sched
7068 	 * may set it to declare a dependency; reject if the root hasn't
7069 	 * enabled it.
7070 	 */
7071 	if ((ops->flags & SCX_OPS_TID_TO_TASK) && scx_parent(sch) &&
7072 	    !(scx_root->ops.flags & SCX_OPS_TID_TO_TASK)) {
7073 		scx_error(sch, "SCX_OPS_TID_TO_TASK requires root scheduler to enable it");
7074 		return -EINVAL;
7075 	}
7076 
7077 	/*
7078 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle
7079 	 * selection policy to be enabled.
7080 	 */
7081 	if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) &&
7082 	    (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) {
7083 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled");
7084 		return -EINVAL;
7085 	}
7086 
7087 	/*
7088 	 * cid-form's struct is shorter and doesn't include the cpu_acquire /
7089 	 * cpu_release tail; reading those fields off a cid-form @ops would
7090 	 * run past the BPF allocation. Skip for cid-form.
7091 	 */
7092 	if (!sch->is_cid_type && (ops->cpu_acquire || ops->cpu_release))
7093 		pr_warn_ratelimited("ops->cpu_acquire/release() are deprecated, use sched_switch TP instead\n");
7094 
7095 	/*
7096 	 * Sub-scheduler support is tied to the cid-form struct_ops. A sub-sched
7097 	 * attaches through a cid-form-only interface (sub_attach/sub_detach),
7098 	 * and a root that accepts sub-scheds must expose cid-form state to
7099 	 * them. Reject cpu-form schedulers on either side.
7100 	 */
7101 	if (!sch->is_cid_type) {
7102 		if (scx_parent(sch)) {
7103 			scx_error(sch, "sub-sched requires cid-form struct_ops");
7104 			return -EINVAL;
7105 		}
7106 		if (ops->sub_attach || ops->sub_detach) {
7107 			scx_error(sch, "sub_attach/sub_detach requires cid-form struct_ops");
7108 			return -EINVAL;
7109 		}
7110 	}
7111 
7112 	return 0;
7113 }
7114 
7115 static void scx_root_enable_workfn(struct kthread_work *work)
7116 {
7117 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
7118 	struct sched_ext_ops *ops = cmd->ops;
7119 	struct cgroup *cgrp = root_cgroup();
7120 	struct scx_sched *sch;
7121 	struct scx_task_iter sti;
7122 	struct task_struct *p;
7123 	int i, cpu, ret;
7124 
7125 	mutex_lock(&scx_enable_mutex);
7126 
7127 	if (scx_enable_state() != SCX_DISABLED) {
7128 		ret = -EBUSY;
7129 		goto err_unlock;
7130 	}
7131 
7132 	/*
7133 	 * @ops->priv binds @ops to its scx_sched instance. It is set here by
7134 	 * scx_alloc_and_add_sched() and cleared at the tail of bpf_scx_unreg(),
7135 	 * which runs after scx_root_disable() has dropped scx_enable_mutex. If
7136 	 * it's still non-NULL here, a previous attachment on @ops has not
7137 	 * finished tearing down; proceeding would let the in-flight unreg's
7138 	 * RCU_INIT_POINTER(NULL) clobber the @ops->priv we are about to assign.
7139 	 */
7140 	if (rcu_access_pointer(ops->priv)) {
7141 		ret = -EBUSY;
7142 		goto err_unlock;
7143 	}
7144 
7145 	ret = alloc_kick_syncs();
7146 	if (ret)
7147 		goto err_unlock;
7148 
7149 	if (ops->flags & SCX_OPS_TID_TO_TASK) {
7150 		ret = rhashtable_init(&scx_tid_hash, &scx_tid_hash_params);
7151 		if (ret)
7152 			goto err_free_ksyncs;
7153 	}
7154 
7155 #ifdef CONFIG_EXT_SUB_SCHED
7156 	cgroup_get(cgrp);
7157 #endif
7158 	sch = scx_alloc_and_add_sched(cmd, cgrp, NULL);
7159 	if (IS_ERR(sch)) {
7160 		ret = PTR_ERR(sch);
7161 		goto err_free_tid_hash;
7162 	}
7163 
7164 	if (sch->is_cid_type)
7165 		static_branch_enable(&__scx_is_cid_type);
7166 
7167 	/*
7168 	 * Transition to ENABLING and clear exit info to arm the disable path.
7169 	 * Failure triggers full disabling from here on.
7170 	 */
7171 	WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED);
7172 	WARN_ON_ONCE(scx_root);
7173 
7174 	atomic_long_set(&scx_nr_rejected, 0);
7175 
7176 	for_each_possible_cpu(cpu) {
7177 		struct rq *rq = cpu_rq(cpu);
7178 
7179 		rq->scx.local_dsq.sched = sch;
7180 		rq->scx.cpuperf_target = SCX_CPUPERF_ONE;
7181 	}
7182 
7183 	/*
7184 	 * Keep CPUs stable during enable so that the BPF scheduler can track
7185 	 * online CPUs by watching ->on/offline_cpu() after ->init().
7186 	 */
7187 	cpus_read_lock();
7188 
7189 	/*
7190 	 * Build the cid mapping before publishing scx_root. The cid kfuncs
7191 	 * dereference the cid arrays unconditionally once scx_prog_sched()
7192 	 * returns non-NULL; the rcu_assign_pointer() below pairs with their
7193 	 * rcu_dereference() to make the populated arrays visible.
7194 	 */
7195 	ret = scx_cid_init(sch);
7196 	if (ret) {
7197 		cpus_read_unlock();
7198 		goto err_disable;
7199 	}
7200 
7201 	/*
7202 	 * Make the scheduler instance visible. Must be inside cpus_read_lock().
7203 	 * See handle_hotplug().
7204 	 */
7205 	rcu_assign_pointer(scx_root, sch);
7206 
7207 	ret = scx_link_sched(sch);
7208 	if (ret) {
7209 		cpus_read_unlock();
7210 		goto err_disable;
7211 	}
7212 
7213 	scx_idle_enable(ops);
7214 
7215 	if (sch->ops.init) {
7216 		ret = SCX_CALL_OP_RET(sch, init, NULL);
7217 		if (ret) {
7218 			ret = ops_sanitize_err(sch, "init", ret);
7219 			cpus_read_unlock();
7220 			scx_error(sch, "ops.init() failed (%d)", ret);
7221 			goto err_disable;
7222 		}
7223 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
7224 	}
7225 
7226 	ret = scx_arena_pool_init(sch);
7227 	if (ret) {
7228 		cpus_read_unlock();
7229 		goto err_disable;
7230 	}
7231 
7232 	ret = scx_set_cmask_scratch_alloc(sch);
7233 	if (ret) {
7234 		cpus_read_unlock();
7235 		goto err_disable;
7236 	}
7237 
7238 	for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++)
7239 		if (((void (**)(void))ops)[i])
7240 			set_bit(i, sch->has_op);
7241 
7242 	ret = check_hotplug_seq(sch, ops);
7243 	if (ret) {
7244 		cpus_read_unlock();
7245 		goto err_disable;
7246 	}
7247 	scx_idle_update_selcpu_topology(ops);
7248 
7249 	cpus_read_unlock();
7250 
7251 	ret = validate_ops(sch, ops);
7252 	if (ret)
7253 		goto err_disable;
7254 
7255 	/*
7256 	 * Attach the ext_server bandwidth reservation before anything is
7257 	 * committed so that we can fail the enable if the root domain cannot
7258 	 * accommodate it. The matching fair_server detach is deferred to the
7259 	 * tail of this function, after the switch is fully committed and can no
7260 	 * longer fail.
7261 	 *
7262 	 * On failure, err_disable funnels into scx_root_disable() which
7263 	 * detaches ext_server, so partially-attached state is cleaned up
7264 	 * automatically.
7265 	 */
7266 	for_each_possible_cpu(cpu) {
7267 		struct rq *rq = cpu_rq(cpu);
7268 
7269 		scoped_guard(rq_lock_irqsave, rq) {
7270 			update_rq_clock(rq);
7271 			ret = dl_server_attach_bw(&rq->ext_server);
7272 		}
7273 		if (ret) {
7274 			pr_warn("sched_ext: failed to attach ext_server on CPU %d (%d)\n",
7275 				cpu, ret);
7276 			goto err_disable;
7277 		}
7278 	}
7279 
7280 	/*
7281 	 * Once __scx_enabled is set, %current can be switched to SCX anytime.
7282 	 * This can lead to stalls as some BPF schedulers (e.g. userspace
7283 	 * scheduling) may not function correctly before all tasks are switched.
7284 	 * Init in bypass mode to guarantee forward progress.
7285 	 */
7286 	scx_bypass(sch, true);
7287 
7288 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
7289 		if (((void (**)(void))ops)[i])
7290 			set_bit(i, sch->has_op);
7291 
7292 	if (sch->ops.cpu_acquire || sch->ops.cpu_release)
7293 		sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT;
7294 
7295 	/*
7296 	 * Lock out forks, cgroup on/offlining and moves before opening the
7297 	 * floodgate so that they don't wander into the operations prematurely.
7298 	 */
7299 	percpu_down_write(&scx_fork_rwsem);
7300 
7301 	WARN_ON_ONCE(scx_init_task_enabled);
7302 	scx_init_task_enabled = true;
7303 
7304 	/* flip under fork_rwsem; the iter below covers existing tasks */
7305 	if (ops->flags & SCX_OPS_TID_TO_TASK)
7306 		static_branch_enable(&__scx_tid_to_task_enabled);
7307 
7308 	/*
7309 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
7310 	 * preventing new tasks from being added. No need to exclude tasks
7311 	 * leaving as sched_ext_free() can handle both prepped and enabled
7312 	 * tasks. Prep all tasks first and then enable them with preemption
7313 	 * disabled.
7314 	 *
7315 	 * All cgroups should be initialized before scx_init_task() so that the
7316 	 * BPF scheduler can reliably track each task's cgroup membership from
7317 	 * scx_init_task(). Lock out cgroup on/offlining and task migrations
7318 	 * while tasks are being initialized so that scx_cgroup_can_attach()
7319 	 * never sees uninitialized tasks.
7320 	 */
7321 	scx_cgroup_lock();
7322 	set_cgroup_sched(sch_cgroup(sch), sch);
7323 	ret = scx_cgroup_init(sch);
7324 	if (ret)
7325 		goto err_disable_unlock_all;
7326 
7327 	scx_task_iter_start(&sti, NULL);
7328 	while ((p = scx_task_iter_next_locked(&sti))) {
7329 		/*
7330 		 * @p is in scx_tasks under scx_tasks_lock, and SCX_TASK_DEAD
7331 		 * tasks are filtered by scx_task_iter_next_locked().
7332 		 * sched_ext_dead() removes @p from scx_tasks under the same
7333 		 * lock before put_task_struct_rcu_user() runs, so @p->usage
7334 		 * is guaranteed > 0 here.
7335 		 */
7336 		get_task_struct(p);
7337 
7338 		/*
7339 		 * Set %INIT_BEGIN under the iter's rq lock so that a concurrent
7340 		 * sched_ext_dead() does not call ops.exit_task() on @p while
7341 		 * ops.init_task() is running. If sched_ext_dead() runs before
7342 		 * this store, it has already removed @p from scx_tasks and the
7343 		 * iter won't visit @p; if it runs after, it observes
7344 		 * %INIT_BEGIN and transitions to %DEAD without calling ops,
7345 		 * leaving the post-init recheck below to unwind.
7346 		 */
7347 		scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
7348 		scx_task_iter_unlock(&sti);
7349 
7350 		ret = __scx_init_task(sch, p, false);
7351 
7352 		scx_task_iter_relock(&sti, p);
7353 
7354 		if (unlikely(ret)) {
7355 			if (scx_get_task_state(p) != SCX_TASK_DEAD)
7356 				scx_set_task_state(p, SCX_TASK_NONE);
7357 			scx_task_iter_stop(&sti);
7358 			scx_error(sch, "ops.init_task() failed (%d) for %s[%d]",
7359 				  ret, p->comm, p->pid);
7360 			put_task_struct(p);
7361 			goto err_disable_unlock_all;
7362 		}
7363 
7364 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
7365 			/*
7366 			 * sched_ext_dead() observed %INIT_BEGIN and set %DEAD.
7367 			 * ops.exit_task() is owed to the sched __scx_init_task()
7368 			 * ran against; call it now.
7369 			 */
7370 			scx_sub_init_cancel_task(sch, p);
7371 		} else {
7372 			scx_set_task_state(p, SCX_TASK_INIT);
7373 			scx_set_task_sched(p, sch);
7374 			scx_set_task_state(p, SCX_TASK_READY);
7375 		}
7376 
7377 		/*
7378 		 * Insert into the tid hash. scx_tasks_lock is held by the iter;
7379 		 * list_empty() guards against sched_ext_dead() having taken @p
7380 		 * off the list while init ran unlocked.
7381 		 */
7382 		if (scx_tid_to_task_enabled() && !list_empty(&p->scx.tasks_node))
7383 			scx_tid_hash_insert(p);
7384 
7385 		put_task_struct(p);
7386 	}
7387 	scx_task_iter_stop(&sti);
7388 	scx_cgroup_unlock();
7389 	percpu_up_write(&scx_fork_rwsem);
7390 
7391 	/*
7392 	 * All tasks are READY. It's safe to turn on scx_enabled() and switch
7393 	 * all eligible tasks.
7394 	 */
7395 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
7396 	static_branch_enable(&__scx_enabled);
7397 
7398 	/*
7399 	 * We're fully committed and can't fail. The task READY -> ENABLED
7400 	 * transitions here are synchronized against sched_ext_free() through
7401 	 * scx_tasks_lock.
7402 	 */
7403 	percpu_down_write(&scx_fork_rwsem);
7404 	scx_task_iter_start(&sti, NULL);
7405 	while ((p = scx_task_iter_next_locked(&sti))) {
7406 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
7407 		const struct sched_class *old_class = p->sched_class;
7408 		const struct sched_class *new_class = scx_setscheduler_class(p);
7409 
7410 		if (scx_get_task_state(p) != SCX_TASK_READY)
7411 			continue;
7412 
7413 		if (old_class != new_class)
7414 			queue_flags |= DEQUEUE_CLASS;
7415 
7416 		scoped_guard (sched_change, p, queue_flags) {
7417 			p->scx.slice = READ_ONCE(sch->slice_dfl);
7418 			p->sched_class = new_class;
7419 		}
7420 	}
7421 	scx_task_iter_stop(&sti);
7422 	percpu_up_write(&scx_fork_rwsem);
7423 
7424 	scx_bypass(sch, false);
7425 
7426 	if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) {
7427 		WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE);
7428 		goto err_disable;
7429 	}
7430 
7431 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
7432 		static_branch_enable(&__scx_switched_all);
7433 
7434 	/*
7435 	 * Detach the fair_server bandwidth reservation now that the switch
7436 	 * is fully committed. In full mode (!SCX_OPS_SWITCH_PARTIAL) no
7437 	 * task will ever run in the fair class, so give that bandwidth
7438 	 * back to the RT class. The matching ext_server attach already
7439 	 * happened earlier; this only releases bandwidth and cannot fail.
7440 	 *
7441 	 * In partial mode keep fair_server attached.
7442 	 */
7443 	if (scx_switched_all()) {
7444 		for_each_possible_cpu(cpu) {
7445 			struct rq *rq = cpu_rq(cpu);
7446 
7447 			guard(rq_lock_irqsave)(rq);
7448 			update_rq_clock(rq);
7449 			dl_server_detach_bw(&rq->fair_server);
7450 		}
7451 	}
7452 
7453 	pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n",
7454 		sch->ops.name, scx_switched_all() ? "" : " (partial)");
7455 	kobject_uevent(&sch->kobj, KOBJ_ADD);
7456 	mutex_unlock(&scx_enable_mutex);
7457 
7458 	atomic_long_inc(&scx_enable_seq);
7459 
7460 	cmd->ret = 0;
7461 	return;
7462 
7463 err_free_tid_hash:
7464 	if (ops->flags & SCX_OPS_TID_TO_TASK)
7465 		rhashtable_free_and_destroy(&scx_tid_hash, NULL, NULL);
7466 err_free_ksyncs:
7467 	free_kick_syncs();
7468 err_unlock:
7469 	mutex_unlock(&scx_enable_mutex);
7470 	cmd->ret = ret;
7471 	return;
7472 
7473 err_disable_unlock_all:
7474 	scx_cgroup_unlock();
7475 	percpu_up_write(&scx_fork_rwsem);
7476 	/* we'll soon enter disable path, keep bypass on */
7477 err_disable:
7478 	mutex_unlock(&scx_enable_mutex);
7479 	/*
7480 	 * Returning an error code here would not pass all the error information
7481 	 * to userspace. Record errno using scx_error() for cases scx_error()
7482 	 * wasn't already invoked and exit indicating success so that the error
7483 	 * is notified through ops.exit() with all the details.
7484 	 *
7485 	 * Flush scx_disable_work to ensure that error is reported before init
7486 	 * completion. sch's base reference will be put by bpf_scx_unreg().
7487 	 */
7488 	scx_error(sch, "scx_root_enable() failed (%d)", ret);
7489 	scx_flush_disable_work(sch);
7490 	cmd->ret = 0;
7491 }
7492 
7493 #ifdef CONFIG_EXT_SUB_SCHED
7494 /* verify that a scheduler can be attached to @cgrp and return the parent */
7495 static struct scx_sched *find_parent_sched(struct cgroup *cgrp)
7496 {
7497 	struct scx_sched *parent = cgrp->scx_sched;
7498 	struct scx_sched *pos;
7499 
7500 	lockdep_assert_held(&scx_sched_lock);
7501 
7502 	/* can't attach twice to the same cgroup */
7503 	if (parent->cgrp == cgrp)
7504 		return ERR_PTR(-EBUSY);
7505 
7506 	/* does $parent allow sub-scheds? */
7507 	if (!parent->ops.sub_attach)
7508 		return ERR_PTR(-EOPNOTSUPP);
7509 
7510 	/* can't insert between $parent and its exiting children */
7511 	list_for_each_entry(pos, &parent->children, sibling)
7512 		if (cgroup_is_descendant(pos->cgrp, cgrp))
7513 			return ERR_PTR(-EBUSY);
7514 
7515 	return parent;
7516 }
7517 
7518 static bool assert_task_ready_or_enabled(struct task_struct *p)
7519 {
7520 	u32 state = scx_get_task_state(p);
7521 
7522 	switch (state) {
7523 	case SCX_TASK_READY:
7524 	case SCX_TASK_ENABLED:
7525 		return true;
7526 	default:
7527 		WARN_ONCE(true, "sched_ext: Invalid task state %d for %s[%d] during enabling sub sched",
7528 			  state, p->comm, p->pid);
7529 		return false;
7530 	}
7531 }
7532 
7533 static void scx_sub_enable_workfn(struct kthread_work *work)
7534 {
7535 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
7536 	struct sched_ext_ops *ops = cmd->ops;
7537 	struct cgroup *cgrp;
7538 	struct scx_sched *parent, *sch;
7539 	struct scx_task_iter sti;
7540 	struct task_struct *p;
7541 	s32 i, ret;
7542 
7543 	mutex_lock(&scx_enable_mutex);
7544 
7545 	if (!scx_enabled()) {
7546 		ret = -ENODEV;
7547 		goto out_unlock;
7548 	}
7549 
7550 	/* See scx_root_enable_workfn() for the @ops->priv check. */
7551 	if (rcu_access_pointer(ops->priv)) {
7552 		ret = -EBUSY;
7553 		goto out_unlock;
7554 	}
7555 
7556 	cgrp = cgroup_get_from_id(ops->sub_cgroup_id);
7557 	if (IS_ERR(cgrp)) {
7558 		ret = PTR_ERR(cgrp);
7559 		goto out_unlock;
7560 	}
7561 
7562 	raw_spin_lock_irq(&scx_sched_lock);
7563 	parent = find_parent_sched(cgrp);
7564 	if (IS_ERR(parent)) {
7565 		raw_spin_unlock_irq(&scx_sched_lock);
7566 		ret = PTR_ERR(parent);
7567 		goto out_put_cgrp;
7568 	}
7569 	kobject_get(&parent->kobj);
7570 	raw_spin_unlock_irq(&scx_sched_lock);
7571 
7572 	/* scx_alloc_and_add_sched() consumes @cgrp whether it succeeds or not */
7573 	sch = scx_alloc_and_add_sched(cmd, cgrp, parent);
7574 	kobject_put(&parent->kobj);
7575 	if (IS_ERR(sch)) {
7576 		ret = PTR_ERR(sch);
7577 		goto out_unlock;
7578 	}
7579 
7580 	ret = scx_link_sched(sch);
7581 	if (ret)
7582 		goto err_disable;
7583 
7584 	if (sch->level >= SCX_SUB_MAX_DEPTH) {
7585 		scx_error(sch, "max nesting depth %d violated",
7586 			  SCX_SUB_MAX_DEPTH);
7587 		goto err_disable;
7588 	}
7589 
7590 	if (sch->ops.init) {
7591 		ret = SCX_CALL_OP_RET(sch, init, NULL);
7592 		if (ret) {
7593 			ret = ops_sanitize_err(sch, "init", ret);
7594 			scx_error(sch, "ops.init() failed (%d)", ret);
7595 			goto err_disable;
7596 		}
7597 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
7598 	}
7599 
7600 	ret = scx_arena_pool_init(sch);
7601 	if (ret)
7602 		goto err_disable;
7603 
7604 	ret = scx_set_cmask_scratch_alloc(sch);
7605 	if (ret)
7606 		goto err_disable;
7607 
7608 	if (validate_ops(sch, ops))
7609 		goto err_disable;
7610 
7611 	struct scx_sub_attach_args sub_attach_args = {
7612 		.ops = &sch->ops,
7613 		.cgroup_path = sch->cgrp_path,
7614 	};
7615 
7616 	ret = SCX_CALL_OP_RET(parent, sub_attach, NULL,
7617 			      &sub_attach_args);
7618 	if (ret) {
7619 		ret = ops_sanitize_err(sch, "sub_attach", ret);
7620 		scx_error(sch, "parent rejected (%d)", ret);
7621 		goto err_disable;
7622 	}
7623 	sch->sub_attached = true;
7624 
7625 	scx_bypass(sch, true);
7626 
7627 	for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++)
7628 		if (((void (**)(void))ops)[i])
7629 			set_bit(i, sch->has_op);
7630 
7631 	percpu_down_write(&scx_fork_rwsem);
7632 	scx_cgroup_lock();
7633 
7634 	/*
7635 	 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see
7636 	 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down.
7637 	 */
7638 	set_cgroup_sched(sch_cgroup(sch), sch);
7639 	if (!(cgrp->self.flags & CSS_ONLINE)) {
7640 		scx_error(sch, "cgroup is not online");
7641 		goto err_unlock_and_disable;
7642 	}
7643 
7644 	/*
7645 	 * Initialize tasks for the new child $sch without exiting them for
7646 	 * $parent so that the tasks can always be reverted back to $parent
7647 	 * sched on child init failure.
7648 	 */
7649 	WARN_ON_ONCE(scx_enabling_sub_sched);
7650 	scx_enabling_sub_sched = sch;
7651 
7652 	scx_task_iter_start(&sti, sch->cgrp);
7653 	while ((p = scx_task_iter_next_locked(&sti))) {
7654 		struct rq *rq;
7655 		struct rq_flags rf;
7656 
7657 		/*
7658 		 * Task iteration may visit the same task twice when racing
7659 		 * against exiting. Use %SCX_TASK_SUB_INIT to mark tasks which
7660 		 * finished __scx_init_task() and skip if set.
7661 		 *
7662 		 * A task may exit and get freed between __scx_init_task()
7663 		 * completion and scx_enable_task(). In such cases,
7664 		 * scx_disable_and_exit_task() must exit the task for both the
7665 		 * parent and child scheds.
7666 		 */
7667 		if (p->scx.flags & SCX_TASK_SUB_INIT)
7668 			continue;
7669 
7670 		/* @p is pinned by the iter; see scx_sub_disable() */
7671 		get_task_struct(p);
7672 
7673 		if (!assert_task_ready_or_enabled(p)) {
7674 			ret = -EINVAL;
7675 			goto abort;
7676 		}
7677 
7678 		scx_task_iter_unlock(&sti);
7679 
7680 		/*
7681 		 * As $p is still on $parent, it can't be transitioned to INIT.
7682 		 * Let's worry about task state later. Use __scx_init_task().
7683 		 */
7684 		ret = __scx_init_task(sch, p, false);
7685 		if (ret)
7686 			goto abort;
7687 
7688 		rq = task_rq_lock(p, &rf);
7689 
7690 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
7691 			/*
7692 			 * sched_ext_dead() raced us between __scx_init_task()
7693 			 * and this rq lock and ran exit_task() on $parent (the
7694 			 * sched @p was on at that point), not on @sch. @sch's
7695 			 * just-completed init is owed an exit_task() and we
7696 			 * issue it here.
7697 			 */
7698 			scx_sub_init_cancel_task(sch, p);
7699 			task_rq_unlock(rq, p, &rf);
7700 			put_task_struct(p);
7701 			continue;
7702 		}
7703 
7704 		p->scx.flags |= SCX_TASK_SUB_INIT;
7705 		task_rq_unlock(rq, p, &rf);
7706 
7707 		put_task_struct(p);
7708 	}
7709 	scx_task_iter_stop(&sti);
7710 
7711 	/*
7712 	 * All tasks are prepped. Disable/exit tasks for $parent and enable for
7713 	 * the new @sch.
7714 	 */
7715 	scx_task_iter_start(&sti, sch->cgrp);
7716 	while ((p = scx_task_iter_next_locked(&sti))) {
7717 		/*
7718 		 * Use clearing of %SCX_TASK_SUB_INIT to detect and skip
7719 		 * duplicate iterations.
7720 		 */
7721 		if (!(p->scx.flags & SCX_TASK_SUB_INIT))
7722 			continue;
7723 
7724 		scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
7725 			/*
7726 			 * $p must be either READY or ENABLED. If ENABLED,
7727 			 * __scx_disabled_and_exit_task() first disables and
7728 			 * makes it READY. However, after exiting $p, it will
7729 			 * leave $p as READY.
7730 			 */
7731 			assert_task_ready_or_enabled(p);
7732 			__scx_disable_and_exit_task(parent, p);
7733 
7734 			/*
7735 			 * $p is now only initialized for @sch and READY, which
7736 			 * is what we want. Assign it to @sch and, if it's on
7737 			 * the ext class, enable. A non-ext task, possible under
7738 			 * an %SCX_OPS_SWITCH_PARTIAL root, stays READY and is
7739 			 * enabled by switching_to_scx() if it switches over.
7740 			 */
7741 			scx_set_task_sched(p, sch);
7742 			if (p->sched_class == &ext_sched_class)
7743 				scx_enable_task(sch, p);
7744 
7745 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
7746 		}
7747 	}
7748 	scx_task_iter_stop(&sti);
7749 
7750 	scx_enabling_sub_sched = NULL;
7751 
7752 	scx_cgroup_unlock();
7753 	percpu_up_write(&scx_fork_rwsem);
7754 
7755 	scx_bypass(sch, false);
7756 
7757 	pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name);
7758 	kobject_uevent(&sch->kobj, KOBJ_ADD);
7759 	ret = 0;
7760 	goto out_unlock;
7761 
7762 out_put_cgrp:
7763 	cgroup_put(cgrp);
7764 out_unlock:
7765 	mutex_unlock(&scx_enable_mutex);
7766 	cmd->ret = ret;
7767 	return;
7768 
7769 abort:
7770 	put_task_struct(p);
7771 	scx_task_iter_stop(&sti);
7772 
7773 	/*
7774 	 * Undo __scx_init_task() for tasks we marked. scx_enable_task() never
7775 	 * ran for @sch on them, so calling scx_disable_task() here would invoke
7776 	 * ops.disable() without a matching ops.enable(). scx_enabling_sub_sched
7777 	 * must stay set until SUB_INIT is cleared from every marked task -
7778 	 * scx_disable_and_exit_task() reads it when a task exits concurrently.
7779 	 */
7780 	scx_task_iter_start(&sti, sch->cgrp);
7781 	while ((p = scx_task_iter_next_locked(&sti))) {
7782 		if (p->scx.flags & SCX_TASK_SUB_INIT) {
7783 			scx_sub_init_cancel_task(sch, p);
7784 			p->scx.flags &= ~SCX_TASK_SUB_INIT;
7785 		}
7786 	}
7787 	scx_task_iter_stop(&sti);
7788 	scx_enabling_sub_sched = NULL;
7789 err_unlock_and_disable:
7790 	/* we'll soon enter disable path, keep bypass on */
7791 	scx_cgroup_unlock();
7792 	percpu_up_write(&scx_fork_rwsem);
7793 err_disable:
7794 	mutex_unlock(&scx_enable_mutex);
7795 	/*
7796 	 * Some enable failures only return an errno (e.g. -ENOMEM from an
7797 	 * allocation) without calling scx_error(). Record it so
7798 	 * scx_flush_disable_work() runs the disable and ops.exit() fires.
7799 	 */
7800 	scx_error(sch, "scx_sub_enable() failed (%d)", ret);
7801 	scx_flush_disable_work(sch);
7802 	cmd->ret = 0;
7803 }
7804 
7805 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb,
7806 				      unsigned long action, void *data)
7807 {
7808 	struct cgroup *cgrp = data;
7809 	struct cgroup *parent = cgroup_parent(cgrp);
7810 
7811 	if (!cgroup_on_dfl(cgrp))
7812 		return NOTIFY_OK;
7813 
7814 	switch (action) {
7815 	case CGROUP_LIFETIME_ONLINE:
7816 		/* inherit ->scx_sched from $parent */
7817 		if (parent)
7818 			rcu_assign_pointer(cgrp->scx_sched, parent->scx_sched);
7819 		break;
7820 	case CGROUP_LIFETIME_OFFLINE:
7821 		/* if there is a sched attached, shoot it down */
7822 		if (cgrp->scx_sched && cgrp->scx_sched->cgrp == cgrp)
7823 			scx_exit(cgrp->scx_sched, SCX_EXIT_UNREG_KERN,
7824 				 SCX_ECODE_RSN_CGROUP_OFFLINE,
7825 				 "cgroup %llu going offline", cgroup_id(cgrp));
7826 		break;
7827 	}
7828 
7829 	return NOTIFY_OK;
7830 }
7831 
7832 static struct notifier_block scx_cgroup_lifetime_nb = {
7833 	.notifier_call = scx_cgroup_lifetime_notify,
7834 };
7835 
7836 static s32 __init scx_cgroup_lifetime_notifier_init(void)
7837 {
7838 	return blocking_notifier_chain_register(&cgroup_lifetime_notifier,
7839 						&scx_cgroup_lifetime_nb);
7840 }
7841 core_initcall(scx_cgroup_lifetime_notifier_init);
7842 #endif	/* CONFIG_EXT_SUB_SCHED */
7843 
7844 static s32 scx_enable(struct scx_enable_cmd *cmd, struct bpf_link *link)
7845 {
7846 	static struct kthread_worker *helper;
7847 	static DEFINE_MUTEX(helper_mutex);
7848 
7849 	if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT)) {
7850 		pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n");
7851 		return -EINVAL;
7852 	}
7853 
7854 	if (!READ_ONCE(helper)) {
7855 		mutex_lock(&helper_mutex);
7856 		if (!helper) {
7857 			struct kthread_worker *w =
7858 				kthread_run_worker(0, "scx_enable_helper");
7859 			if (IS_ERR_OR_NULL(w)) {
7860 				mutex_unlock(&helper_mutex);
7861 				return -ENOMEM;
7862 			}
7863 			sched_set_fifo(w->task);
7864 			WRITE_ONCE(helper, w);
7865 		}
7866 		mutex_unlock(&helper_mutex);
7867 	}
7868 
7869 #ifdef CONFIG_EXT_SUB_SCHED
7870 	if (cmd->ops->sub_cgroup_id > 1)
7871 		kthread_init_work(&cmd->work, scx_sub_enable_workfn);
7872 	else
7873 #endif	/* CONFIG_EXT_SUB_SCHED */
7874 		kthread_init_work(&cmd->work, scx_root_enable_workfn);
7875 
7876 	kthread_queue_work(READ_ONCE(helper), &cmd->work);
7877 	kthread_flush_work(&cmd->work);
7878 	return cmd->ret;
7879 }
7880 
7881 
7882 /********************************************************************************
7883  * bpf_struct_ops plumbing.
7884  */
7885 #include <linux/bpf_verifier.h>
7886 #include <linux/bpf.h>
7887 #include <linux/btf.h>
7888 
7889 static const struct btf_type *task_struct_type;
7890 
7891 static bool bpf_scx_is_valid_access(int off, int size,
7892 				    enum bpf_access_type type,
7893 				    const struct bpf_prog *prog,
7894 				    struct bpf_insn_access_aux *info)
7895 {
7896 	if (type != BPF_READ)
7897 		return false;
7898 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
7899 		return false;
7900 	if (off % size != 0)
7901 		return false;
7902 
7903 	return btf_ctx_access(off, size, type, prog, info);
7904 }
7905 
7906 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
7907 				     const struct bpf_reg_state *reg, int off,
7908 				     int size)
7909 {
7910 	const struct btf_type *t;
7911 
7912 	t = btf_type_by_id(reg->btf, reg->btf_id);
7913 	if (t == task_struct_type) {
7914 		/*
7915 		 * COMPAT: Will be removed in v6.23.
7916 		 */
7917 		if ((off >= offsetof(struct task_struct, scx.slice) &&
7918 		     off + size <= offsetofend(struct task_struct, scx.slice)) ||
7919 		    (off >= offsetof(struct task_struct, scx.dsq_vtime) &&
7920 		     off + size <= offsetofend(struct task_struct, scx.dsq_vtime))) {
7921 			pr_warn_ratelimited("sched_ext: Writing directly to p->scx.slice/dsq_vtime is deprecated, use scx_bpf_task_set_slice/dsq_vtime()\n");
7922 			return SCALAR_VALUE;
7923 		}
7924 
7925 		if (off >= offsetof(struct task_struct, scx.disallow) &&
7926 		    off + size <= offsetofend(struct task_struct, scx.disallow))
7927 			return SCALAR_VALUE;
7928 	}
7929 
7930 	return -EACCES;
7931 }
7932 
7933 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
7934 	.get_func_proto = bpf_base_func_proto,
7935 	.is_valid_access = bpf_scx_is_valid_access,
7936 	.btf_struct_access = bpf_scx_btf_struct_access,
7937 };
7938 
7939 static int bpf_scx_init_member(const struct btf_type *t,
7940 			       const struct btf_member *member,
7941 			       void *kdata, const void *udata)
7942 {
7943 	const struct sched_ext_ops *uops = udata;
7944 	struct sched_ext_ops *ops = kdata;
7945 	u32 moff = __btf_member_bit_offset(t, member) / 8;
7946 	int ret;
7947 
7948 	switch (moff) {
7949 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
7950 		if (*(u32 *)(udata + moff) > INT_MAX)
7951 			return -E2BIG;
7952 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
7953 		return 1;
7954 	case offsetof(struct sched_ext_ops, flags):
7955 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
7956 			return -EINVAL;
7957 		ops->flags = *(u64 *)(udata + moff);
7958 		return 1;
7959 	case offsetof(struct sched_ext_ops, name):
7960 		ret = bpf_obj_name_cpy(ops->name, uops->name,
7961 				       sizeof(ops->name));
7962 		if (ret < 0)
7963 			return ret;
7964 		if (ret == 0)
7965 			return -EINVAL;
7966 		return 1;
7967 	case offsetof(struct sched_ext_ops, timeout_ms):
7968 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
7969 		    SCX_WATCHDOG_MAX_TIMEOUT)
7970 			return -E2BIG;
7971 		ops->timeout_ms = *(u32 *)(udata + moff);
7972 		return 1;
7973 	case offsetof(struct sched_ext_ops, exit_dump_len):
7974 		ops->exit_dump_len =
7975 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
7976 		return 1;
7977 	case offsetof(struct sched_ext_ops, hotplug_seq):
7978 		ops->hotplug_seq = *(u64 *)(udata + moff);
7979 		return 1;
7980 #ifdef CONFIG_EXT_SUB_SCHED
7981 	case offsetof(struct sched_ext_ops, sub_cgroup_id):
7982 		ops->sub_cgroup_id = *(u64 *)(udata + moff);
7983 		return 1;
7984 #endif	/* CONFIG_EXT_SUB_SCHED */
7985 	}
7986 
7987 	return 0;
7988 }
7989 
7990 #ifdef CONFIG_EXT_SUB_SCHED
7991 static void scx_pstack_recursion_on_dispatch(struct bpf_prog *prog)
7992 {
7993 	struct scx_sched *sch;
7994 
7995 	guard(rcu)();
7996 	sch = scx_prog_sched(prog->aux);
7997 	if (unlikely(!sch))
7998 		return;
7999 
8000 	scx_error(sch, "dispatch recursion detected");
8001 }
8002 #endif	/* CONFIG_EXT_SUB_SCHED */
8003 
8004 static int bpf_scx_check_member(const struct btf_type *t,
8005 				const struct btf_member *member,
8006 				const struct bpf_prog *prog)
8007 {
8008 	u32 moff = __btf_member_bit_offset(t, member) / 8;
8009 
8010 	switch (moff) {
8011 	case offsetof(struct sched_ext_ops, init_task):
8012 #ifdef CONFIG_EXT_GROUP_SCHED
8013 	case offsetof(struct sched_ext_ops, cgroup_init):
8014 	case offsetof(struct sched_ext_ops, cgroup_exit):
8015 	case offsetof(struct sched_ext_ops, cgroup_prep_move):
8016 #endif
8017 	case offsetof(struct sched_ext_ops, cpu_online):
8018 	case offsetof(struct sched_ext_ops, cpu_offline):
8019 	case offsetof(struct sched_ext_ops, init):
8020 	case offsetof(struct sched_ext_ops, exit):
8021 	case offsetof(struct sched_ext_ops, sub_attach):
8022 	case offsetof(struct sched_ext_ops, sub_detach):
8023 		break;
8024 	default:
8025 		if (prog->sleepable)
8026 			return -EINVAL;
8027 	}
8028 
8029 #ifdef CONFIG_EXT_SUB_SCHED
8030 	/*
8031 	 * Enable private stack for operations that can nest along the
8032 	 * hierarchy.
8033 	 *
8034 	 * XXX - Ideally, we should only do this for scheds that allow
8035 	 * sub-scheds and sub-scheds themselves but I don't know how to access
8036 	 * struct_ops from here.
8037 	 */
8038 	switch (moff) {
8039 	case offsetof(struct sched_ext_ops, dispatch):
8040 		prog->aux->priv_stack_requested = true;
8041 		prog->aux->recursion_detected = scx_pstack_recursion_on_dispatch;
8042 	}
8043 #endif	/* CONFIG_EXT_SUB_SCHED */
8044 
8045 	return 0;
8046 }
8047 
8048 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
8049 {
8050 	struct scx_enable_cmd cmd = { .ops = kdata };
8051 
8052 	return scx_enable(&cmd, link);
8053 }
8054 
8055 struct scx_arena_scan {
8056 	struct bpf_map	*arena;
8057 	int		err;
8058 };
8059 
8060 /*
8061  * The verifier enforces one arena per BPF program, so each struct_ops
8062  * member prog contributes at most one arena via bpf_prog_arena().
8063  * Require all non-NULL contributions to match.
8064  */
8065 static int scx_arena_scan_prog(struct bpf_prog *prog, void *data)
8066 {
8067 	struct scx_arena_scan *s = data;
8068 	struct bpf_map *arena = NULL;
8069 
8070 	/* arena.o, which defines these, is built only on MMU && 64BIT */
8071 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
8072 	arena = bpf_prog_arena(prog);
8073 #endif
8074 	if (!arena)
8075 		return 0;
8076 	if (s->arena && s->arena != arena) {
8077 		s->err = -EINVAL;
8078 		return 1;
8079 	}
8080 	s->arena = arena;
8081 	return 0;
8082 }
8083 
8084 static int bpf_scx_reg_cid(void *kdata, struct bpf_link *link)
8085 {
8086 	struct scx_enable_cmd cmd = { .ops_cid = kdata, .is_cid_type = true };
8087 	struct scx_arena_scan scan = {};
8088 	int ret;
8089 
8090 	bpf_struct_ops_for_each_prog(kdata, scx_arena_scan_prog, &scan);
8091 	if (scan.err) {
8092 		pr_err("sched_ext: cid-form scheduler uses multiple arena maps\n");
8093 		return scan.err;
8094 	}
8095 	if (!scan.arena) {
8096 		pr_err("sched_ext: cid-form scheduler must use a BPF arena map\n");
8097 		return -EINVAL;
8098 	}
8099 
8100 	bpf_map_inc(scan.arena);
8101 	cmd.arena_map = scan.arena;
8102 	ret = scx_enable(&cmd, link);
8103 	if (cmd.arena_map)		/* not consumed by scx_alloc_and_add_sched() */
8104 		bpf_map_put(cmd.arena_map);
8105 	return ret;
8106 }
8107 
8108 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
8109 {
8110 	struct sched_ext_ops *ops = kdata;
8111 	struct scx_sched *sch = rcu_dereference_protected(ops->priv, true);
8112 
8113 	scx_disable(sch, SCX_EXIT_UNREG);
8114 	scx_flush_disable_work(sch);
8115 	RCU_INIT_POINTER(ops->priv, NULL);
8116 	kobject_put(&sch->kobj);
8117 }
8118 
8119 static int bpf_scx_init(struct btf *btf)
8120 {
8121 	task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]);
8122 
8123 	return 0;
8124 }
8125 
8126 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
8127 {
8128 	/*
8129 	 * sched_ext does not support updating the actively-loaded BPF
8130 	 * scheduler, as registering a BPF scheduler can always fail if the
8131 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
8132 	 * etc. Similarly, we can always race with unregistration happening
8133 	 * elsewhere, such as with sysrq.
8134 	 */
8135 	return -EOPNOTSUPP;
8136 }
8137 
8138 static int bpf_scx_validate(void *kdata)
8139 {
8140 	return 0;
8141 }
8142 
8143 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
8144 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
8145 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
8146 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {}
8147 static void sched_ext_ops__tick(struct task_struct *p) {}
8148 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {}
8149 static void sched_ext_ops__running(struct task_struct *p) {}
8150 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {}
8151 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {}
8152 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; }
8153 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; }
8154 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {}
8155 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {}
8156 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {}
8157 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {}
8158 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {}
8159 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
8160 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {}
8161 static void sched_ext_ops__enable(struct task_struct *p) {}
8162 static void sched_ext_ops__disable(struct task_struct *p) {}
8163 #ifdef CONFIG_EXT_GROUP_SCHED
8164 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; }
8165 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {}
8166 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; }
8167 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
8168 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
8169 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
8170 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
8171 static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}
8172 #endif	/* CONFIG_EXT_GROUP_SCHED */
8173 static s32 sched_ext_ops__sub_attach(struct scx_sub_attach_args *args) { return -EINVAL; }
8174 static void sched_ext_ops__sub_detach(struct scx_sub_detach_args *args) {}
8175 static void sched_ext_ops__cpu_online(s32 cpu) {}
8176 static void sched_ext_ops__cpu_offline(s32 cpu) {}
8177 static s32 sched_ext_ops__init(void) { return -EINVAL; }
8178 static void sched_ext_ops__exit(struct scx_exit_info *info) {}
8179 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {}
8180 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {}
8181 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {}
8182 
8183 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
8184 	.select_cpu		= sched_ext_ops__select_cpu,
8185 	.enqueue		= sched_ext_ops__enqueue,
8186 	.dequeue		= sched_ext_ops__dequeue,
8187 	.dispatch		= sched_ext_ops__dispatch,
8188 	.tick			= sched_ext_ops__tick,
8189 	.runnable		= sched_ext_ops__runnable,
8190 	.running		= sched_ext_ops__running,
8191 	.stopping		= sched_ext_ops__stopping,
8192 	.quiescent		= sched_ext_ops__quiescent,
8193 	.yield			= sched_ext_ops__yield,
8194 	.core_sched_before	= sched_ext_ops__core_sched_before,
8195 	.set_weight		= sched_ext_ops__set_weight,
8196 	.set_cpumask		= sched_ext_ops__set_cpumask,
8197 	.update_idle		= sched_ext_ops__update_idle,
8198 	.cpu_acquire		= sched_ext_ops__cpu_acquire,
8199 	.cpu_release		= sched_ext_ops__cpu_release,
8200 	.init_task		= sched_ext_ops__init_task,
8201 	.exit_task		= sched_ext_ops__exit_task,
8202 	.enable			= sched_ext_ops__enable,
8203 	.disable		= sched_ext_ops__disable,
8204 #ifdef CONFIG_EXT_GROUP_SCHED
8205 	.cgroup_init		= sched_ext_ops__cgroup_init,
8206 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
8207 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
8208 	.cgroup_move		= sched_ext_ops__cgroup_move,
8209 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
8210 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
8211 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
8212 	.cgroup_set_idle	= sched_ext_ops__cgroup_set_idle,
8213 #endif
8214 	.sub_attach		= sched_ext_ops__sub_attach,
8215 	.sub_detach		= sched_ext_ops__sub_detach,
8216 	.cpu_online		= sched_ext_ops__cpu_online,
8217 	.cpu_offline		= sched_ext_ops__cpu_offline,
8218 	.init			= sched_ext_ops__init,
8219 	.exit			= sched_ext_ops__exit,
8220 	.dump			= sched_ext_ops__dump,
8221 	.dump_cpu		= sched_ext_ops__dump_cpu,
8222 	.dump_task		= sched_ext_ops__dump_task,
8223 };
8224 
8225 static struct bpf_struct_ops bpf_sched_ext_ops = {
8226 	.verifier_ops = &bpf_scx_verifier_ops,
8227 	.reg = bpf_scx_reg,
8228 	.unreg = bpf_scx_unreg,
8229 	.check_member = bpf_scx_check_member,
8230 	.init_member = bpf_scx_init_member,
8231 	.init = bpf_scx_init,
8232 	.update = bpf_scx_update,
8233 	.validate = bpf_scx_validate,
8234 	.name = "sched_ext_ops",
8235 	.owner = THIS_MODULE,
8236 	.cfi_stubs = &__bpf_ops_sched_ext_ops
8237 };
8238 
8239 /*
8240  * cid-form cfi stubs. Stubs whose signatures match the cpu-form (param types
8241  * identical, only param names differ across structs) are reused; only
8242  * set_cmask needs a fresh stub since the second argument type differs.
8243  */
8244 static void sched_ext_ops_cid__set_cmask(struct task_struct *p,
8245 					 const struct scx_cmask *cmask) {}
8246 
8247 static struct sched_ext_ops_cid __bpf_ops_sched_ext_ops_cid = {
8248 	.select_cid		= sched_ext_ops__select_cpu,
8249 	.enqueue		= sched_ext_ops__enqueue,
8250 	.dequeue		= sched_ext_ops__dequeue,
8251 	.dispatch		= sched_ext_ops__dispatch,
8252 	.tick			= sched_ext_ops__tick,
8253 	.runnable		= sched_ext_ops__runnable,
8254 	.running		= sched_ext_ops__running,
8255 	.stopping		= sched_ext_ops__stopping,
8256 	.quiescent		= sched_ext_ops__quiescent,
8257 	.yield			= sched_ext_ops__yield,
8258 	.core_sched_before	= sched_ext_ops__core_sched_before,
8259 	.set_weight		= sched_ext_ops__set_weight,
8260 	.set_cmask		= sched_ext_ops_cid__set_cmask,
8261 	.update_idle		= sched_ext_ops__update_idle,
8262 	.init_task		= sched_ext_ops__init_task,
8263 	.exit_task		= sched_ext_ops__exit_task,
8264 	.enable			= sched_ext_ops__enable,
8265 	.disable		= sched_ext_ops__disable,
8266 #ifdef CONFIG_EXT_GROUP_SCHED
8267 	.cgroup_init		= sched_ext_ops__cgroup_init,
8268 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
8269 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
8270 	.cgroup_move		= sched_ext_ops__cgroup_move,
8271 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
8272 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
8273 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
8274 	.cgroup_set_idle	= sched_ext_ops__cgroup_set_idle,
8275 #endif
8276 	.sub_attach		= sched_ext_ops__sub_attach,
8277 	.sub_detach		= sched_ext_ops__sub_detach,
8278 	.cid_online		= sched_ext_ops__cpu_online,
8279 	.cid_offline		= sched_ext_ops__cpu_offline,
8280 	.init			= sched_ext_ops__init,
8281 	.exit			= sched_ext_ops__exit,
8282 	.dump			= sched_ext_ops__dump,
8283 	.dump_cid		= sched_ext_ops__dump_cpu,
8284 	.dump_task		= sched_ext_ops__dump_task,
8285 };
8286 
8287 /*
8288  * The cid-form struct_ops shares all bpf_struct_ops hooks with the cpu form.
8289  * init_member, check_member, reg, unreg, etc. process kdata as the byte block
8290  * verified to match by the BUILD_BUG_ON checks in scx_init().
8291  */
8292 static struct bpf_struct_ops bpf_sched_ext_ops_cid = {
8293 	.verifier_ops = &bpf_scx_verifier_ops,
8294 	.reg = bpf_scx_reg_cid,
8295 	.unreg = bpf_scx_unreg,
8296 	.check_member = bpf_scx_check_member,
8297 	.init_member = bpf_scx_init_member,
8298 	.init = bpf_scx_init,
8299 	.update = bpf_scx_update,
8300 	.validate = bpf_scx_validate,
8301 	.name = "sched_ext_ops_cid",
8302 	.owner = THIS_MODULE,
8303 	.cfi_stubs = &__bpf_ops_sched_ext_ops_cid
8304 };
8305 
8306 
8307 /********************************************************************************
8308  * System integration and init.
8309  */
8310 
8311 static void sysrq_handle_sched_ext_reset(u8 key)
8312 {
8313 	struct scx_sched *sch;
8314 
8315 	sch = rcu_dereference(scx_root);
8316 	if (likely(sch))
8317 		scx_disable(sch, SCX_EXIT_SYSRQ);
8318 	else
8319 		pr_info("sched_ext: BPF schedulers not loaded\n");
8320 }
8321 
8322 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
8323 	.handler	= sysrq_handle_sched_ext_reset,
8324 	.help_msg	= "reset-sched-ext(S)",
8325 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
8326 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
8327 };
8328 
8329 static void sysrq_handle_sched_ext_dump(u8 key)
8330 {
8331 	struct scx_exit_info ei = {
8332 		.kind		= SCX_EXIT_NONE,
8333 		.exit_cpu	= -1,
8334 		.reason		= "SysRq-D",
8335 	};
8336 	struct scx_sched *sch;
8337 
8338 	list_for_each_entry_rcu(sch, &scx_sched_all, all)
8339 		scx_dump_state(sch, &ei, 0, false);
8340 }
8341 
8342 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
8343 	.handler	= sysrq_handle_sched_ext_dump,
8344 	.help_msg	= "dump-sched-ext(D)",
8345 	.action_msg	= "Trigger sched_ext debug dump",
8346 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
8347 };
8348 
8349 static bool can_skip_idle_kick(struct rq *rq)
8350 {
8351 	lockdep_assert_rq_held(rq);
8352 
8353 	/*
8354 	 * We can skip idle kicking if @rq is going to go through at least one
8355 	 * full SCX scheduling cycle before going idle. Just checking whether
8356 	 * curr is not idle is insufficient because we could be racing
8357 	 * balance_one() trying to pull the next task from a remote rq, which
8358 	 * may fail, and @rq may become idle afterwards.
8359 	 *
8360 	 * The race window is small and we don't and can't guarantee that @rq is
8361 	 * only kicked while idle anyway. Skip only when sure.
8362 	 */
8363 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_BALANCE);
8364 }
8365 
8366 static bool kick_one_cpu(s32 cpu, struct rq *this_rq, unsigned long *ksyncs)
8367 {
8368 	struct rq *rq = cpu_rq(cpu);
8369 	struct scx_rq *this_scx = &this_rq->scx;
8370 	const struct sched_class *cur_class;
8371 	bool should_wait = false;
8372 	unsigned long flags;
8373 
8374 	raw_spin_rq_lock_irqsave(rq, flags);
8375 	cur_class = rq->curr->sched_class;
8376 
8377 	/*
8378 	 * During CPU hotplug, a CPU may depend on kicking itself to make
8379 	 * forward progress. Allow kicking self regardless of online state. If
8380 	 * @cpu is running a higher class task, we have no control over @cpu.
8381 	 * Skip kicking.
8382 	 */
8383 	if ((cpu_online(cpu) || cpu == cpu_of(this_rq)) &&
8384 	    !sched_class_above(cur_class, &ext_sched_class)) {
8385 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_preempt)) {
8386 			if (cur_class == &ext_sched_class)
8387 				rq->curr->scx.slice = 0;
8388 			cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
8389 		}
8390 
8391 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_wait)) {
8392 			if (cur_class == &ext_sched_class) {
8393 				cpumask_set_cpu(cpu, this_scx->cpus_to_sync);
8394 				ksyncs[cpu] = rq->scx.kick_sync;
8395 				should_wait = true;
8396 			}
8397 			cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
8398 		}
8399 
8400 		resched_curr(rq);
8401 	} else {
8402 		cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
8403 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
8404 	}
8405 
8406 	raw_spin_rq_unlock_irqrestore(rq, flags);
8407 
8408 	return should_wait;
8409 }
8410 
8411 static void kick_one_cpu_if_idle(s32 cpu, struct rq *this_rq)
8412 {
8413 	struct rq *rq = cpu_rq(cpu);
8414 	unsigned long flags;
8415 
8416 	raw_spin_rq_lock_irqsave(rq, flags);
8417 
8418 	if (!can_skip_idle_kick(rq) &&
8419 	    (cpu_online(cpu) || cpu == cpu_of(this_rq)))
8420 		resched_curr(rq);
8421 
8422 	raw_spin_rq_unlock_irqrestore(rq, flags);
8423 }
8424 
8425 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
8426 {
8427 	struct rq *this_rq = this_rq();
8428 	struct scx_rq *this_scx = &this_rq->scx;
8429 	struct scx_kick_syncs __rcu *ksyncs_pcpu = __this_cpu_read(scx_kick_syncs);
8430 	bool should_wait = false;
8431 	unsigned long *ksyncs;
8432 	s32 cpu;
8433 
8434 	/* can race with free_kick_syncs() during scheduler disable */
8435 	if (unlikely(!ksyncs_pcpu))
8436 		return;
8437 
8438 	ksyncs = rcu_dereference_bh(ksyncs_pcpu)->syncs;
8439 
8440 	for_each_cpu(cpu, this_scx->cpus_to_kick) {
8441 		should_wait |= kick_one_cpu(cpu, this_rq, ksyncs);
8442 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick);
8443 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
8444 	}
8445 
8446 	for_each_cpu(cpu, this_scx->cpus_to_kick_if_idle) {
8447 		kick_one_cpu_if_idle(cpu, this_rq);
8448 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
8449 	}
8450 
8451 	/*
8452 	 * Can't wait in hardirq — kick_sync can't advance, deadlocking if
8453 	 * CPUs wait for each other. Defer to kick_sync_wait_bal_cb().
8454 	 */
8455 	if (should_wait) {
8456 		raw_spin_rq_lock(this_rq);
8457 		this_scx->kick_sync_pending = true;
8458 		resched_curr(this_rq);
8459 		raw_spin_rq_unlock(this_rq);
8460 	}
8461 }
8462 
8463 /**
8464  * print_scx_info - print out sched_ext scheduler state
8465  * @log_lvl: the log level to use when printing
8466  * @p: target task
8467  *
8468  * If a sched_ext scheduler is enabled, print the name and state of the
8469  * scheduler. If @p is on sched_ext, print further information about the task.
8470  *
8471  * This function can be safely called on any task as long as the task_struct
8472  * itself is accessible. While safe, this function isn't synchronized and may
8473  * print out mixups or garbages of limited length.
8474  */
8475 void print_scx_info(const char *log_lvl, struct task_struct *p)
8476 {
8477 	struct scx_sched *sch;
8478 	enum scx_enable_state state = scx_enable_state();
8479 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
8480 	char runnable_at_buf[22] = "?";
8481 	struct sched_class *class;
8482 	unsigned long runnable_at;
8483 
8484 	guard(rcu)();
8485 
8486 	sch = scx_task_sched_rcu(p);
8487 
8488 	if (!sch)
8489 		return;
8490 
8491 	/*
8492 	 * Carefully check if the task was running on sched_ext, and then
8493 	 * carefully copy the time it's been runnable, and its state.
8494 	 */
8495 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
8496 	    class != &ext_sched_class) {
8497 		printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name,
8498 		       scx_enable_state_str[state], all);
8499 		return;
8500 	}
8501 
8502 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
8503 				      sizeof(runnable_at)))
8504 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
8505 			  jiffies_delta_msecs(runnable_at, jiffies));
8506 
8507 	/* print everything onto one line to conserve console space */
8508 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
8509 	       log_lvl, sch->ops.name, scx_enable_state_str[state], all,
8510 	       runnable_at_buf);
8511 }
8512 
8513 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr)
8514 {
8515 	struct scx_sched *sch;
8516 
8517 	guard(rcu)();
8518 
8519 	sch = rcu_dereference(scx_root);
8520 	if (!sch)
8521 		return NOTIFY_OK;
8522 
8523 	/*
8524 	 * SCX schedulers often have userspace components which are sometimes
8525 	 * involved in critial scheduling paths. PM operations involve freezing
8526 	 * userspace which can lead to scheduling misbehaviors including stalls.
8527 	 * Let's bypass while PM operations are in progress.
8528 	 */
8529 	switch (event) {
8530 	case PM_HIBERNATION_PREPARE:
8531 	case PM_SUSPEND_PREPARE:
8532 	case PM_RESTORE_PREPARE:
8533 		scx_bypass(sch, true);
8534 		break;
8535 	case PM_POST_HIBERNATION:
8536 	case PM_POST_SUSPEND:
8537 	case PM_POST_RESTORE:
8538 		scx_bypass(sch, false);
8539 		break;
8540 	}
8541 
8542 	return NOTIFY_OK;
8543 }
8544 
8545 static struct notifier_block scx_pm_notifier = {
8546 	.notifier_call = scx_pm_handler,
8547 };
8548 
8549 void __init init_sched_ext_class(void)
8550 {
8551 	s32 cpu, v;
8552 
8553 	/*
8554 	 * The following is to prevent the compiler from optimizing out the enum
8555 	 * definitions so that BPF scheduler implementations can use them
8556 	 * through the generated vmlinux.h.
8557 	 */
8558 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT |
8559 		   SCX_TG_ONLINE);
8560 
8561 	scx_idle_init_masks();
8562 
8563 	for_each_possible_cpu(cpu) {
8564 		struct rq *rq = cpu_rq(cpu);
8565 		int  n = cpu_to_node(cpu);
8566 
8567 		/* local_dsq's sch will be set during scx_root_enable() */
8568 		BUG_ON(init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL, NULL));
8569 
8570 		INIT_LIST_HEAD(&rq->scx.runnable_list);
8571 		INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals);
8572 
8573 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick, GFP_KERNEL, n));
8574 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick_if_idle, GFP_KERNEL, n));
8575 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_preempt, GFP_KERNEL, n));
8576 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_wait, GFP_KERNEL, n));
8577 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_sync, GFP_KERNEL, n));
8578 		raw_spin_lock_init(&rq->scx.deferred_reenq_lock);
8579 		INIT_LIST_HEAD(&rq->scx.deferred_reenq_locals);
8580 		INIT_LIST_HEAD(&rq->scx.deferred_reenq_users);
8581 		rq->scx.deferred_irq_work = IRQ_WORK_INIT_HARD(deferred_irq_workfn);
8582 		rq->scx.kick_cpus_irq_work = IRQ_WORK_INIT_HARD(kick_cpus_irq_workfn);
8583 
8584 		if (cpu_online(cpu))
8585 			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
8586 	}
8587 
8588 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
8589 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
8590 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
8591 
8592 #ifdef CONFIG_EXT_SUB_SCHED
8593 	BUG_ON(rhashtable_init(&scx_sched_hash, &scx_sched_hash_params));
8594 #endif	/* CONFIG_EXT_SUB_SCHED */
8595 }
8596 
8597 
8598 /********************************************************************************
8599  * Helpers that can be called from the BPF scheduler.
8600  */
8601 static bool scx_vet_enq_flags(struct scx_sched *sch, u64 dsq_id, u64 *enq_flags)
8602 {
8603 	bool is_local = dsq_id == SCX_DSQ_LOCAL ||
8604 		(dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON;
8605 
8606 	if (*enq_flags & SCX_ENQ_IMMED) {
8607 		if (unlikely(!is_local)) {
8608 			scx_error(sch, "SCX_ENQ_IMMED on a non-local DSQ 0x%llx", dsq_id);
8609 			return false;
8610 		}
8611 	} else if ((sch->ops.flags & SCX_OPS_ALWAYS_ENQ_IMMED) && is_local) {
8612 		*enq_flags |= SCX_ENQ_IMMED;
8613 	}
8614 
8615 	return true;
8616 }
8617 
8618 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p,
8619 				    u64 dsq_id, u64 *enq_flags)
8620 {
8621 	lockdep_assert_irqs_disabled();
8622 
8623 	if (unlikely(!p)) {
8624 		scx_error(sch, "called with NULL task");
8625 		return false;
8626 	}
8627 
8628 	if (unlikely(*enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
8629 		scx_error(sch, "invalid enq_flags 0x%llx", *enq_flags);
8630 		return false;
8631 	}
8632 
8633 	/* see SCX_EV_INSERT_NOT_OWNED definition */
8634 	if (unlikely(!scx_task_on_sched(sch, p))) {
8635 		__scx_add_event(sch, SCX_EV_INSERT_NOT_OWNED, 1);
8636 		return false;
8637 	}
8638 
8639 	if (!scx_vet_enq_flags(sch, dsq_id, enq_flags))
8640 		return false;
8641 
8642 	return true;
8643 }
8644 
8645 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p,
8646 				  u64 dsq_id, u64 enq_flags)
8647 {
8648 	struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
8649 	struct task_struct *ddsp_task;
8650 
8651 	ddsp_task = __this_cpu_read(direct_dispatch_task);
8652 	if (ddsp_task) {
8653 		mark_direct_dispatch(sch, ddsp_task, p, dsq_id, enq_flags);
8654 		return;
8655 	}
8656 
8657 	if (unlikely(dspc->cursor >= sch->dsp_max_batch)) {
8658 		scx_error(sch, "dispatch buffer overflow");
8659 		return;
8660 	}
8661 
8662 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
8663 		.task = p,
8664 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
8665 		.dsq_id = dsq_id,
8666 		.enq_flags = enq_flags,
8667 	};
8668 }
8669 
8670 __bpf_kfunc_start_defs();
8671 
8672 /**
8673  * scx_bpf_dsq_insert - Insert a task into the FIFO queue of a DSQ
8674  * @p: task_struct to insert
8675  * @dsq_id: DSQ to insert into
8676  * @slice: duration @p can run for in nsecs, 0 to keep the current value
8677  * @enq_flags: SCX_ENQ_*
8678  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8679  *
8680  * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to
8681  * call this function spuriously. Can be called from ops.enqueue(),
8682  * ops.select_cpu(), and ops.dispatch().
8683  *
8684  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
8685  * and @p must match the task being enqueued.
8686  *
8687  * When called from ops.select_cpu(), @enq_flags and @dsp_id are stored, and @p
8688  * will be directly inserted into the corresponding dispatch queue after
8689  * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be
8690  * inserted into the local DSQ of the CPU returned by ops.select_cpu().
8691  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
8692  * task is inserted.
8693  *
8694  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
8695  * and this function can be called upto ops.dispatch_max_batch times to insert
8696  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
8697  * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the
8698  * counter.
8699  *
8700  * This function doesn't have any locking restrictions and may be called under
8701  * BPF locks (in the future when BPF introduces more flexible locking).
8702  *
8703  * @p is allowed to run for @slice. The scheduling path is triggered on slice
8704  * exhaustion. If zero, the current residual slice is maintained. If
8705  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
8706  * scx_bpf_kick_cpu() to trigger scheduling.
8707  *
8708  * Returns %true on successful insertion, %false on failure. On the root
8709  * scheduler, %false return triggers scheduler abort and the caller doesn't need
8710  * to check the return value.
8711  */
8712 __bpf_kfunc bool scx_bpf_dsq_insert___v2(struct task_struct *p, u64 dsq_id,
8713 					 u64 slice, u64 enq_flags,
8714 					 const struct bpf_prog_aux *aux)
8715 {
8716 	struct scx_sched *sch;
8717 
8718 	guard(rcu)();
8719 	sch = scx_prog_sched(aux);
8720 	if (unlikely(!sch))
8721 		return false;
8722 
8723 	if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags))
8724 		return false;
8725 
8726 	if (slice)
8727 		p->scx.slice = slice;
8728 	else
8729 		p->scx.slice = p->scx.slice ?: 1;
8730 
8731 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags);
8732 
8733 	return true;
8734 }
8735 
8736 /*
8737  * COMPAT: Will be removed in v6.23 along with the ___v2 suffix.
8738  */
8739 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id,
8740 				    u64 slice, u64 enq_flags,
8741 				    const struct bpf_prog_aux *aux)
8742 {
8743 	scx_bpf_dsq_insert___v2(p, dsq_id, slice, enq_flags, aux);
8744 }
8745 
8746 static bool scx_dsq_insert_vtime(struct scx_sched *sch, struct task_struct *p,
8747 				 u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
8748 {
8749 	if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags))
8750 		return false;
8751 
8752 	if (slice)
8753 		p->scx.slice = slice;
8754 	else
8755 		p->scx.slice = p->scx.slice ?: 1;
8756 
8757 	p->scx.dsq_vtime = vtime;
8758 
8759 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
8760 
8761 	return true;
8762 }
8763 
8764 struct scx_bpf_dsq_insert_vtime_args {
8765 	/* @p can't be packed together as KF_RCU is not transitive */
8766 	u64			dsq_id;
8767 	u64			slice;
8768 	u64			vtime;
8769 	u64			enq_flags;
8770 };
8771 
8772 /**
8773  * __scx_bpf_dsq_insert_vtime - Arg-wrapped vtime DSQ insertion
8774  * @p: task_struct to insert
8775  * @args: struct containing the rest of the arguments
8776  *       @args->dsq_id: DSQ to insert into
8777  *       @args->slice: duration @p can run for in nsecs, 0 to keep the current value
8778  *       @args->vtime: @p's ordering inside the vtime-sorted queue of the target DSQ
8779  *       @args->enq_flags: SCX_ENQ_*
8780  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8781  *
8782  * Wrapper kfunc that takes arguments via struct to work around BPF's 5 argument
8783  * limit. BPF programs should use scx_bpf_dsq_insert_vtime() which is provided
8784  * as an inline wrapper in common.bpf.h.
8785  *
8786  * Insert @p into the vtime priority queue of the DSQ identified by
8787  * @args->dsq_id. Tasks queued into the priority queue are ordered by
8788  * @args->vtime. All other aspects are identical to scx_bpf_dsq_insert().
8789  *
8790  * @args->vtime ordering is according to time_before64() which considers
8791  * wrapping. A numerically larger vtime may indicate an earlier position in the
8792  * ordering and vice-versa.
8793  *
8794  * A DSQ can only be used as a FIFO or priority queue at any given time and this
8795  * function must not be called on a DSQ which already has one or more FIFO tasks
8796  * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and
8797  * SCX_DSQ_GLOBAL) cannot be used as priority queues.
8798  *
8799  * Returns %true on successful insertion, %false on failure. On the root
8800  * scheduler, %false return triggers scheduler abort and the caller doesn't need
8801  * to check the return value.
8802  */
8803 __bpf_kfunc bool
8804 __scx_bpf_dsq_insert_vtime(struct task_struct *p,
8805 			   struct scx_bpf_dsq_insert_vtime_args *args,
8806 			   const struct bpf_prog_aux *aux)
8807 {
8808 	struct scx_sched *sch;
8809 
8810 	guard(rcu)();
8811 
8812 	sch = scx_prog_sched(aux);
8813 	if (unlikely(!sch))
8814 		return false;
8815 
8816 	return scx_dsq_insert_vtime(sch, p, args->dsq_id, args->slice,
8817 				    args->vtime, args->enq_flags);
8818 }
8819 
8820 /*
8821  * COMPAT: Will be removed in v6.23.
8822  */
8823 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id,
8824 					  u64 slice, u64 vtime, u64 enq_flags)
8825 {
8826 	struct scx_sched *sch;
8827 
8828 	guard(rcu)();
8829 
8830 	sch = rcu_dereference(scx_root);
8831 	if (unlikely(!sch))
8832 		return;
8833 
8834 #ifdef CONFIG_EXT_SUB_SCHED
8835 	/*
8836 	 * Disallow if any sub-scheds are attached. There is no way to tell
8837 	 * which scheduler called us, just error out @p's scheduler.
8838 	 */
8839 	if (unlikely(!list_empty(&sch->children))) {
8840 		scx_error(scx_task_sched(p), "__scx_bpf_dsq_insert_vtime() must be used");
8841 		return;
8842 	}
8843 #endif
8844 
8845 	scx_dsq_insert_vtime(sch, p, dsq_id, slice, vtime, enq_flags);
8846 }
8847 
8848 __bpf_kfunc_end_defs();
8849 
8850 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
8851 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_IMPLICIT_ARGS | KF_RCU)
8852 BTF_ID_FLAGS(func, scx_bpf_dsq_insert___v2, KF_IMPLICIT_ARGS | KF_RCU)
8853 BTF_ID_FLAGS(func, __scx_bpf_dsq_insert_vtime, KF_IMPLICIT_ARGS | KF_RCU)
8854 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU)
8855 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
8856 
8857 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
8858 	.owner			= THIS_MODULE,
8859 	.set			= &scx_kfunc_ids_enqueue_dispatch,
8860 	.filter			= scx_kfunc_context_filter,
8861 };
8862 
8863 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit,
8864 			 struct task_struct *p, u64 dsq_id, u64 enq_flags)
8865 {
8866 	struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq;
8867 	struct scx_sched *sch;
8868 	struct rq *this_rq, *src_rq, *locked_rq;
8869 	bool dispatched = false;
8870 	bool in_balance;
8871 	unsigned long flags;
8872 
8873 	/*
8874 	 * The verifier considers an iterator slot initialized on any
8875 	 * KF_ITER_NEW return, so a BPF program may legally reach here after
8876 	 * bpf_iter_scx_dsq_new() failed and left @kit->dsq NULL.
8877 	 */
8878 	if (unlikely(!src_dsq))
8879 		return false;
8880 
8881 	sch = src_dsq->sched;
8882 
8883 	if (!scx_vet_enq_flags(sch, dsq_id, &enq_flags))
8884 		return false;
8885 
8886 	/*
8887 	 * If the BPF scheduler keeps calling this function repeatedly, it can
8888 	 * cause similar live-lock conditions as consume_dispatch_q().
8889 	 */
8890 	if (unlikely(READ_ONCE(sch->aborting)))
8891 		return false;
8892 
8893 	if (unlikely(!scx_task_on_sched(sch, p))) {
8894 		scx_error(sch, "scx_bpf_dsq_move[_vtime]() on %s[%d] but the task belongs to a different scheduler",
8895 			  p->comm, p->pid);
8896 		return false;
8897 	}
8898 
8899 	/*
8900 	 * Can be called from either ops.dispatch() locking this_rq() or any
8901 	 * context where no rq lock is held. If latter, lock @p's task_rq which
8902 	 * we'll likely need anyway.
8903 	 */
8904 	src_rq = task_rq(p);
8905 
8906 	local_irq_save(flags);
8907 	this_rq = this_rq();
8908 	in_balance = this_rq->scx.flags & SCX_RQ_IN_BALANCE;
8909 
8910 	if (in_balance) {
8911 		if (this_rq != src_rq)
8912 			switch_rq_lock(this_rq, src_rq);
8913 	} else {
8914 		raw_spin_rq_lock(src_rq);
8915 	}
8916 
8917 	locked_rq = src_rq;
8918 	raw_spin_lock(&src_dsq->lock);
8919 
8920 	/* did someone else get to it while we dropped the locks? */
8921 	if (nldsq_cursor_lost_task(&kit->cursor, src_rq, src_dsq, p)) {
8922 		raw_spin_unlock(&src_dsq->lock);
8923 		goto out;
8924 	}
8925 
8926 	/* @p is still on $src_dsq and stable, determine the destination */
8927 	dst_dsq = find_dsq_for_dispatch(sch, this_rq, dsq_id, task_cpu(p));
8928 
8929 	/*
8930 	 * Apply vtime and slice updates before moving so that the new time is
8931 	 * visible before inserting into $dst_dsq. @p is still on $src_dsq but
8932 	 * this is safe as we're locking it.
8933 	 */
8934 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME)
8935 		p->scx.dsq_vtime = kit->vtime;
8936 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE)
8937 		p->scx.slice = kit->slice;
8938 
8939 	/* execute move */
8940 	locked_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq);
8941 	dispatched = true;
8942 out:
8943 	if (in_balance) {
8944 		if (this_rq != locked_rq)
8945 			switch_rq_lock(locked_rq, this_rq);
8946 	} else {
8947 		raw_spin_rq_unlock_irqrestore(locked_rq, flags);
8948 	}
8949 
8950 	kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE |
8951 			       __SCX_DSQ_ITER_HAS_VTIME);
8952 	return dispatched;
8953 }
8954 
8955 __bpf_kfunc_start_defs();
8956 
8957 /**
8958  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
8959  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8960  *
8961  * Can only be called from ops.dispatch().
8962  */
8963 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(const struct bpf_prog_aux *aux)
8964 {
8965 	struct scx_sched *sch;
8966 
8967 	guard(rcu)();
8968 
8969 	sch = scx_prog_sched(aux);
8970 	if (unlikely(!sch))
8971 		return 0;
8972 
8973 	return sch->dsp_max_batch - __this_cpu_read(sch->pcpu->dsp_ctx.cursor);
8974 }
8975 
8976 /**
8977  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
8978  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8979  *
8980  * Cancel the latest dispatch. Can be called multiple times to cancel further
8981  * dispatches. Can only be called from ops.dispatch().
8982  */
8983 __bpf_kfunc void scx_bpf_dispatch_cancel(const struct bpf_prog_aux *aux)
8984 {
8985 	struct scx_sched *sch;
8986 	struct scx_dsp_ctx *dspc;
8987 
8988 	guard(rcu)();
8989 
8990 	sch = scx_prog_sched(aux);
8991 	if (unlikely(!sch))
8992 		return;
8993 
8994 	dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
8995 
8996 	if (dspc->cursor > 0)
8997 		dspc->cursor--;
8998 	else
8999 		scx_error(sch, "dispatch buffer underflow");
9000 }
9001 
9002 /**
9003  * scx_bpf_dsq_move_to_local - move a task from a DSQ to the current CPU's local DSQ
9004  * @dsq_id: DSQ to move task from. Must be a user-created DSQ
9005  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9006  * @enq_flags: %SCX_ENQ_*
9007  *
9008  * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's
9009  * local DSQ for execution with @enq_flags applied. Can only be called from
9010  * ops.dispatch().
9011  *
9012  * Built-in DSQs (%SCX_DSQ_GLOBAL and %SCX_DSQ_LOCAL*) are not supported as
9013  * sources. Local DSQs support reenqueueing (a task can be picked up for
9014  * execution, dequeued for property changes, or reenqueued), but the BPF
9015  * scheduler cannot directly iterate or move tasks from them. %SCX_DSQ_GLOBAL
9016  * is similar but also doesn't support reenqueueing, as it maps to multiple
9017  * per-node DSQs making the scope difficult to define; this may change in the
9018  * future.
9019  *
9020  * This function flushes the in-flight dispatches from scx_bpf_dsq_insert()
9021  * before trying to move from the specified DSQ. It may also grab rq locks and
9022  * thus can't be called under any BPF locks.
9023  *
9024  * Returns %true if a task has been moved, %false if there isn't any task to
9025  * move.
9026  */
9027 __bpf_kfunc bool scx_bpf_dsq_move_to_local___v2(u64 dsq_id, u64 enq_flags,
9028 						const struct bpf_prog_aux *aux)
9029 {
9030 	struct scx_dispatch_q *dsq;
9031 	struct scx_sched *sch;
9032 	struct scx_dsp_ctx *dspc;
9033 
9034 	guard(rcu)();
9035 
9036 	sch = scx_prog_sched(aux);
9037 	if (unlikely(!sch))
9038 		return false;
9039 
9040 	if (!scx_vet_enq_flags(sch, SCX_DSQ_LOCAL, &enq_flags))
9041 		return false;
9042 
9043 	dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
9044 
9045 	flush_dispatch_buf(sch, dspc->rq);
9046 
9047 	dsq = find_user_dsq(sch, dsq_id);
9048 	if (unlikely(!dsq)) {
9049 		scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id);
9050 		return false;
9051 	}
9052 
9053 	if (consume_dispatch_q(sch, dspc->rq, dsq, enq_flags)) {
9054 		/*
9055 		 * A successfully consumed task can be dequeued before it starts
9056 		 * running while the CPU is trying to migrate other dispatched
9057 		 * tasks. Bump nr_tasks to tell balance_one() to retry on empty
9058 		 * local DSQ.
9059 		 */
9060 		dspc->nr_tasks++;
9061 		return true;
9062 	} else {
9063 		return false;
9064 	}
9065 }
9066 
9067 /*
9068  * COMPAT: ___v2 was introduced in v7.1. Remove this and ___v2 tag in the future.
9069  */
9070 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id, const struct bpf_prog_aux *aux)
9071 {
9072 	return scx_bpf_dsq_move_to_local___v2(dsq_id, 0, aux);
9073 }
9074 
9075 /**
9076  * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs
9077  * @it__iter: DSQ iterator in progress
9078  * @slice: duration the moved task can run for in nsecs
9079  *
9080  * Override the slice of the next task that will be moved from @it__iter using
9081  * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous
9082  * slice duration is kept.
9083  */
9084 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter,
9085 					    u64 slice)
9086 {
9087 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
9088 
9089 	kit->slice = slice;
9090 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE;
9091 }
9092 
9093 /**
9094  * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs
9095  * @it__iter: DSQ iterator in progress
9096  * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ
9097  *
9098  * Override the vtime of the next task that will be moved from @it__iter using
9099  * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice
9100  * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the
9101  * override is ignored and cleared.
9102  */
9103 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter,
9104 					    u64 vtime)
9105 {
9106 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
9107 
9108 	kit->vtime = vtime;
9109 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME;
9110 }
9111 
9112 /**
9113  * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ
9114  * @it__iter: DSQ iterator in progress
9115  * @p: task to transfer
9116  * @dsq_id: DSQ to move @p to
9117  * @enq_flags: SCX_ENQ_*
9118  *
9119  * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ
9120  * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can
9121  * be the destination.
9122  *
9123  * For the transfer to be successful, @p must still be on the DSQ and have been
9124  * queued before the DSQ iteration started. This function doesn't care whether
9125  * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have
9126  * been queued before the iteration started.
9127  *
9128  * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update.
9129  *
9130  * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq
9131  * lock (e.g. BPF timers or SYSCALL programs).
9132  *
9133  * Returns %true if @p has been consumed, %false if @p had already been
9134  * consumed, dequeued, or, for sub-scheds, @dsq_id points to a disallowed local
9135  * DSQ.
9136  */
9137 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter,
9138 				  struct task_struct *p, u64 dsq_id,
9139 				  u64 enq_flags)
9140 {
9141 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
9142 			    p, dsq_id, enq_flags);
9143 }
9144 
9145 /**
9146  * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ
9147  * @it__iter: DSQ iterator in progress
9148  * @p: task to transfer
9149  * @dsq_id: DSQ to move @p to
9150  * @enq_flags: SCX_ENQ_*
9151  *
9152  * Transfer @p which is on the DSQ currently iterated by @it__iter to the
9153  * priority queue of the DSQ specified by @dsq_id. The destination must be a
9154  * user DSQ as only user DSQs support priority queue.
9155  *
9156  * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice()
9157  * and scx_bpf_dsq_move_set_vtime() to update.
9158  *
9159  * All other aspects are identical to scx_bpf_dsq_move(). See
9160  * scx_bpf_dsq_insert_vtime() for more information on @vtime.
9161  */
9162 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter,
9163 					struct task_struct *p, u64 dsq_id,
9164 					u64 enq_flags)
9165 {
9166 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
9167 			    p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
9168 }
9169 
9170 #ifdef CONFIG_EXT_SUB_SCHED
9171 /**
9172  * scx_bpf_sub_dispatch - Trigger dispatching on a child scheduler
9173  * @cgroup_id: cgroup ID of the child scheduler to dispatch
9174  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9175  *
9176  * Allows a parent scheduler to trigger dispatching on one of its direct
9177  * child schedulers. The child scheduler runs its dispatch operation to
9178  * move tasks from dispatch queues to the local runqueue.
9179  *
9180  * Returns: true on success, false if cgroup_id is invalid, not a direct
9181  * child, or caller lacks dispatch permission.
9182  */
9183 __bpf_kfunc bool scx_bpf_sub_dispatch(u64 cgroup_id, const struct bpf_prog_aux *aux)
9184 {
9185 	struct rq *this_rq = this_rq();
9186 	struct scx_sched *parent, *child;
9187 
9188 	guard(rcu)();
9189 	parent = scx_prog_sched(aux);
9190 	if (unlikely(!parent))
9191 		return false;
9192 
9193 	child = scx_find_sub_sched(cgroup_id);
9194 
9195 	if (unlikely(!child))
9196 		return false;
9197 
9198 	if (unlikely(scx_parent(child) != parent)) {
9199 		scx_error(parent, "trying to dispatch a distant sub-sched on cgroup %llu",
9200 			  cgroup_id);
9201 		return false;
9202 	}
9203 
9204 	return scx_dispatch_sched(child, this_rq, this_rq->scx.sub_dispatch_prev,
9205 				  true);
9206 }
9207 #endif	/* CONFIG_EXT_SUB_SCHED */
9208 
9209 __bpf_kfunc_end_defs();
9210 
9211 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
9212 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots, KF_IMPLICIT_ARGS)
9213 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel, KF_IMPLICIT_ARGS)
9214 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local, KF_IMPLICIT_ARGS)
9215 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local___v2, KF_IMPLICIT_ARGS)
9216 /* scx_bpf_dsq_move*() also in scx_kfunc_ids_unlocked: callable from unlocked contexts */
9217 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
9218 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
9219 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
9220 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
9221 #ifdef CONFIG_EXT_SUB_SCHED
9222 BTF_ID_FLAGS(func, scx_bpf_sub_dispatch, KF_IMPLICIT_ARGS)
9223 #endif
9224 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
9225 
9226 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
9227 	.owner			= THIS_MODULE,
9228 	.set			= &scx_kfunc_ids_dispatch,
9229 	.filter			= scx_kfunc_context_filter,
9230 };
9231 
9232 __bpf_kfunc_start_defs();
9233 
9234 /**
9235  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
9236  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9237  *
9238  * Iterate over all of the tasks currently enqueued on the local DSQ of the
9239  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
9240  * processed tasks. Can only be called from ops.cpu_release().
9241  */
9242 __bpf_kfunc u32 scx_bpf_reenqueue_local(const struct bpf_prog_aux *aux)
9243 {
9244 	struct scx_sched *sch;
9245 	struct rq *rq;
9246 
9247 	guard(rcu)();
9248 	sch = scx_prog_sched(aux);
9249 	if (unlikely(!sch))
9250 		return 0;
9251 
9252 	rq = cpu_rq(smp_processor_id());
9253 	lockdep_assert_rq_held(rq);
9254 
9255 	return reenq_local(sch, rq, SCX_REENQ_ANY);
9256 }
9257 
9258 __bpf_kfunc_end_defs();
9259 
9260 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
9261 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local, KF_IMPLICIT_ARGS)
9262 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
9263 
9264 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
9265 	.owner			= THIS_MODULE,
9266 	.set			= &scx_kfunc_ids_cpu_release,
9267 	.filter			= scx_kfunc_context_filter,
9268 };
9269 
9270 __bpf_kfunc_start_defs();
9271 
9272 /**
9273  * scx_bpf_create_dsq - Create a custom DSQ
9274  * @dsq_id: DSQ to create
9275  * @node: NUMA node to allocate from
9276  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9277  *
9278  * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable
9279  * scx callback, and any BPF_PROG_TYPE_SYSCALL prog.
9280  */
9281 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node, const struct bpf_prog_aux *aux)
9282 {
9283 	struct scx_dispatch_q *dsq;
9284 	struct scx_sched *sch;
9285 	s32 ret;
9286 
9287 	if (unlikely(node >= (int)nr_node_ids ||
9288 		     (node < 0 && node != NUMA_NO_NODE)))
9289 		return -EINVAL;
9290 
9291 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN))
9292 		return -EINVAL;
9293 
9294 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
9295 	if (!dsq)
9296 		return -ENOMEM;
9297 
9298 	/*
9299 	 * init_dsq() must be called in GFP_KERNEL context. Init it with NULL
9300 	 * @sch and update afterwards.
9301 	 */
9302 	ret = init_dsq(dsq, dsq_id, NULL);
9303 	if (ret) {
9304 		kfree(dsq);
9305 		return ret;
9306 	}
9307 
9308 	rcu_read_lock();
9309 
9310 	sch = scx_prog_sched(aux);
9311 	if (sch) {
9312 		dsq->sched = sch;
9313 		ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node,
9314 						    dsq_hash_params);
9315 	} else {
9316 		ret = -ENODEV;
9317 	}
9318 
9319 	rcu_read_unlock();
9320 	if (ret) {
9321 		exit_dsq(dsq);
9322 		kfree(dsq);
9323 	}
9324 	return ret;
9325 }
9326 
9327 __bpf_kfunc_end_defs();
9328 
9329 BTF_KFUNCS_START(scx_kfunc_ids_unlocked)
9330 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_IMPLICIT_ARGS | KF_SLEEPABLE)
9331 /* also in scx_kfunc_ids_dispatch: also callable from ops.dispatch() */
9332 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
9333 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
9334 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
9335 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
9336 /* also in scx_kfunc_ids_select_cpu: also callable from ops.select_cpu()/ops.enqueue() */
9337 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU)
9338 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU)
9339 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU)
9340 BTF_KFUNCS_END(scx_kfunc_ids_unlocked)
9341 
9342 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = {
9343 	.owner			= THIS_MODULE,
9344 	.set			= &scx_kfunc_ids_unlocked,
9345 	.filter			= scx_kfunc_context_filter,
9346 };
9347 
9348 __bpf_kfunc_start_defs();
9349 
9350 /**
9351  * scx_bpf_task_set_slice - Set task's time slice
9352  * @p: task of interest
9353  * @slice: time slice to set in nsecs
9354  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9355  *
9356  * Set @p's time slice to @slice. Returns %true on success, %false if the
9357  * calling scheduler doesn't have authority over @p.
9358  */
9359 __bpf_kfunc bool scx_bpf_task_set_slice(struct task_struct *p, u64 slice,
9360 					const struct bpf_prog_aux *aux)
9361 {
9362 	struct scx_sched *sch;
9363 
9364 	guard(rcu)();
9365 	sch = scx_prog_sched(aux);
9366 	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
9367 		return false;
9368 
9369 	p->scx.slice = slice;
9370 	return true;
9371 }
9372 
9373 /**
9374  * scx_bpf_task_set_dsq_vtime - Set task's virtual time for DSQ ordering
9375  * @p: task of interest
9376  * @vtime: virtual time to set
9377  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9378  *
9379  * Set @p's virtual time to @vtime. Returns %true on success, %false if the
9380  * calling scheduler doesn't have authority over @p.
9381  */
9382 __bpf_kfunc bool scx_bpf_task_set_dsq_vtime(struct task_struct *p, u64 vtime,
9383 					    const struct bpf_prog_aux *aux)
9384 {
9385 	struct scx_sched *sch;
9386 
9387 	guard(rcu)();
9388 	sch = scx_prog_sched(aux);
9389 	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
9390 		return false;
9391 
9392 	p->scx.dsq_vtime = vtime;
9393 	return true;
9394 }
9395 
9396 static void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags)
9397 {
9398 	struct rq *this_rq;
9399 	unsigned long irq_flags;
9400 
9401 	local_irq_save(irq_flags);
9402 
9403 	this_rq = this_rq();
9404 
9405 	/*
9406 	 * While bypassing for PM ops, IRQ handling may not be online which can
9407 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
9408 	 * IRQ status update. Suppress kicking.
9409 	 */
9410 	if (scx_bypassing(sch, cpu_of(this_rq)))
9411 		goto out;
9412 
9413 	/*
9414 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
9415 	 * rq locks. We can probably be smarter and avoid bouncing if called
9416 	 * from ops which don't hold a rq lock.
9417 	 */
9418 	if (flags & SCX_KICK_IDLE) {
9419 		struct rq *target_rq = cpu_rq(cpu);
9420 
9421 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT)))
9422 			scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
9423 
9424 		if (raw_spin_rq_trylock(target_rq)) {
9425 			if (can_skip_idle_kick(target_rq)) {
9426 				raw_spin_rq_unlock(target_rq);
9427 				goto out;
9428 			}
9429 			raw_spin_rq_unlock(target_rq);
9430 		}
9431 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick_if_idle);
9432 	} else {
9433 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick);
9434 
9435 		if (flags & SCX_KICK_PREEMPT)
9436 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_preempt);
9437 		if (flags & SCX_KICK_WAIT)
9438 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_wait);
9439 	}
9440 
9441 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
9442 out:
9443 	local_irq_restore(irq_flags);
9444 }
9445 
9446 /**
9447  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
9448  * @cpu: cpu to kick
9449  * @flags: %SCX_KICK_* flags
9450  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9451  *
9452  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
9453  * trigger rescheduling on a busy CPU. This can be called from any online
9454  * scx_ops operation and the actual kicking is performed asynchronously through
9455  * an irq work.
9456  */
9457 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags, const struct bpf_prog_aux *aux)
9458 {
9459 	struct scx_sched *sch;
9460 
9461 	guard(rcu)();
9462 	sch = scx_prog_sched(aux);
9463 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
9464 		scx_kick_cpu(sch, cpu, flags);
9465 }
9466 
9467 /**
9468  * scx_bpf_kick_cid - Trigger reschedule on the CPU mapped to @cid
9469  * @cid: cid to kick
9470  * @flags: %SCX_KICK_* flags
9471  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9472  *
9473  * cid-addressed equivalent of scx_bpf_kick_cpu(). Return 0 on success,
9474  * -errno otherwise.
9475  */
9476 __bpf_kfunc s32 scx_bpf_kick_cid(s32 cid, u64 flags, const struct bpf_prog_aux *aux)
9477 {
9478 	struct scx_sched *sch;
9479 	s32 cpu;
9480 
9481 	guard(rcu)();
9482 	sch = scx_prog_sched(aux);
9483 	if (unlikely(!sch))
9484 		return -ENODEV;
9485 	cpu = scx_cid_to_cpu(sch, cid);
9486 	if (cpu < 0)
9487 		return cpu;
9488 	scx_kick_cpu(sch, cpu, flags);
9489 	return 0;
9490 }
9491 
9492 /**
9493  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
9494  * @dsq_id: id of the DSQ
9495  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9496  *
9497  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
9498  * -%ENOENT is returned.
9499  */
9500 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id, const struct bpf_prog_aux *aux)
9501 {
9502 	struct scx_sched *sch;
9503 	struct scx_dispatch_q *dsq;
9504 	s32 ret;
9505 
9506 	preempt_disable();
9507 
9508 	sch = scx_prog_sched(aux);
9509 	if (unlikely(!sch)) {
9510 		ret = -ENODEV;
9511 		goto out;
9512 	}
9513 
9514 	if (dsq_id == SCX_DSQ_LOCAL) {
9515 		ret = READ_ONCE(this_rq()->scx.local_dsq.nr);
9516 		goto out;
9517 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
9518 		s32 cpu = scx_cpu_ret(sch, dsq_id & SCX_DSQ_LOCAL_CPU_MASK);
9519 
9520 		if (scx_cpu_valid(sch, cpu, NULL)) {
9521 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
9522 			goto out;
9523 		}
9524 	} else {
9525 		dsq = find_user_dsq(sch, dsq_id);
9526 		if (dsq) {
9527 			ret = READ_ONCE(dsq->nr);
9528 			goto out;
9529 		}
9530 	}
9531 	ret = -ENOENT;
9532 out:
9533 	preempt_enable();
9534 	return ret;
9535 }
9536 
9537 /**
9538  * scx_bpf_destroy_dsq - Destroy a custom DSQ
9539  * @dsq_id: DSQ to destroy
9540  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9541  *
9542  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
9543  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
9544  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
9545  * which doesn't exist. Can be called from any online scx_ops operations.
9546  */
9547 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id, const struct bpf_prog_aux *aux)
9548 {
9549 	struct scx_sched *sch;
9550 
9551 	guard(rcu)();
9552 	sch = scx_prog_sched(aux);
9553 	if (sch)
9554 		destroy_dsq(sch, dsq_id);
9555 }
9556 
9557 /**
9558  * bpf_iter_scx_dsq_new - Create a DSQ iterator
9559  * @it: iterator to initialize
9560  * @dsq_id: DSQ to iterate
9561  * @flags: %SCX_DSQ_ITER_*
9562  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9563  *
9564  * Initialize BPF iterator @it which can be used with bpf_for_each() to walk
9565  * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes
9566  * tasks which are already queued when this function is invoked.
9567  */
9568 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id,
9569 				     u64 flags, const struct bpf_prog_aux *aux)
9570 {
9571 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
9572 	struct scx_sched *sch;
9573 
9574 	BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) >
9575 		     sizeof(struct bpf_iter_scx_dsq));
9576 	BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) !=
9577 		     __alignof__(struct bpf_iter_scx_dsq));
9578 	BUILD_BUG_ON(__SCX_DSQ_ITER_ALL_FLAGS &
9579 		     ((1U << __SCX_DSQ_LNODE_PRIV_SHIFT) - 1));
9580 
9581 	/*
9582 	 * next() and destroy() will be called regardless of the return value.
9583 	 * Always clear $kit->dsq.
9584 	 */
9585 	kit->dsq = NULL;
9586 
9587 	sch = scx_prog_sched(aux);
9588 	if (unlikely(!sch))
9589 		return -ENODEV;
9590 
9591 	if (flags & ~__SCX_DSQ_ITER_USER_FLAGS)
9592 		return -EINVAL;
9593 
9594 	kit->dsq = find_user_dsq(sch, dsq_id);
9595 	if (!kit->dsq)
9596 		return -ENOENT;
9597 
9598 	kit->cursor = INIT_DSQ_LIST_CURSOR(kit->cursor, kit->dsq, flags);
9599 
9600 	return 0;
9601 }
9602 
9603 /**
9604  * bpf_iter_scx_dsq_next - Progress a DSQ iterator
9605  * @it: iterator to progress
9606  *
9607  * Return the next task. See bpf_iter_scx_dsq_new().
9608  */
9609 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it)
9610 {
9611 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
9612 
9613 	if (!kit->dsq)
9614 		return NULL;
9615 
9616 	guard(raw_spinlock_irqsave)(&kit->dsq->lock);
9617 
9618 	return nldsq_cursor_next_task(&kit->cursor, kit->dsq);
9619 }
9620 
9621 /**
9622  * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator
9623  * @it: iterator to destroy
9624  *
9625  * Undo scx_iter_scx_dsq_new().
9626  */
9627 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it)
9628 {
9629 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
9630 
9631 	if (!kit->dsq)
9632 		return;
9633 
9634 	if (!list_empty(&kit->cursor.node)) {
9635 		unsigned long flags;
9636 
9637 		raw_spin_lock_irqsave(&kit->dsq->lock, flags);
9638 		list_del_init(&kit->cursor.node);
9639 		raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
9640 	}
9641 	kit->dsq = NULL;
9642 }
9643 
9644 /**
9645  * scx_bpf_dsq_peek - Lockless peek at the first element.
9646  * @dsq_id: DSQ to examine.
9647  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9648  *
9649  * Read the first element in the DSQ. This is semantically equivalent to using
9650  * the DSQ iterator, but is lockfree. Of course, like any lockless operation,
9651  * this provides only a point-in-time snapshot, and the contents may change
9652  * by the time any subsequent locking operation reads the queue.
9653  *
9654  * Returns the pointer, or NULL indicates an empty queue OR internal error.
9655  */
9656 __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id,
9657 						 const struct bpf_prog_aux *aux)
9658 {
9659 	struct scx_sched *sch;
9660 	struct scx_dispatch_q *dsq;
9661 
9662 	sch = scx_prog_sched(aux);
9663 	if (unlikely(!sch))
9664 		return NULL;
9665 
9666 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) {
9667 		scx_error(sch, "peek disallowed on builtin DSQ 0x%llx", dsq_id);
9668 		return NULL;
9669 	}
9670 
9671 	dsq = find_user_dsq(sch, dsq_id);
9672 	if (unlikely(!dsq)) {
9673 		scx_error(sch, "peek on non-existent DSQ 0x%llx", dsq_id);
9674 		return NULL;
9675 	}
9676 
9677 	return rcu_dereference(dsq->first_task);
9678 }
9679 
9680 /**
9681  * scx_bpf_dsq_reenq - Re-enqueue tasks on a DSQ
9682  * @dsq_id: DSQ to re-enqueue
9683  * @reenq_flags: %SCX_RENQ_*
9684  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9685  *
9686  * Iterate over all of the tasks currently enqueued on the DSQ identified by
9687  * @dsq_id, and re-enqueue them in the BPF scheduler. The following DSQs are
9688  * supported:
9689  *
9690  * - Local DSQs (%SCX_DSQ_LOCAL or %SCX_DSQ_LOCAL_ON | $cpu)
9691  * - User DSQs
9692  *
9693  * Re-enqueues are performed asynchronously. Can be called from anywhere.
9694  */
9695 __bpf_kfunc void scx_bpf_dsq_reenq(u64 dsq_id, u64 reenq_flags,
9696 				   const struct bpf_prog_aux *aux)
9697 {
9698 	struct scx_sched *sch;
9699 	struct scx_dispatch_q *dsq;
9700 
9701 	guard(preempt)();
9702 
9703 	sch = scx_prog_sched(aux);
9704 	if (unlikely(!sch))
9705 		return;
9706 
9707 	if (unlikely(reenq_flags & ~__SCX_REENQ_USER_MASK)) {
9708 		scx_error(sch, "invalid SCX_REENQ flags 0x%llx", reenq_flags);
9709 		return;
9710 	}
9711 
9712 	/* not specifying any filter bits is the same as %SCX_REENQ_ANY */
9713 	if (!(reenq_flags & __SCX_REENQ_FILTER_MASK))
9714 		reenq_flags |= SCX_REENQ_ANY;
9715 
9716 	dsq = find_dsq_for_dispatch(sch, this_rq(), dsq_id, smp_processor_id());
9717 	schedule_dsq_reenq(sch, dsq, reenq_flags, scx_locked_rq());
9718 }
9719 
9720 /**
9721  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
9722  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9723  *
9724  * Iterate over all of the tasks currently enqueued on the local DSQ of the
9725  * caller's CPU, and re-enqueue them in the BPF scheduler. Can be called from
9726  * anywhere.
9727  *
9728  * This is now a special case of scx_bpf_dsq_reenq() and may be removed in the
9729  * future.
9730  */
9731 __bpf_kfunc void scx_bpf_reenqueue_local___v2(const struct bpf_prog_aux *aux)
9732 {
9733 	scx_bpf_dsq_reenq(SCX_DSQ_LOCAL, 0, aux);
9734 }
9735 
9736 __bpf_kfunc_end_defs();
9737 
9738 __printf(5, 0)
9739 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
9740 			 size_t line_size, char *fmt, unsigned long long *data,
9741 			 u32 data__sz)
9742 {
9743 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
9744 	s32 ret;
9745 
9746 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
9747 	    (data__sz && !data)) {
9748 		scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz);
9749 		return -EINVAL;
9750 	}
9751 
9752 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
9753 	if (ret < 0) {
9754 		scx_error(sch, "failed to read data fields (%d)", ret);
9755 		return ret;
9756 	}
9757 
9758 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
9759 				  &bprintf_data);
9760 	if (ret < 0) {
9761 		scx_error(sch, "format preparation failed (%d)", ret);
9762 		return ret;
9763 	}
9764 
9765 	ret = bstr_printf(line_buf, line_size, fmt,
9766 			  bprintf_data.bin_args);
9767 	bpf_bprintf_cleanup(&bprintf_data);
9768 	if (ret < 0) {
9769 		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
9770 		return ret;
9771 	}
9772 
9773 	return ret;
9774 }
9775 
9776 __printf(3, 0)
9777 static s32 bstr_format(struct scx_sched *sch, struct scx_bstr_buf *buf,
9778 		       char *fmt, unsigned long long *data, u32 data__sz)
9779 {
9780 	return __bstr_format(sch, buf->data, buf->line, sizeof(buf->line),
9781 			     fmt, data, data__sz);
9782 }
9783 
9784 __bpf_kfunc_start_defs();
9785 
9786 /**
9787  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
9788  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
9789  * @fmt: error message format string
9790  * @data: format string parameters packaged using ___bpf_fill() macro
9791  * @data__sz: @data len, must end in '__sz' for the verifier
9792  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9793  *
9794  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
9795  * disabling.
9796  */
9797 __printf(2, 0)
9798 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
9799 				   unsigned long long *data, u32 data__sz,
9800 				   const struct bpf_prog_aux *aux)
9801 {
9802 	struct scx_sched *sch;
9803 	unsigned long flags;
9804 
9805 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
9806 	sch = scx_prog_sched(aux);
9807 	if (likely(sch) &&
9808 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
9809 		scx_exit(sch, SCX_EXIT_UNREG_BPF, exit_code, "%s", scx_exit_bstr_buf.line);
9810 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
9811 }
9812 
9813 /**
9814  * scx_bpf_error_bstr - Indicate fatal error
9815  * @fmt: error message format string
9816  * @data: format string parameters packaged using ___bpf_fill() macro
9817  * @data__sz: @data len, must end in '__sz' for the verifier
9818  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9819  *
9820  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
9821  * disabling.
9822  */
9823 __printf(1, 0)
9824 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
9825 				    u32 data__sz, const struct bpf_prog_aux *aux)
9826 {
9827 	struct scx_sched *sch;
9828 	unsigned long flags;
9829 
9830 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
9831 	sch = scx_prog_sched(aux);
9832 	if (likely(sch) &&
9833 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
9834 		scx_exit(sch, SCX_EXIT_ERROR_BPF, 0, "%s", scx_exit_bstr_buf.line);
9835 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
9836 }
9837 
9838 /**
9839  * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler
9840  * @fmt: format string
9841  * @data: format string parameters packaged using ___bpf_fill() macro
9842  * @data__sz: @data len, must end in '__sz' for the verifier
9843  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9844  *
9845  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
9846  * dump_task() to generate extra debug dump specific to the BPF scheduler.
9847  *
9848  * The extra dump may be multiple lines. A single line may be split over
9849  * multiple calls. The last line is automatically terminated.
9850  */
9851 __printf(1, 0)
9852 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
9853 				   u32 data__sz, const struct bpf_prog_aux *aux)
9854 {
9855 	struct scx_sched *sch;
9856 	struct scx_dump_data *dd = &scx_dump_data;
9857 	struct scx_bstr_buf *buf = &dd->buf;
9858 	s32 ret;
9859 
9860 	guard(rcu)();
9861 
9862 	sch = scx_prog_sched(aux);
9863 	if (unlikely(!sch))
9864 		return;
9865 
9866 	if (raw_smp_processor_id() != dd->cpu) {
9867 		scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends");
9868 		return;
9869 	}
9870 
9871 	/* append the formatted string to the line buf */
9872 	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
9873 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
9874 	if (ret < 0) {
9875 		dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
9876 			  dd->prefix, fmt, data, data__sz, ret);
9877 		return;
9878 	}
9879 
9880 	dd->cursor += ret;
9881 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
9882 
9883 	if (!dd->cursor)
9884 		return;
9885 
9886 	/*
9887 	 * If the line buf overflowed or ends in a newline, flush it into the
9888 	 * dump. This is to allow the caller to generate a single line over
9889 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
9890 	 * the line buf, the only case which can lead to an unexpected
9891 	 * truncation is when the caller keeps generating newlines in the middle
9892 	 * instead of the end consecutively. Don't do that.
9893 	 */
9894 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
9895 		ops_dump_flush();
9896 }
9897 
9898 /**
9899  * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU
9900  * @cpu: CPU of interest
9901  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9902  *
9903  * Return the maximum relative capacity of @cpu in relation to the most
9904  * performant CPU in the system. The return value is in the range [1,
9905  * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur().
9906  */
9907 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu, const struct bpf_prog_aux *aux)
9908 {
9909 	struct scx_sched *sch;
9910 
9911 	guard(rcu)();
9912 
9913 	sch = scx_prog_sched(aux);
9914 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
9915 		return arch_scale_cpu_capacity(cpu);
9916 	else
9917 		return SCX_CPUPERF_ONE;
9918 }
9919 
9920 /**
9921  * scx_bpf_cidperf_cap - Query the maximum relative capacity of the CPU at @cid
9922  * @cid: cid of the CPU to query
9923  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9924  *
9925  * cid-addressed equivalent of scx_bpf_cpuperf_cap().
9926  */
9927 __bpf_kfunc u32 scx_bpf_cidperf_cap(s32 cid, const struct bpf_prog_aux *aux)
9928 {
9929 	struct scx_sched *sch;
9930 	s32 cpu;
9931 
9932 	guard(rcu)();
9933 
9934 	sch = scx_prog_sched(aux);
9935 	if (unlikely(!sch))
9936 		return SCX_CPUPERF_ONE;
9937 	cpu = scx_cid_to_cpu(sch, cid);
9938 	if (cpu < 0)
9939 		return SCX_CPUPERF_ONE;
9940 	return arch_scale_cpu_capacity(cpu);
9941 }
9942 
9943 /**
9944  * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU
9945  * @cpu: CPU of interest
9946  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9947  *
9948  * Return the current relative performance of @cpu in relation to its maximum.
9949  * The return value is in the range [1, %SCX_CPUPERF_ONE].
9950  *
9951  * The current performance level of a CPU in relation to the maximum performance
9952  * available in the system can be calculated as follows:
9953  *
9954  *   scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE
9955  *
9956  * The result is in the range [1, %SCX_CPUPERF_ONE].
9957  */
9958 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu, const struct bpf_prog_aux *aux)
9959 {
9960 	struct scx_sched *sch;
9961 
9962 	guard(rcu)();
9963 
9964 	sch = scx_prog_sched(aux);
9965 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
9966 		return arch_scale_freq_capacity(cpu);
9967 	else
9968 		return SCX_CPUPERF_ONE;
9969 }
9970 
9971 /**
9972  * scx_bpf_cidperf_cur - Query the current performance of the CPU at @cid
9973  * @cid: cid of the CPU to query
9974  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9975  *
9976  * cid-addressed equivalent of scx_bpf_cpuperf_cur().
9977  */
9978 __bpf_kfunc u32 scx_bpf_cidperf_cur(s32 cid, const struct bpf_prog_aux *aux)
9979 {
9980 	struct scx_sched *sch;
9981 	s32 cpu;
9982 
9983 	guard(rcu)();
9984 
9985 	sch = scx_prog_sched(aux);
9986 	if (unlikely(!sch))
9987 		return SCX_CPUPERF_ONE;
9988 	cpu = scx_cid_to_cpu(sch, cid);
9989 	if (cpu < 0)
9990 		return SCX_CPUPERF_ONE;
9991 	return arch_scale_freq_capacity(cpu);
9992 }
9993 
9994 /**
9995  * scx_bpf_cpuperf_set - Set the relative performance target of a CPU
9996  * @cpu: CPU of interest
9997  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
9998  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9999  *
10000  * Set the target performance level of @cpu to @perf. @perf is in linear
10001  * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the
10002  * schedutil cpufreq governor chooses the target frequency.
10003  *
10004  * The actual performance level chosen, CPU grouping, and the overhead and
10005  * latency of the operations are dependent on the hardware and cpufreq driver in
10006  * use. Consult hardware and cpufreq documentation for more information. The
10007  * current performance level can be monitored using scx_bpf_cpuperf_cur().
10008  */
10009 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf, const struct bpf_prog_aux *aux)
10010 {
10011 	struct scx_sched *sch;
10012 
10013 	guard(rcu)();
10014 
10015 	sch = scx_prog_sched(aux);
10016 	if (unlikely(!sch))
10017 		return;
10018 
10019 	if (unlikely(perf > SCX_CPUPERF_ONE)) {
10020 		scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu);
10021 		return;
10022 	}
10023 
10024 	if (scx_cpu_valid(sch, cpu, NULL)) {
10025 		struct rq *rq = cpu_rq(cpu), *locked_rq = scx_locked_rq();
10026 		struct rq_flags rf;
10027 
10028 		/*
10029 		 * When called with an rq lock held, restrict the operation
10030 		 * to the corresponding CPU to prevent ABBA deadlocks.
10031 		 */
10032 		if (locked_rq && rq != locked_rq) {
10033 			scx_error(sch, "Invalid target CPU %d", cpu);
10034 			return;
10035 		}
10036 
10037 		/*
10038 		 * If no rq lock is held, allow to operate on any CPU by
10039 		 * acquiring the corresponding rq lock.
10040 		 */
10041 		if (!locked_rq) {
10042 			rq_lock_irqsave(rq, &rf);
10043 			update_rq_clock(rq);
10044 		}
10045 
10046 		rq->scx.cpuperf_target = perf;
10047 		cpufreq_update_util(rq, 0);
10048 
10049 		if (!locked_rq)
10050 			rq_unlock_irqrestore(rq, &rf);
10051 	}
10052 }
10053 
10054 /**
10055  * scx_bpf_cidperf_set - Set the performance target of the CPU at @cid
10056  * @cid: cid of the CPU to target
10057  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
10058  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10059  *
10060  * cid-addressed equivalent of scx_bpf_cpuperf_set().
10061  */
10062 __bpf_kfunc void scx_bpf_cidperf_set(s32 cid, u32 perf,
10063 				     const struct bpf_prog_aux *aux)
10064 {
10065 	struct scx_sched *sch;
10066 	s32 cpu;
10067 
10068 	guard(rcu)();
10069 
10070 	sch = scx_prog_sched(aux);
10071 	if (unlikely(!sch))
10072 		return;
10073 	cpu = scx_cid_to_cpu(sch, cid);
10074 	if (cpu < 0)
10075 		return;
10076 	scx_bpf_cpuperf_set(cpu, perf, aux);
10077 }
10078 
10079 /**
10080  * scx_bpf_nr_node_ids - Return the number of possible node IDs
10081  *
10082  * All valid node IDs in the system are smaller than the returned value.
10083  */
10084 __bpf_kfunc u32 scx_bpf_nr_node_ids(void)
10085 {
10086 	return nr_node_ids;
10087 }
10088 
10089 /**
10090  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
10091  *
10092  * All valid CPU IDs in the system are smaller than the returned value.
10093  */
10094 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
10095 {
10096 	return nr_cpu_ids;
10097 }
10098 
10099 /**
10100  * scx_bpf_nr_cids - Return the size of the cid space
10101  *
10102  * Equals num_possible_cpus(). All valid cids are in [0, return value).
10103  */
10104 __bpf_kfunc u32 scx_bpf_nr_cids(void)
10105 {
10106 	return num_possible_cpus();
10107 }
10108 
10109 /**
10110  * scx_bpf_nr_online_cids - Return current count of online CPUs in cid space
10111  *
10112  * Return num_online_cpus(). The standard model restarts the scheduler on
10113  * hotplug, which lets schedulers treat [0, nr_online_cids) as the online
10114  * range. Schedulers that prefer to handle hotplug without a restart should
10115  * install a custom mapping via scx_bpf_cid_override() and track onlining
10116  * through the ops.cid_online / ops.cid_offline callbacks.
10117  */
10118 __bpf_kfunc u32 scx_bpf_nr_online_cids(void)
10119 {
10120 	return num_online_cpus();
10121 }
10122 
10123 /**
10124  * scx_bpf_this_cid - Return the cid of the CPU this program is running on
10125  *
10126  * cid-addressed equivalent of bpf_get_smp_processor_id() for scx programs.
10127  * The current cpu is trivially valid, so this is just a table lookup. Return
10128  * -EINVAL if called from a non-SCX program before any scheduler has ever
10129  * been enabled (the cid table is still unallocated at that point).
10130  */
10131 __bpf_kfunc s32 scx_bpf_this_cid(void)
10132 {
10133 	s16 *tbl = READ_ONCE(scx_cpu_to_cid_tbl);
10134 
10135 	if (!tbl)
10136 		return -EINVAL;
10137 	return tbl[raw_smp_processor_id()];
10138 }
10139 
10140 /**
10141  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
10142  */
10143 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
10144 {
10145 	return cpu_possible_mask;
10146 }
10147 
10148 /**
10149  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
10150  */
10151 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
10152 {
10153 	return cpu_online_mask;
10154 }
10155 
10156 /**
10157  * scx_bpf_put_cpumask - Release a possible/online cpumask
10158  * @cpumask: cpumask to release
10159  */
10160 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
10161 {
10162 	/*
10163 	 * Empty function body because we aren't actually acquiring or releasing
10164 	 * a reference to a global cpumask, which is read-only in the caller and
10165 	 * is never released. The acquire / release semantics here are just used
10166 	 * to make the cpumask is a trusted pointer in the caller.
10167 	 */
10168 }
10169 
10170 /**
10171  * scx_bpf_task_running - Is task currently running?
10172  * @p: task of interest
10173  */
10174 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
10175 {
10176 	return task_rq(p)->curr == p;
10177 }
10178 
10179 /**
10180  * scx_bpf_task_cpu - CPU a task is currently associated with
10181  * @p: task of interest
10182  */
10183 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
10184 {
10185 	return task_cpu(p);
10186 }
10187 
10188 /**
10189  * scx_bpf_task_cid - cid a task is currently associated with
10190  * @p: task of interest
10191  *
10192  * cid-addressed equivalent of scx_bpf_task_cpu(). task_cpu(p) is always a
10193  * valid cpu, so this is just a table lookup. Return -EINVAL if called from
10194  * a non-SCX program before any scheduler has ever been enabled.
10195  */
10196 __bpf_kfunc s32 scx_bpf_task_cid(const struct task_struct *p)
10197 {
10198 	s16 *tbl = READ_ONCE(scx_cpu_to_cid_tbl);
10199 
10200 	if (!tbl)
10201 		return -EINVAL;
10202 	return tbl[task_cpu(p)];
10203 }
10204 
10205 /**
10206  * scx_bpf_cpu_rq - Fetch the rq of a CPU
10207  * @cpu: CPU of the rq
10208  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10209  */
10210 __bpf_kfunc struct rq *scx_bpf_cpu_rq(s32 cpu, const struct bpf_prog_aux *aux)
10211 {
10212 	struct scx_sched *sch;
10213 
10214 	guard(rcu)();
10215 
10216 	sch = scx_prog_sched(aux);
10217 	if (unlikely(!sch))
10218 		return NULL;
10219 
10220 	if (!scx_cpu_valid(sch, cpu, NULL))
10221 		return NULL;
10222 
10223 	if (!sch->warned_deprecated_rq) {
10224 		printk_deferred(KERN_WARNING "sched_ext: %s() is deprecated; "
10225 				"use scx_bpf_locked_rq() when holding rq lock "
10226 				"or scx_bpf_cpu_curr() to read remote curr safely.\n", __func__);
10227 		sch->warned_deprecated_rq = true;
10228 	}
10229 
10230 	return cpu_rq(cpu);
10231 }
10232 
10233 /**
10234  * scx_bpf_locked_rq - Return the rq currently locked by SCX
10235  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10236  *
10237  * Returns the rq if a rq lock is currently held by SCX.
10238  * Otherwise emits an error and returns NULL.
10239  */
10240 __bpf_kfunc struct rq *scx_bpf_locked_rq(const struct bpf_prog_aux *aux)
10241 {
10242 	struct scx_sched *sch;
10243 	struct rq *rq;
10244 
10245 	guard(preempt)();
10246 
10247 	sch = scx_prog_sched(aux);
10248 	if (unlikely(!sch))
10249 		return NULL;
10250 
10251 	rq = scx_locked_rq();
10252 	if (!rq) {
10253 		scx_error(sch, "accessing rq without holding rq lock");
10254 		return NULL;
10255 	}
10256 
10257 	return rq;
10258 }
10259 
10260 /**
10261  * scx_bpf_cpu_curr - Return remote CPU's curr task
10262  * @cpu: CPU of interest
10263  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10264  *
10265  * Callers must hold RCU read lock (KF_RCU).
10266  */
10267 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_aux *aux)
10268 {
10269 	struct scx_sched *sch;
10270 
10271 	guard(rcu)();
10272 
10273 	sch = scx_prog_sched(aux);
10274 	if (unlikely(!sch))
10275 		return NULL;
10276 
10277 	if (!scx_cpu_valid(sch, cpu, NULL))
10278 		return NULL;
10279 
10280 	return rcu_dereference(cpu_rq(cpu)->curr);
10281 }
10282 
10283 /**
10284  * scx_bpf_cid_curr - Return the curr task on the CPU at @cid
10285  * @cid: cid of interest
10286  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10287  *
10288  * cid-addressed equivalent of scx_bpf_cpu_curr(). Callers must hold RCU
10289  * read lock (KF_RCU).
10290  */
10291 __bpf_kfunc struct task_struct *scx_bpf_cid_curr(s32 cid, const struct bpf_prog_aux *aux)
10292 {
10293 	struct scx_sched *sch;
10294 	s32 cpu;
10295 
10296 	guard(rcu)();
10297 
10298 	sch = scx_prog_sched(aux);
10299 	if (unlikely(!sch))
10300 		return NULL;
10301 	cpu = scx_cid_to_cpu(sch, cid);
10302 	if (cpu < 0)
10303 		return NULL;
10304 	return rcu_dereference(cpu_rq(cpu)->curr);
10305 }
10306 
10307 /**
10308  * scx_bpf_tid_to_task - Look up a task by its scx tid
10309  * @tid: task ID previously read from p->scx.tid
10310  *
10311  * Returns the task with the given tid, or NULL if no such task exists. The
10312  * returned pointer is valid until the end of the current RCU read section
10313  * (KF_RCU_PROTECTED). Requires SCX_OPS_TID_TO_TASK to be set on the root
10314  * scheduler; otherwise an error is raised and NULL returned.
10315  */
10316 __bpf_kfunc struct task_struct *scx_bpf_tid_to_task(u64 tid)
10317 {
10318 	struct sched_ext_entity *scx;
10319 
10320 	if (!scx_tid_to_task_enabled()) {
10321 		struct scx_sched *sch = rcu_dereference(scx_root);
10322 
10323 		if (sch)
10324 			scx_error(sch, "scx_bpf_tid_to_task() called without SCX_OPS_TID_TO_TASK");
10325 		return NULL;
10326 	}
10327 
10328 	scx = rhashtable_lookup(&scx_tid_hash, &tid, scx_tid_hash_params);
10329 	if (!scx)
10330 		return NULL;
10331 
10332 	return container_of(scx, struct task_struct, scx);
10333 }
10334 
10335 /**
10336  * scx_bpf_now - Returns a high-performance monotonically non-decreasing
10337  * clock for the current CPU. The clock returned is in nanoseconds.
10338  *
10339  * It provides the following properties:
10340  *
10341  * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently
10342  *  to account for execution time and track tasks' runtime properties.
10343  *  Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which
10344  *  eventually reads a hardware timestamp counter -- is neither performant nor
10345  *  scalable. scx_bpf_now() aims to provide a high-performance clock by
10346  *  using the rq clock in the scheduler core whenever possible.
10347  *
10348  * 2) High enough resolution for the BPF scheduler use cases: In most BPF
10349  *  scheduler use cases, the required clock resolution is lower than the most
10350  *  accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically
10351  *  uses the rq clock in the scheduler core whenever it is valid. It considers
10352  *  that the rq clock is valid from the time the rq clock is updated
10353  *  (update_rq_clock) until the rq is unlocked (rq_unpin_lock).
10354  *
10355  * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now()
10356  *  guarantees the clock never goes backward when comparing them in the same
10357  *  CPU. On the other hand, when comparing clocks in different CPUs, there
10358  *  is no such guarantee -- the clock can go backward. It provides a
10359  *  monotonically *non-decreasing* clock so that it would provide the same
10360  *  clock values in two different scx_bpf_now() calls in the same CPU
10361  *  during the same period of when the rq clock is valid.
10362  */
10363 __bpf_kfunc u64 scx_bpf_now(void)
10364 {
10365 	struct rq *rq;
10366 	u64 clock;
10367 
10368 	preempt_disable();
10369 
10370 	rq = this_rq();
10371 	if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) {
10372 		/*
10373 		 * If the rq clock is valid, use the cached rq clock.
10374 		 *
10375 		 * Note that scx_bpf_now() is re-entrant between a process
10376 		 * context and an interrupt context (e.g., timer interrupt).
10377 		 * However, we don't need to consider the race between them
10378 		 * because such race is not observable from a caller.
10379 		 */
10380 		clock = READ_ONCE(rq->scx.clock);
10381 	} else {
10382 		/*
10383 		 * Otherwise, return a fresh rq clock.
10384 		 *
10385 		 * The rq clock is updated outside of the rq lock.
10386 		 * In this case, keep the updated rq clock invalid so the next
10387 		 * kfunc call outside the rq lock gets a fresh rq clock.
10388 		 */
10389 		clock = sched_clock_cpu(cpu_of(rq));
10390 	}
10391 
10392 	preempt_enable();
10393 
10394 	return clock;
10395 }
10396 
10397 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events)
10398 {
10399 	struct scx_event_stats *e_cpu;
10400 	int cpu;
10401 
10402 	/* Aggregate per-CPU event counters into @events. */
10403 	memset(events, 0, sizeof(*events));
10404 	for_each_possible_cpu(cpu) {
10405 		e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats;
10406 		scx_agg_event(events, e_cpu, SCX_EV_SELECT_CPU_FALLBACK);
10407 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
10408 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_KEEP_LAST);
10409 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_EXITING);
10410 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
10411 		scx_agg_event(events, e_cpu, SCX_EV_REENQ_IMMED);
10412 		scx_agg_event(events, e_cpu, SCX_EV_REENQ_LOCAL_REPEAT);
10413 		scx_agg_event(events, e_cpu, SCX_EV_REFILL_SLICE_DFL);
10414 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DURATION);
10415 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DISPATCH);
10416 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_ACTIVATE);
10417 		scx_agg_event(events, e_cpu, SCX_EV_INSERT_NOT_OWNED);
10418 		scx_agg_event(events, e_cpu, SCX_EV_SUB_BYPASS_DISPATCH);
10419 	}
10420 }
10421 
10422 /*
10423  * scx_bpf_events - Get a system-wide event counter to
10424  * @events: output buffer from a BPF program
10425  * @events__sz: @events len, must end in '__sz'' for the verifier
10426  */
10427 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events,
10428 				size_t events__sz)
10429 {
10430 	struct scx_sched *sch;
10431 	struct scx_event_stats e_sys;
10432 
10433 	rcu_read_lock();
10434 	sch = rcu_dereference(scx_root);
10435 	if (sch)
10436 		scx_read_events(sch, &e_sys);
10437 	else
10438 		memset(&e_sys, 0, sizeof(e_sys));
10439 	rcu_read_unlock();
10440 
10441 	/*
10442 	 * We cannot entirely trust a BPF-provided size since a BPF program
10443 	 * might be compiled against a different vmlinux.h, of which
10444 	 * scx_event_stats would be larger (a newer vmlinux.h) or smaller
10445 	 * (an older vmlinux.h). Hence, we use the smaller size to avoid
10446 	 * memory corruption.
10447 	 */
10448 	events__sz = min(events__sz, sizeof(*events));
10449 	memcpy(events, &e_sys, events__sz);
10450 }
10451 
10452 #ifdef CONFIG_CGROUP_SCHED
10453 /**
10454  * scx_bpf_task_cgroup - Return the sched cgroup of a task
10455  * @p: task of interest
10456  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10457  *
10458  * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with
10459  * from the scheduler's POV. SCX operations should use this function to
10460  * determine @p's current cgroup as, unlike following @p->cgroups,
10461  * @p->sched_task_group is stable for the duration of the SCX op. See
10462  * SCX_CALL_OP_TASK() for details.
10463  */
10464 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p,
10465 					       const struct bpf_prog_aux *aux)
10466 {
10467 	struct task_group *tg = p->sched_task_group;
10468 	struct cgroup *cgrp = &cgrp_dfl_root.cgrp;
10469 	struct scx_sched *sch;
10470 
10471 	guard(rcu)();
10472 
10473 	sch = scx_prog_sched(aux);
10474 	if (unlikely(!sch))
10475 		goto out;
10476 
10477 	if (!scx_kf_arg_task_ok(sch, p))
10478 		goto out;
10479 
10480 	cgrp = tg_cgrp(tg);
10481 
10482 out:
10483 	cgroup_get(cgrp);
10484 	return cgrp;
10485 }
10486 #endif	/* CONFIG_CGROUP_SCHED */
10487 
10488 __bpf_kfunc_end_defs();
10489 
10490 BTF_KFUNCS_START(scx_kfunc_ids_any)
10491 BTF_ID_FLAGS(func, scx_bpf_task_set_slice, KF_IMPLICIT_ARGS | KF_RCU);
10492 BTF_ID_FLAGS(func, scx_bpf_task_set_dsq_vtime, KF_IMPLICIT_ARGS | KF_RCU);
10493 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
10494 BTF_ID_FLAGS(func, scx_bpf_kick_cid, KF_IMPLICIT_ARGS)
10495 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued, KF_IMPLICIT_ARGS)
10496 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS)
10497 BTF_ID_FLAGS(func, scx_bpf_dsq_peek, KF_IMPLICIT_ARGS | KF_RCU_PROTECTED | KF_RET_NULL)
10498 BTF_ID_FLAGS(func, scx_bpf_dsq_reenq, KF_IMPLICIT_ARGS)
10499 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local___v2, KF_IMPLICIT_ARGS)
10500 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_IMPLICIT_ARGS | KF_ITER_NEW | KF_RCU_PROTECTED)
10501 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
10502 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
10503 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_IMPLICIT_ARGS)
10504 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_IMPLICIT_ARGS)
10505 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_IMPLICIT_ARGS)
10506 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS)
10507 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS)
10508 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
10509 BTF_ID_FLAGS(func, scx_bpf_cidperf_cap, KF_IMPLICIT_ARGS)
10510 BTF_ID_FLAGS(func, scx_bpf_cidperf_cur, KF_IMPLICIT_ARGS)
10511 BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS)
10512 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
10513 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
10514 BTF_ID_FLAGS(func, scx_bpf_nr_cids)
10515 BTF_ID_FLAGS(func, scx_bpf_nr_online_cids)
10516 BTF_ID_FLAGS(func, scx_bpf_this_cid)
10517 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
10518 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
10519 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
10520 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
10521 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
10522 BTF_ID_FLAGS(func, scx_bpf_task_cid, KF_RCU)
10523 BTF_ID_FLAGS(func, scx_bpf_cpu_rq, KF_IMPLICIT_ARGS)
10524 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL)
10525 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
10526 BTF_ID_FLAGS(func, scx_bpf_cid_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
10527 BTF_ID_FLAGS(func, scx_bpf_tid_to_task, KF_RET_NULL | KF_RCU_PROTECTED)
10528 BTF_ID_FLAGS(func, scx_bpf_now)
10529 BTF_ID_FLAGS(func, scx_bpf_events)
10530 #ifdef CONFIG_CGROUP_SCHED
10531 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_IMPLICIT_ARGS | KF_RCU | KF_ACQUIRE)
10532 #endif
10533 BTF_KFUNCS_END(scx_kfunc_ids_any)
10534 
10535 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
10536 	.owner			= THIS_MODULE,
10537 	.set			= &scx_kfunc_ids_any,
10538 	.filter			= scx_kfunc_context_filter,
10539 };
10540 
10541 /*
10542  * cpu-form kfuncs that are forbidden from cid-form schedulers
10543  * (bpf_sched_ext_ops_cid). Programs targeting the cid struct_ops type must
10544  * use the cid-form alternative (cid/cmask kfuncs).
10545  *
10546  * Membership overlaps with scx_kfunc_ids_{any,idle,select_cpu}; the filter
10547  * tests this set independently and rejects matches before the per-op
10548  * allow-list check runs.
10549  *
10550  * pahole/resolve_btfids scans every BTF_ID_FLAGS() at build time and
10551  * intersects flags across duplicate entries, so each entry must carry the
10552  * same flags as the kfunc's primary declaration; otherwise the flags get
10553  * dropped globally.
10554  */
10555 BTF_KFUNCS_START(scx_kfunc_ids_cpu_only)
10556 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
10557 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
10558 BTF_ID_FLAGS(func, scx_bpf_cpu_rq, KF_IMPLICIT_ARGS)
10559 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
10560 BTF_ID_FLAGS(func, scx_bpf_cpu_node, KF_IMPLICIT_ARGS)
10561 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS)
10562 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS)
10563 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
10564 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
10565 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
10566 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
10567 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU)
10568 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU)
10569 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU)
10570 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10571 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10572 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10573 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10574 BTF_ID_FLAGS(func, scx_bpf_put_idle_cpumask, KF_RELEASE)
10575 BTF_ID_FLAGS(func, scx_bpf_test_and_clear_cpu_idle, KF_IMPLICIT_ARGS)
10576 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu, KF_IMPLICIT_ARGS | KF_RCU)
10577 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu_node, KF_IMPLICIT_ARGS | KF_RCU)
10578 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu, KF_IMPLICIT_ARGS | KF_RCU)
10579 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu_node, KF_IMPLICIT_ARGS | KF_RCU)
10580 BTF_KFUNCS_END(scx_kfunc_ids_cpu_only)
10581 
10582 /*
10583  * Per-op kfunc allow flags. Each bit corresponds to a context-sensitive kfunc
10584  * group; an op may permit zero or more groups, with the union expressed in
10585  * scx_kf_allow_flags[]. The verifier-time filter (scx_kfunc_context_filter())
10586  * consults this table to decide whether a context-sensitive kfunc is callable
10587  * from a given SCX op.
10588  */
10589 enum scx_kf_allow_flags {
10590 	SCX_KF_ALLOW_UNLOCKED		= 1 << 0,
10591 	SCX_KF_ALLOW_INIT		= 1 << 1,
10592 	SCX_KF_ALLOW_CPU_RELEASE	= 1 << 2,
10593 	SCX_KF_ALLOW_DISPATCH		= 1 << 3,
10594 	SCX_KF_ALLOW_ENQUEUE		= 1 << 4,
10595 	SCX_KF_ALLOW_SELECT_CPU		= 1 << 5,
10596 };
10597 
10598 /*
10599  * Map each SCX op to the union of kfunc groups it permits, indexed by
10600  * SCX_OP_IDX(op). Ops not listed only permit kfuncs that are not
10601  * context-sensitive.
10602  */
10603 static const u32 scx_kf_allow_flags[] = {
10604 	[SCX_OP_IDX(select_cpu)]	= SCX_KF_ALLOW_SELECT_CPU | SCX_KF_ALLOW_ENQUEUE,
10605 	[SCX_OP_IDX(enqueue)]		= SCX_KF_ALLOW_SELECT_CPU | SCX_KF_ALLOW_ENQUEUE,
10606 	[SCX_OP_IDX(dispatch)]		= SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH,
10607 	[SCX_OP_IDX(cpu_release)]	= SCX_KF_ALLOW_CPU_RELEASE,
10608 	[SCX_OP_IDX(init_task)]		= SCX_KF_ALLOW_UNLOCKED,
10609 	[SCX_OP_IDX(dump)]		= SCX_KF_ALLOW_UNLOCKED,
10610 #ifdef CONFIG_EXT_GROUP_SCHED
10611 	[SCX_OP_IDX(cgroup_init)]	= SCX_KF_ALLOW_UNLOCKED,
10612 	[SCX_OP_IDX(cgroup_exit)]	= SCX_KF_ALLOW_UNLOCKED,
10613 	[SCX_OP_IDX(cgroup_prep_move)]	= SCX_KF_ALLOW_UNLOCKED,
10614 	[SCX_OP_IDX(cgroup_cancel_move)] = SCX_KF_ALLOW_UNLOCKED,
10615 	[SCX_OP_IDX(cgroup_set_weight)]	= SCX_KF_ALLOW_UNLOCKED,
10616 	[SCX_OP_IDX(cgroup_set_bandwidth)] = SCX_KF_ALLOW_UNLOCKED,
10617 	[SCX_OP_IDX(cgroup_set_idle)]	= SCX_KF_ALLOW_UNLOCKED,
10618 #endif	/* CONFIG_EXT_GROUP_SCHED */
10619 	[SCX_OP_IDX(sub_attach)]	= SCX_KF_ALLOW_UNLOCKED,
10620 	[SCX_OP_IDX(sub_detach)]	= SCX_KF_ALLOW_UNLOCKED,
10621 	[SCX_OP_IDX(cpu_online)]	= SCX_KF_ALLOW_UNLOCKED,
10622 	[SCX_OP_IDX(cpu_offline)]	= SCX_KF_ALLOW_UNLOCKED,
10623 	[SCX_OP_IDX(init)]		= SCX_KF_ALLOW_UNLOCKED | SCX_KF_ALLOW_INIT,
10624 	[SCX_OP_IDX(exit)]		= SCX_KF_ALLOW_UNLOCKED,
10625 };
10626 
10627 /*
10628  * Verifier-time filter for SCX kfuncs. Registered via the .filter field on
10629  * each per-group btf_kfunc_id_set. The BPF core invokes this for every kfunc
10630  * call in the registered hook (BPF_PROG_TYPE_STRUCT_OPS or
10631  * BPF_PROG_TYPE_SYSCALL), regardless of which set originally introduced the
10632  * kfunc - so the filter must short-circuit on kfuncs it doesn't govern by
10633  * falling through to "allow" when none of the SCX sets contain the kfunc.
10634  */
10635 int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id)
10636 {
10637 	bool in_unlocked = btf_id_set8_contains(&scx_kfunc_ids_unlocked, kfunc_id);
10638 	bool in_init = btf_id_set8_contains(&scx_kfunc_ids_init, kfunc_id);
10639 	bool in_select_cpu = btf_id_set8_contains(&scx_kfunc_ids_select_cpu, kfunc_id);
10640 	bool in_enqueue = btf_id_set8_contains(&scx_kfunc_ids_enqueue_dispatch, kfunc_id);
10641 	bool in_dispatch = btf_id_set8_contains(&scx_kfunc_ids_dispatch, kfunc_id);
10642 	bool in_cpu_release = btf_id_set8_contains(&scx_kfunc_ids_cpu_release, kfunc_id);
10643 	bool in_idle = btf_id_set8_contains(&scx_kfunc_ids_idle, kfunc_id);
10644 	bool in_any = btf_id_set8_contains(&scx_kfunc_ids_any, kfunc_id);
10645 	bool in_cpu_only = btf_id_set8_contains(&scx_kfunc_ids_cpu_only, kfunc_id);
10646 	u32 moff, flags;
10647 
10648 	/* Not an SCX kfunc - allow. */
10649 	if (!(in_unlocked || in_init || in_select_cpu || in_enqueue || in_dispatch ||
10650 	      in_cpu_release || in_idle || in_any))
10651 		return 0;
10652 
10653 	/* SYSCALL progs (e.g. BPF test_run()) may call unlocked and select_cpu kfuncs. */
10654 	if (prog->type == BPF_PROG_TYPE_SYSCALL)
10655 		return (in_unlocked || in_select_cpu || in_idle || in_any) ? 0 : -EACCES;
10656 
10657 	if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
10658 		return (in_any || in_idle) ? 0 : -EACCES;
10659 
10660 	/*
10661 	 * add_subprog_and_kfunc() collects all kfunc calls, including dead code
10662 	 * guarded by bpf_ksym_exists(), before check_attach_btf_id() sets
10663 	 * prog->aux->st_ops. Allow all kfuncs when st_ops is not yet set;
10664 	 * do_check_main() re-runs the filter with st_ops set and enforces the
10665 	 * actual restrictions.
10666 	 */
10667 	if (!prog->aux->st_ops)
10668 		return 0;
10669 
10670 	/*
10671 	 * Non-SCX struct_ops: SCX kfuncs are not permitted.
10672 	 *
10673 	 * Both bpf_sched_ext_ops (cpu-form) and bpf_sched_ext_ops_cid
10674 	 * (cid-form) are valid SCX struct_ops. Member offsets match between
10675 	 * the two (verified by BUILD_BUG_ON in scx_init()), so the shared
10676 	 * scx_kf_allow_flags[] table indexed by SCX_MOFF_IDX(moff) applies to
10677 	 * both.
10678 	 */
10679 	if (prog->aux->st_ops != &bpf_sched_ext_ops &&
10680 	    prog->aux->st_ops != &bpf_sched_ext_ops_cid)
10681 		return -EACCES;
10682 
10683 	/*
10684 	 * cid-form schedulers must use cid/cmask kfuncs. cid and cpu are both
10685 	 * small s32s and trivially confused, so cpu-only kfuncs are rejected at
10686 	 * load time. The reverse (cpu-form calling cid-form kfuncs) is
10687 	 * intentionally permissive to ease gradual cpumask -> cid migration.
10688 	 */
10689 	if (prog->aux->st_ops == &bpf_sched_ext_ops_cid && in_cpu_only)
10690 		return -EACCES;
10691 
10692 	/* SCX struct_ops: check the per-op allow list. */
10693 	if (in_any || in_idle)
10694 		return 0;
10695 
10696 	moff = prog->aux->attach_st_ops_member_off;
10697 	flags = scx_kf_allow_flags[SCX_MOFF_IDX(moff)];
10698 
10699 	if ((flags & SCX_KF_ALLOW_UNLOCKED) && in_unlocked)
10700 		return 0;
10701 	if ((flags & SCX_KF_ALLOW_INIT) && in_init)
10702 		return 0;
10703 	if ((flags & SCX_KF_ALLOW_CPU_RELEASE) && in_cpu_release)
10704 		return 0;
10705 	if ((flags & SCX_KF_ALLOW_DISPATCH) && in_dispatch)
10706 		return 0;
10707 	if ((flags & SCX_KF_ALLOW_ENQUEUE) && in_enqueue)
10708 		return 0;
10709 	if ((flags & SCX_KF_ALLOW_SELECT_CPU) && in_select_cpu)
10710 		return 0;
10711 
10712 	return -EACCES;
10713 }
10714 
10715 static int __init scx_init(void)
10716 {
10717 	int ret;
10718 
10719 	/*
10720 	 * sched_ext_ops_cid mirrors sched_ext_ops up to and including @priv.
10721 	 * Both bpf_scx_init_member() and bpf_scx_check_member() use offsets
10722 	 * from struct sched_ext_ops; sched_ext_ops_cid relies on those offsets
10723 	 * matching for the shared fields. Catch any drift at boot.
10724 	 */
10725 #define CID_OFFSET_MATCH(cpu_field, cid_field)					\
10726 	BUILD_BUG_ON(offsetof(struct sched_ext_ops, cpu_field) !=		\
10727 		     offsetof(struct sched_ext_ops_cid, cid_field))
10728 	/* data fields used by bpf_scx_init_member() */
10729 	CID_OFFSET_MATCH(dispatch_max_batch, dispatch_max_batch);
10730 	CID_OFFSET_MATCH(flags, flags);
10731 	CID_OFFSET_MATCH(name, name);
10732 	CID_OFFSET_MATCH(timeout_ms, timeout_ms);
10733 	CID_OFFSET_MATCH(exit_dump_len, exit_dump_len);
10734 	CID_OFFSET_MATCH(hotplug_seq, hotplug_seq);
10735 	CID_OFFSET_MATCH(sub_cgroup_id, sub_cgroup_id);
10736 	/* shared callbacks: the union view requires byte-for-byte offset match */
10737 	CID_OFFSET_MATCH(enqueue, enqueue);
10738 	CID_OFFSET_MATCH(dequeue, dequeue);
10739 	CID_OFFSET_MATCH(dispatch, dispatch);
10740 	CID_OFFSET_MATCH(tick, tick);
10741 	CID_OFFSET_MATCH(runnable, runnable);
10742 	CID_OFFSET_MATCH(running, running);
10743 	CID_OFFSET_MATCH(stopping, stopping);
10744 	CID_OFFSET_MATCH(quiescent, quiescent);
10745 	CID_OFFSET_MATCH(yield, yield);
10746 	CID_OFFSET_MATCH(core_sched_before, core_sched_before);
10747 	CID_OFFSET_MATCH(set_weight, set_weight);
10748 	CID_OFFSET_MATCH(update_idle, update_idle);
10749 	CID_OFFSET_MATCH(init_task, init_task);
10750 	CID_OFFSET_MATCH(exit_task, exit_task);
10751 	CID_OFFSET_MATCH(enable, enable);
10752 	CID_OFFSET_MATCH(disable, disable);
10753 	CID_OFFSET_MATCH(dump, dump);
10754 	CID_OFFSET_MATCH(dump_task, dump_task);
10755 	CID_OFFSET_MATCH(sub_attach, sub_attach);
10756 	CID_OFFSET_MATCH(sub_detach, sub_detach);
10757 	CID_OFFSET_MATCH(init, init);
10758 	CID_OFFSET_MATCH(exit, exit);
10759 #ifdef CONFIG_EXT_GROUP_SCHED
10760 	CID_OFFSET_MATCH(cgroup_init, cgroup_init);
10761 	CID_OFFSET_MATCH(cgroup_exit, cgroup_exit);
10762 	CID_OFFSET_MATCH(cgroup_prep_move, cgroup_prep_move);
10763 	CID_OFFSET_MATCH(cgroup_move, cgroup_move);
10764 	CID_OFFSET_MATCH(cgroup_cancel_move, cgroup_cancel_move);
10765 	CID_OFFSET_MATCH(cgroup_set_weight, cgroup_set_weight);
10766 	CID_OFFSET_MATCH(cgroup_set_bandwidth, cgroup_set_bandwidth);
10767 	CID_OFFSET_MATCH(cgroup_set_idle, cgroup_set_idle);
10768 #endif
10769 	/* renamed callbacks must occupy the same slot as their cpu-form sibling */
10770 	CID_OFFSET_MATCH(select_cpu, select_cid);
10771 	CID_OFFSET_MATCH(set_cpumask, set_cmask);
10772 	CID_OFFSET_MATCH(cpu_online, cid_online);
10773 	CID_OFFSET_MATCH(cpu_offline, cid_offline);
10774 	CID_OFFSET_MATCH(dump_cpu, dump_cid);
10775 	/* @priv tail must align since both share the same data block */
10776 	CID_OFFSET_MATCH(priv, priv);
10777 	/*
10778 	 * cid-form must end exactly at @priv - validate_ops() skips
10779 	 * cpu_acquire/cpu_release for cid-form because reading those fields
10780 	 * past the BPF allocation would be UB.
10781 	 */
10782 	BUILD_BUG_ON(offsetof(struct sched_ext_ops_cid, __end) !=
10783 		     offsetofend(struct sched_ext_ops, priv));
10784 #undef CID_OFFSET_MATCH
10785 
10786 	/*
10787 	 * kfunc registration can't be done from init_sched_ext_class() as
10788 	 * register_btf_kfunc_id_set() needs most of the system to be up.
10789 	 *
10790 	 * Some kfuncs are context-sensitive and can only be called from
10791 	 * specific SCX ops. They are grouped into per-context BTF sets, each
10792 	 * registered with scx_kfunc_context_filter as its .filter callback. The
10793 	 * BPF core dedups identical filter pointers per hook
10794 	 * (btf_populate_kfunc_set()), so the filter is invoked exactly once per
10795 	 * kfunc lookup; it consults scx_kf_allow_flags[] to enforce per-op
10796 	 * restrictions at verify time.
10797 	 */
10798 	if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
10799 					     &scx_kfunc_set_enqueue_dispatch)) ||
10800 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
10801 					     &scx_kfunc_set_dispatch)) ||
10802 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
10803 					     &scx_kfunc_set_cpu_release)) ||
10804 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
10805 					     &scx_kfunc_set_unlocked)) ||
10806 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
10807 					     &scx_kfunc_set_unlocked)) ||
10808 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
10809 					     &scx_kfunc_set_any)) ||
10810 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
10811 					     &scx_kfunc_set_any)) ||
10812 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
10813 					     &scx_kfunc_set_any))) {
10814 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
10815 		return ret;
10816 	}
10817 
10818 	ret = scx_idle_init();
10819 	if (ret) {
10820 		pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret);
10821 		return ret;
10822 	}
10823 
10824 	ret = scx_cid_kfunc_init();
10825 	if (ret) {
10826 		pr_err("sched_ext: Failed to register cid kfuncs (%d)\n", ret);
10827 		return ret;
10828 	}
10829 
10830 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops);
10831 	if (ret) {
10832 		pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret);
10833 		return ret;
10834 	}
10835 
10836 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops_cid, sched_ext_ops_cid);
10837 	if (ret) {
10838 		pr_err("sched_ext: Failed to register cid struct_ops (%d)\n", ret);
10839 		return ret;
10840 	}
10841 
10842 	ret = register_pm_notifier(&scx_pm_notifier);
10843 	if (ret) {
10844 		pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret);
10845 		return ret;
10846 	}
10847 
10848 	scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj);
10849 	if (!scx_kset) {
10850 		pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n");
10851 		return -ENOMEM;
10852 	}
10853 
10854 	ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group);
10855 	if (ret < 0) {
10856 		pr_err("sched_ext: Failed to add global attributes\n");
10857 		return ret;
10858 	}
10859 
10860 	return 0;
10861 }
10862 __initcall(scx_init);
10863