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