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