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