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