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