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