xref: /linux/kernel/sched/ext/ext.c (revision 56bbc91219c0711f1580a8ba7cd60471b6e1684e)
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_init_task_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 	 * Re-balance the dl_server bandwidth reservations: detach ext_server
6480 	 * (no more sched_ext tasks) and reinstate fair_server if it was
6481 	 * previously detached because we were running in full mode.
6482 	 *
6483 	 * Unlike the enable path, this runs on a recovery path that cannot
6484 	 * fail, so we use dl_server_swap_bw() to atomically free ext_server's
6485 	 * bandwidth and reclaim it for fair_server under the same dl_b lock.
6486 	 *
6487 	 * The swap can still fail with -EBUSY if someone bumped ext_server's
6488 	 * runtime via debugfs between enable and disable; in that narrow case
6489 	 * both servers end up detached and we just WARN.
6490 	 */
6491 	for_each_possible_cpu(cpu) {
6492 		struct rq *rq = cpu_rq(cpu);
6493 
6494 		scoped_guard(rq_lock_irqsave, rq) {
6495 			update_rq_clock(rq);
6496 			if (was_switched_all) {
6497 				if (WARN_ON_ONCE(dl_server_swap_bw(&rq->ext_server,
6498 								   &rq->fair_server)))
6499 					pr_warn("failed to re-attach fair_server on CPU %d\n", cpu);
6500 			} else {
6501 				dl_server_detach_bw(&rq->ext_server);
6502 			}
6503 		}
6504 	}
6505 
6506 	/* no task is on scx, turn off all the switches and flush in-progress calls */
6507 	static_branch_disable(&__scx_enabled);
6508 	static_branch_disable(&__scx_is_cid_type);
6509 	if (sch->ops.flags & SCX_OPS_TID_TO_TASK)
6510 		static_branch_disable(&__scx_tid_to_task_enabled);
6511 	bitmap_zero(sch->has_op, SCX_OPI_END);
6512 	scx_idle_disable();
6513 	synchronize_rcu();
6514 	if (sch->ops.flags & SCX_OPS_TID_TO_TASK)
6515 		rhashtable_free_and_destroy(&scx_tid_hash, NULL, NULL);
6516 
6517 	scx_log_sched_disable(sch);
6518 
6519 	if (sch->ops.exit)
6520 		SCX_CALL_OP(sch, exit, NULL, sch->exit_info);
6521 
6522 	/*
6523 	 * @sch's non-ops programs such as timers and tracers can fire after
6524 	 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from
6525 	 * resolving to @sch and drain in-flight resolvers.
6526 	 */
6527 	WRITE_ONCE(sch->dead, true);
6528 	synchronize_rcu();
6529 
6530 	scx_unlink_sched(sch);
6531 
6532 	/*
6533 	 * scx_root clearing and cid table retirement must be inside
6534 	 * cpus_read_lock(). See handle_hotplug().
6535 	 */
6536 	cpus_read_lock();
6537 	RCU_INIT_POINTER(scx_root, NULL);
6538 	scx_cid_retire_tables();
6539 	cpus_read_unlock();
6540 
6541 	/*
6542 	 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs
6543 	 * could observe an object of the same name still in the hierarchy when
6544 	 * the next scheduler is loaded.
6545 	 */
6546 #ifdef CONFIG_EXT_SUB_SCHED
6547 	if (sch->sub_kset)
6548 		kobject_del(&sch->sub_kset->kobj);
6549 #endif
6550 	/* not added if enable failed before scx_sched_sysfs_add() */
6551 	if (sch->kobj.state_in_sysfs)
6552 		kobject_del(&sch->kobj);
6553 
6554 	free_kick_syncs();
6555 
6556 	mutex_unlock(&scx_enable_mutex);
6557 
6558 	WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
6559 done:
6560 	scx_bypass(sch, false);
6561 }
6562 
6563 /**
6564  * scx_propagate_exit_irq_workfn - Claim SCX_EXIT_PARENT on the exiting subtree
6565  * @irq_work: &scx_sched.propagate_exit_irq_work
6566  *
6567  * Queued by scx_claim_exit() after a non-PARENT claim. Claims SCX_EXIT_PARENT
6568  * on each descendant, giving every one its own disable work - most of disabling
6569  * is serialized but ops.exit() can take arbitrarily long and running them in
6570  * separate helper kthreads parallelizes it. No recursion as only non-PARENT
6571  * claims propagate.
6572  */
6573 static void scx_propagate_exit_irq_workfn(struct irq_work *irq_work)
6574 {
6575 	struct scx_sched *sch = container_of(irq_work, struct scx_sched,
6576 					     propagate_exit_irq_work);
6577 	struct scx_sched *pos;
6578 
6579 	scoped_guard (raw_spinlock_irqsave, &scx_sched_lock) {
6580 		scx_for_each_descendant_pre(pos, sch)
6581 			scx_disable(pos, SCX_EXIT_PARENT);
6582 	}
6583 }
6584 
6585 /*
6586  * Claim the exit on @sch. The caller must ensure that the helper kthread work
6587  * is kicked before the current task can be preempted. Once exit_kind is
6588  * claimed, scx_error() can no longer trigger, so if the current task gets
6589  * preempted and the BPF scheduler fails to schedule it back, the helper work
6590  * will never be kicked and the whole system can wedge.
6591  *
6592  * Lock-free and safe to call from any context including NMI.
6593  */
6594 static bool scx_claim_exit(struct scx_sched *sch, enum scx_exit_kind kind)
6595 {
6596 	int none = SCX_EXIT_NONE;
6597 
6598 	lockdep_assert_preemption_disabled();
6599 
6600 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
6601 		kind = SCX_EXIT_ERROR;
6602 
6603 	if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind))
6604 		return false;
6605 
6606 	if (kind == SCX_EXIT_PARENT) {
6607 		/* an ancestor is already sweeping the subtree */
6608 		WRITE_ONCE(sch->aborting, true);
6609 	} else {
6610 		struct scx_sched *pos;
6611 
6612 		/*
6613 		 * CPUs may be live-locked in the dispatch paths of @sch or its
6614 		 * descendants, which ->aborting breaks. Sweep the subtree
6615 		 * locklessly so that this works from NMI. smp_store_mb() orders
6616 		 * each node's ->aborting store before its children are walked -
6617 		 * either we see a racing scx_link_sched() on ->children or it
6618 		 * sees ->aborting.
6619 		 */
6620 		scoped_guard (rcu) {
6621 			scx_for_each_descendant_pre(pos, sch)
6622 				smp_store_mb(pos->aborting, true);
6623 		}
6624 
6625 		irq_work_queue(&sch->propagate_exit_irq_work);
6626 	}
6627 
6628 	/* fired after ->aborting is set so callbacks can't delay recovery */
6629 	trace_sched_ext_exit(sch, kind);
6630 
6631 	return true;
6632 }
6633 
6634 static void scx_disable_workfn(struct kthread_work *work)
6635 {
6636 	struct scx_sched *sch = container_of(work, struct scx_sched, disable_work);
6637 	struct scx_exit_info *ei = sch->exit_info;
6638 	int kind;
6639 
6640 	kind = atomic_read(&sch->exit_kind);
6641 	while (true) {
6642 		if (kind == SCX_EXIT_DONE)	/* already disabled? */
6643 			return;
6644 		WARN_ON_ONCE(kind == SCX_EXIT_NONE);
6645 		if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE))
6646 			break;
6647 	}
6648 	ei->kind = kind;
6649 	ei->reason = scx_exit_reason(ei->kind);
6650 
6651 	if (scx_parent(sch))
6652 		scx_sub_disable(sch);
6653 	else
6654 		scx_root_disable(sch);
6655 }
6656 
6657 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind)
6658 {
6659 	guard(preempt)();
6660 	if (scx_claim_exit(sch, kind))
6661 		irq_work_queue(&sch->disable_irq_work);
6662 }
6663 
6664 /**
6665  * scx_flush_disable_work - flush the disable work and wait for it to finish
6666  * @sch: the scheduler
6667  *
6668  * sch->disable_work might still not queued, causing kthread_flush_work()
6669  * as a noop. Syncing the irq_work first is required to guarantee the
6670  * kthread work has been queued before waiting for it.
6671  */
6672 void scx_flush_disable_work(struct scx_sched *sch)
6673 {
6674 	int kind;
6675 
6676 	do {
6677 		irq_work_sync(&sch->disable_irq_work);
6678 		kthread_flush_work(&sch->disable_work);
6679 		kind = atomic_read(&sch->exit_kind);
6680 	} while (kind != SCX_EXIT_NONE && kind != SCX_EXIT_DONE);
6681 }
6682 
6683 static void dump_newline(struct seq_buf *s)
6684 {
6685 	trace_sched_ext_dump("");
6686 
6687 	/* @s may be zero sized and seq_buf triggers WARN if so */
6688 	if (s->size)
6689 		seq_buf_putc(s, '\n');
6690 }
6691 
6692 __printf(2, 3) void scx_dump_line(struct seq_buf *s, const char *fmt, ...)
6693 {
6694 	va_list args;
6695 
6696 #ifdef CONFIG_TRACEPOINTS
6697 	if (trace_sched_ext_dump_enabled()) {
6698 		/* protected by scx_dump_lock */
6699 		static char line_buf[SCX_EXIT_MSG_LEN];
6700 
6701 		va_start(args, fmt);
6702 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
6703 		va_end(args);
6704 
6705 		trace_call__sched_ext_dump(line_buf);
6706 	}
6707 #endif
6708 	/* @s may be zero sized and seq_buf triggers WARN if so */
6709 	if (s->size) {
6710 		va_start(args, fmt);
6711 		seq_buf_vprintf(s, fmt, args);
6712 		va_end(args);
6713 
6714 		seq_buf_putc(s, '\n');
6715 	}
6716 }
6717 
6718 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
6719 			     const unsigned long *bt, unsigned int len)
6720 {
6721 	unsigned int i;
6722 
6723 	for (i = 0; i < len; i++)
6724 		scx_dump_line(s, "%s%pS", prefix, (void *)bt[i]);
6725 }
6726 
6727 static void ops_dump_init(struct seq_buf *s, const char *prefix)
6728 {
6729 	struct scx_dump_data *dd = &scx_dump_data;
6730 
6731 	lockdep_assert_irqs_disabled();
6732 
6733 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
6734 	dd->first = true;
6735 	dd->cursor = 0;
6736 	dd->s = s;
6737 	dd->prefix = prefix;
6738 }
6739 
6740 static void ops_dump_flush(void)
6741 {
6742 	struct scx_dump_data *dd = &scx_dump_data;
6743 	char *line = dd->buf.line;
6744 
6745 	if (!dd->cursor)
6746 		return;
6747 
6748 	/*
6749 	 * There's something to flush and this is the first line. Insert a blank
6750 	 * line to distinguish ops dump.
6751 	 */
6752 	if (dd->first) {
6753 		dump_newline(dd->s);
6754 		dd->first = false;
6755 	}
6756 
6757 	/*
6758 	 * There may be multiple lines in $line. Scan and emit each line
6759 	 * separately.
6760 	 */
6761 	while (true) {
6762 		char *end = line;
6763 		char c;
6764 
6765 		while (*end != '\n' && *end != '\0')
6766 			end++;
6767 
6768 		/*
6769 		 * If $line overflowed, it may not have newline at the end.
6770 		 * Always emit with a newline.
6771 		 */
6772 		c = *end;
6773 		*end = '\0';
6774 		scx_dump_line(dd->s, "%s%s", dd->prefix, line);
6775 		if (c == '\0')
6776 			break;
6777 
6778 		/* move to the next line */
6779 		end++;
6780 		if (*end == '\0')
6781 			break;
6782 		line = end;
6783 	}
6784 
6785 	dd->cursor = 0;
6786 }
6787 
6788 static void ops_dump_exit(void)
6789 {
6790 	ops_dump_flush();
6791 	scx_dump_data.cpu = -1;
6792 }
6793 
6794 static void scx_dump_task(struct scx_sched *sch, struct seq_buf *s, struct scx_dump_ctx *dctx,
6795 			  struct rq *rq, struct task_struct *p, char marker)
6796 {
6797 	static unsigned long bt[SCX_EXIT_BT_LEN];
6798 	struct scx_sched *task_sch = scx_task_sched(p);
6799 	const char *own_marker;
6800 	char sch_id_buf[32];
6801 	char dsq_id_buf[19] = "(n/a)";
6802 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
6803 	unsigned int bt_len = 0;
6804 
6805 	own_marker = task_sch == sch ? "*" : "";
6806 
6807 	if (task_sch->level == 0)
6808 		scnprintf(sch_id_buf, sizeof(sch_id_buf), "root");
6809 	else
6810 		scnprintf(sch_id_buf, sizeof(sch_id_buf), "sub%d-%llu",
6811 			  task_sch->level, task_sch->ops.sub_cgroup_id);
6812 
6813 	if (p->scx.dsq)
6814 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
6815 			  (unsigned long long)p->scx.dsq->id);
6816 
6817 	dump_newline(s);
6818 	scx_dump_line(s, " %c%c %s[%d] %s%s %+ldms",
6819 		      marker, task_state_to_char(p), p->comm, p->pid, own_marker, sch_id_buf,
6820 		      jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
6821 	scx_dump_line(s, "      scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu",
6822 		      scx_get_task_state(p) >> SCX_TASK_STATE_SHIFT,
6823 		      p->scx.flags & ~SCX_TASK_STATE_MASK, p->scx.dsq_flags,
6824 		      ops_state & SCX_OPSS_STATE_MASK, ops_state >> SCX_OPSS_QSEQ_SHIFT);
6825 	scx_dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
6826 		      p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
6827 	scx_dump_line(s, "      dsq_vtime=%llu slice=%llu weight=%u",
6828 		      p->scx.dsq_vtime, p->scx.slice, p->scx.weight);
6829 	scx_dump_line(s, "      cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr),
6830 		      p->migration_disabled);
6831 
6832 	if (SCX_HAS_OP(sch, dump_task)) {
6833 		ops_dump_init(s, "    ");
6834 		SCX_CALL_OP(sch, dump_task, rq, dctx, p);
6835 		ops_dump_exit();
6836 	}
6837 
6838 #ifdef CONFIG_STACKTRACE
6839 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
6840 #endif
6841 	if (bt_len) {
6842 		dump_newline(s);
6843 		dump_stack_trace(s, "    ", bt, bt_len);
6844 	}
6845 }
6846 
6847 static void scx_dump_cpu(struct scx_sched *sch, struct seq_buf *s,
6848 			 struct scx_dump_ctx *dctx, int cpu,
6849 			 bool dump_all_tasks)
6850 {
6851 	struct rq *rq = cpu_rq(cpu);
6852 	struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
6853 	struct rq_flags rf;
6854 	struct task_struct *p;
6855 	struct seq_buf ns;
6856 	size_t avail, used;
6857 	char *buf;
6858 	bool idle;
6859 
6860 	rq_lock_irqsave(rq, &rf);
6861 
6862 	idle = list_empty(&rq->scx.runnable_list) &&
6863 		rq->curr->sched_class == &idle_sched_class;
6864 
6865 	if (idle && !SCX_HAS_OP(sch, dump_cpu))
6866 		goto next;
6867 
6868 	/*
6869 	 * We don't yet know whether ops.dump_cpu() will produce output
6870 	 * and we may want to skip the default CPU dump if it doesn't.
6871 	 * Use a nested seq_buf to generate the standard dump so that we
6872 	 * can decide whether to commit later.
6873 	 */
6874 	avail = seq_buf_get_buf(s, &buf);
6875 	seq_buf_init(&ns, buf, avail);
6876 
6877 	dump_newline(&ns);
6878 	scx_dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu ksync=%lu",
6879 		      cpu, rq->scx.nr_running, rq->scx.flags, rq->scx.cpu_released,
6880 		      rq->scx.ops_qseq, rq->scx.kick_sync);
6881 	scx_rescue_dump(&ns, rq);
6882 	scx_dump_line(&ns, "          curr=%s[%d] class=%ps",
6883 		      rq->curr->comm, rq->curr->pid, rq->curr->sched_class);
6884 	if (!cpumask_empty(pcpu->cpus_to_kick))
6885 		scx_dump_line(&ns, "  cpus_to_kick   : %*pb",
6886 			      cpumask_pr_args(pcpu->cpus_to_kick));
6887 	if (!cpumask_empty(pcpu->cpus_to_kick_if_idle))
6888 		scx_dump_line(&ns, "  idle_to_kick   : %*pb",
6889 			      cpumask_pr_args(pcpu->cpus_to_kick_if_idle));
6890 	if (!cpumask_empty(pcpu->cpus_to_preempt))
6891 		scx_dump_line(&ns, "  cpus_to_preempt: %*pb",
6892 			      cpumask_pr_args(pcpu->cpus_to_preempt));
6893 	if (!cpumask_empty(pcpu->cpus_to_wait))
6894 		scx_dump_line(&ns, "  cpus_to_wait   : %*pb",
6895 			      cpumask_pr_args(pcpu->cpus_to_wait));
6896 	if (!cpumask_empty(rq->scx.cpus_to_sync))
6897 		scx_dump_line(&ns, "  cpus_to_sync   : %*pb",
6898 			      cpumask_pr_args(rq->scx.cpus_to_sync));
6899 
6900 	used = seq_buf_used(&ns);
6901 	if (SCX_HAS_OP(sch, dump_cpu)) {
6902 		ops_dump_init(&ns, "  ");
6903 		SCX_CALL_OP(sch, dump_cpu, rq, dctx, scx_cpu_arg(cpu), idle);
6904 		ops_dump_exit();
6905 	}
6906 
6907 	/*
6908 	 * If idle && nothing generated by ops.dump_cpu(), there's
6909 	 * nothing interesting. Skip.
6910 	 */
6911 	if (idle && used == seq_buf_used(&ns))
6912 		goto next;
6913 
6914 	/*
6915 	 * $s may already have overflowed when $ns was created. If so,
6916 	 * calling commit on it will trigger BUG.
6917 	 */
6918 	if (avail) {
6919 		seq_buf_commit(s, seq_buf_used(&ns));
6920 		if (seq_buf_has_overflowed(&ns))
6921 			seq_buf_set_overflow(s);
6922 	}
6923 
6924 	if (rq->curr->sched_class == &ext_sched_class &&
6925 	    (dump_all_tasks || scx_task_on_sched(sch, rq->curr)))
6926 		scx_dump_task(sch, s, dctx, rq, rq->curr, '*');
6927 
6928 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
6929 		if (dump_all_tasks || scx_task_on_sched(sch, p))
6930 			scx_dump_task(sch, s, dctx, rq, p, ' ');
6931 next:
6932 	rq_unlock_irqrestore(rq, &rf);
6933 }
6934 
6935 /*
6936  * Dump scheduler state. If @dump_all_tasks is true, dump all tasks regardless
6937  * of which scheduler they belong to. If false, only dump tasks owned by @sch.
6938  * For SysRq-D dumps, @dump_all_tasks=false since all schedulers are dumped
6939  * separately. For error dumps, @dump_all_tasks=true since only the failing
6940  * scheduler is dumped.
6941  */
6942 static void scx_dump_state(struct scx_sched *sch, struct scx_exit_info *ei,
6943 			   size_t dump_len, bool dump_all_tasks)
6944 {
6945 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
6946 	struct scx_dump_ctx dctx = {
6947 		.kind = ei->kind,
6948 		.exit_code = ei->exit_code,
6949 		.reason = ei->reason,
6950 		.at_ns = ktime_get_ns(),
6951 		.at_jiffies = jiffies,
6952 	};
6953 	struct seq_buf s;
6954 	struct scx_event_stats events;
6955 	int cpu;
6956 
6957 	guard(raw_spinlock_irqsave)(&scx_dump_lock);
6958 
6959 	if (sch->dump_disabled)
6960 		return;
6961 
6962 	seq_buf_init(&s, ei->dump, dump_len);
6963 
6964 #ifdef CONFIG_EXT_SUB_SCHED
6965 	if (sch->level == 0)
6966 		scx_dump_line(&s, "%s: root", sch->ops.name);
6967 	else
6968 		scx_dump_line(&s, "%s: sub%d-%llu %s",
6969 			      sch->ops.name, sch->level, sch->ops.sub_cgroup_id,
6970 			      sch->cgrp_path);
6971 #endif
6972 	if (ei->kind == SCX_EXIT_NONE) {
6973 		scx_dump_line(&s, "Debug dump triggered by %s", ei->reason);
6974 	} else {
6975 		if (ei->exit_cpu >= 0)
6976 			scx_dump_line(&s, "%s[%d] triggered exit kind %d on CPU %d:",
6977 				      current->comm, current->pid, ei->kind,
6978 				      ei->exit_cpu);
6979 		else
6980 			scx_dump_line(&s, "%s[%d] triggered exit kind %d:",
6981 				      current->comm, current->pid, ei->kind);
6982 		scx_dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
6983 		dump_newline(&s);
6984 		scx_dump_line(&s, "Backtrace:");
6985 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
6986 	}
6987 
6988 	if (SCX_HAS_OP(sch, dump)) {
6989 		ops_dump_init(&s, "");
6990 		SCX_CALL_OP(sch, dump, NULL, &dctx);
6991 		ops_dump_exit();
6992 	}
6993 
6994 	dump_newline(&s);
6995 	scx_dump_line(&s, "CPU states");
6996 	scx_dump_line(&s, "----------");
6997 
6998 	/*
6999 	 * Dump stalled CPUs first so they aren't lost to dump truncation, then
7000 	 * walk the rest in order. Fall back to exit_cpu if no stall mask set.
7001 	 */
7002 	if (!cpumask_empty(sch->stall_cpus)) {
7003 		for_each_cpu(cpu, sch->stall_cpus)
7004 			scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks);
7005 		for_each_possible_cpu(cpu) {
7006 			if (!cpumask_test_cpu(cpu, sch->stall_cpus))
7007 				scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks);
7008 		}
7009 	} else {
7010 		if (ei->exit_cpu >= 0)
7011 			scx_dump_cpu(sch, &s, &dctx, ei->exit_cpu, dump_all_tasks);
7012 		for_each_possible_cpu(cpu) {
7013 			if (cpu != ei->exit_cpu)
7014 				scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks);
7015 		}
7016 	}
7017 
7018 	dump_newline(&s);
7019 	scx_dump_line(&s, "Event counters");
7020 	scx_dump_line(&s, "--------------");
7021 
7022 	scx_read_events(sch, &events);
7023 #define SCX_EVENT(name)	scx_dump_event(s, &events, name)
7024 	SCX_EVENTS_LIST(SCX_EVENT);
7025 #undef SCX_EVENT
7026 
7027 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
7028 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
7029 		       trunc_marker, sizeof(trunc_marker));
7030 }
7031 
7032 static void scx_disable_irq_workfn(struct irq_work *irq_work)
7033 {
7034 	struct scx_sched *sch = container_of(irq_work, struct scx_sched, disable_irq_work);
7035 	struct scx_exit_info *ei = sch->exit_info;
7036 
7037 	if (ei->kind >= SCX_EXIT_ERROR)
7038 		scx_dump_state(sch, ei, sch->ops.exit_dump_len, true);
7039 
7040 	kthread_queue_work(sch->helper, &sch->disable_work);
7041 }
7042 
7043 /* finish exit_info and kick the disable work, ei->msg must already be set */
7044 static void scx_finish_exit(struct scx_sched *sch, enum scx_exit_kind kind,
7045 			    s64 exit_code, s32 exit_cpu)
7046 {
7047 	struct scx_exit_info *ei = sch->exit_info;
7048 
7049 	ei->exit_code = exit_code;
7050 #ifdef CONFIG_STACKTRACE
7051 	/*
7052 	 * stack_trace_save()'s NMI-safety is arch-dependent and undocumented.
7053 	 * Skip the backtrace when exiting from NMI.
7054 	 */
7055 	if (kind >= SCX_EXIT_ERROR && !in_nmi())
7056 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
7057 #endif
7058 	/*
7059 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
7060 	 * in scx_disable_workfn().
7061 	 */
7062 	ei->kind = kind;
7063 	ei->reason = scx_exit_reason(ei->kind);
7064 	ei->exit_cpu = exit_cpu;
7065 
7066 	irq_work_queue(&sch->disable_irq_work);
7067 }
7068 
7069 bool scx_vexit(struct scx_sched *sch,
7070 	       enum scx_exit_kind kind, s64 exit_code, s32 exit_cpu,
7071 	       const char *fmt, va_list args)
7072 {
7073 	struct scx_exit_info *ei = sch->exit_info;
7074 
7075 	guard(preempt)();
7076 
7077 	if (!scx_claim_exit(sch, kind))
7078 		return false;
7079 
7080 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
7081 
7082 	scx_finish_exit(sch, kind, exit_code, exit_cpu);
7083 	return true;
7084 }
7085 
7086 static int alloc_kick_syncs(void)
7087 {
7088 	int cpu;
7089 
7090 	/*
7091 	 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size
7092 	 * can exceed percpu allocator limits on large machines.
7093 	 */
7094 	for_each_possible_cpu(cpu) {
7095 		struct scx_kick_syncs __rcu **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
7096 		struct scx_kick_syncs *new_ksyncs;
7097 
7098 		WARN_ON_ONCE(rcu_access_pointer(*ksyncs));
7099 
7100 		new_ksyncs = kvzalloc_node(struct_size(new_ksyncs, syncs, nr_cpu_ids),
7101 					   GFP_KERNEL, cpu_to_node(cpu));
7102 		if (!new_ksyncs) {
7103 			free_kick_syncs();
7104 			return -ENOMEM;
7105 		}
7106 
7107 		rcu_assign_pointer(*ksyncs, new_ksyncs);
7108 	}
7109 
7110 	return 0;
7111 }
7112 
7113 static void free_pnode(struct scx_sched_pnode *pnode)
7114 {
7115 	if (!pnode)
7116 		return;
7117 	exit_dsq(&pnode->global_dsq);
7118 	kfree(pnode);
7119 }
7120 
7121 static struct scx_sched_pnode *alloc_pnode(struct scx_sched *sch, int node)
7122 {
7123 	struct scx_sched_pnode *pnode;
7124 
7125 	pnode = kzalloc_node(sizeof(*pnode), GFP_KERNEL, node);
7126 	if (!pnode)
7127 		return NULL;
7128 
7129 	if (scx_init_dsq(&pnode->global_dsq, SCX_DSQ_GLOBAL, sch)) {
7130 		kfree(pnode);
7131 		return NULL;
7132 	}
7133 
7134 	return pnode;
7135 }
7136 
7137 /*
7138  * Allocate and initialize a new scx_sched. @cgrp's reference is always
7139  * consumed whether the function succeeds or fails.
7140  */
7141 struct scx_sched *scx_alloc_and_add_sched(struct scx_enable_cmd *cmd,
7142 					  struct cgroup *cgrp,
7143 					  struct scx_sched *parent)
7144 {
7145 	struct sched_ext_ops *ops = cmd->ops;
7146 	struct scx_sched *sch;
7147 	s32 level = parent ? parent->level + 1 : 0;
7148 	s32 node, cpu, ret, bypass_fail_cpu = nr_cpu_ids;
7149 
7150 	sch = kzalloc_flex(*sch, ancestors, level + 1);
7151 	if (!sch) {
7152 		ret = -ENOMEM;
7153 		goto err_put_cgrp;
7154 	}
7155 
7156 	sch->exit_info = alloc_exit_info(ops->exit_dump_len);
7157 	if (!sch->exit_info) {
7158 		ret = -ENOMEM;
7159 		goto err_free_sch;
7160 	}
7161 
7162 	ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params);
7163 	if (ret < 0)
7164 		goto err_free_ei;
7165 
7166 	sch->pnode = kzalloc_objs(sch->pnode[0], nr_node_ids);
7167 	if (!sch->pnode) {
7168 		ret = -ENOMEM;
7169 		goto err_free_hash;
7170 	}
7171 
7172 	for_each_node_state(node, N_POSSIBLE) {
7173 		sch->pnode[node] = alloc_pnode(sch, node);
7174 		if (!sch->pnode[node]) {
7175 			ret = -ENOMEM;
7176 			goto err_free_pnode;
7177 		}
7178 	}
7179 
7180 	sch->dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
7181 	sch->pcpu = __alloc_percpu(struct_size_t(struct scx_sched_pcpu,
7182 						 dsp_ctx.buf, sch->dsp_max_batch),
7183 				   __alignof__(struct scx_sched_pcpu));
7184 	if (!sch->pcpu) {
7185 		ret = -ENOMEM;
7186 		goto err_free_pnode;
7187 	}
7188 
7189 	for_each_possible_cpu(cpu) {
7190 		ret = scx_init_dsq(scx_bypass_dsq(sch, cpu), SCX_DSQ_BYPASS, sch);
7191 		if (ret) {
7192 			bypass_fail_cpu = cpu;
7193 			goto err_free_pcpu;
7194 		}
7195 	}
7196 
7197 	for_each_possible_cpu(cpu) {
7198 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
7199 
7200 		node = cpu_to_node(cpu);
7201 		pcpu->sch = sch;
7202 		INIT_LIST_HEAD(&pcpu->deferred_reenq_local.node);
7203 #ifdef CONFIG_EXT_SUB_SCHED
7204 		init_llist_node(&pcpu->ecaps_to_sync_node);
7205 #endif
7206 		INIT_LIST_HEAD(&pcpu->to_kick_node);
7207 		if (!zalloc_cpumask_var_node(&pcpu->cpus_to_kick, GFP_KERNEL, node) ||
7208 		    !zalloc_cpumask_var_node(&pcpu->cpus_to_kick_if_idle, GFP_KERNEL, node) ||
7209 		    !zalloc_cpumask_var_node(&pcpu->cpus_to_preempt, GFP_KERNEL, node) ||
7210 		    !zalloc_cpumask_var_node(&pcpu->cpus_to_wait, GFP_KERNEL, node)) {
7211 			ret = -ENOMEM;
7212 			goto err_free_pcpu;
7213 		}
7214 	}
7215 
7216 	sch->helper = kthread_run_worker(0, "sched_ext_helper");
7217 	if (IS_ERR(sch->helper)) {
7218 		ret = PTR_ERR(sch->helper);
7219 		goto err_free_pcpu;
7220 	}
7221 
7222 	sched_set_fifo(sch->helper->task);
7223 
7224 	if (parent)
7225 		memcpy(sch->ancestors, parent->ancestors,
7226 		       level * sizeof(parent->ancestors[0]));
7227 	sch->ancestors[level] = sch;
7228 	sch->level = level;
7229 	sch->id = atomic64_inc_return(&scx_sched_id_cursor);
7230 
7231 	if (ops->timeout_ms)
7232 		sch->watchdog_timeout = msecs_to_jiffies(ops->timeout_ms);
7233 	else
7234 		sch->watchdog_timeout = SCX_WATCHDOG_MAX_TIMEOUT;
7235 
7236 	sch->slice_dfl = SCX_SLICE_DFL;
7237 	atomic_set(&sch->exit_kind, SCX_EXIT_NONE);
7238 	sch->disable_irq_work = IRQ_WORK_INIT_HARD(scx_disable_irq_workfn);
7239 	sch->propagate_exit_irq_work = IRQ_WORK_INIT_HARD(scx_propagate_exit_irq_workfn);
7240 	kthread_init_work(&sch->disable_work, scx_disable_workfn);
7241 	timer_setup(&sch->bypass_lb_timer, scx_bypass_lb_timerfn, 0);
7242 
7243 	if (!alloc_cpumask_var(&sch->bypass_lb_donee_cpumask, GFP_KERNEL)) {
7244 		ret = -ENOMEM;
7245 		goto err_stop_helper;
7246 	}
7247 	if (!alloc_cpumask_var(&sch->bypass_lb_resched_cpumask, GFP_KERNEL)) {
7248 		ret = -ENOMEM;
7249 		goto err_free_lb_cpumask;
7250 	}
7251 	if (!zalloc_cpumask_var(&sch->stall_cpus, GFP_KERNEL)) {
7252 		ret = -ENOMEM;
7253 		goto err_free_lb_resched_cpumask;
7254 	}
7255 	/*
7256 	 * Copy ops through the right union view. For cid-form the source is
7257 	 * struct sched_ext_ops_cid which lacks the trailing cpu_acquire/
7258 	 * cpu_release; those stay zero from kzalloc.
7259 	 */
7260 	if (cmd->is_cid_type) {
7261 		sch->ops_cid = *cmd->ops_cid;
7262 		sch->is_cid_type = true;
7263 	} else {
7264 		sch->ops = *cmd->ops;
7265 	}
7266 
7267 #ifdef CONFIG_EXT_SUB_SCHED
7268 	char *buf = kzalloc(PATH_MAX, GFP_KERNEL);
7269 	if (!buf) {
7270 		ret = -ENOMEM;
7271 		goto err_free_lb_resched;
7272 	}
7273 	cgroup_path(cgrp, buf, PATH_MAX);
7274 	sch->cgrp_path = kstrdup(buf, GFP_KERNEL);
7275 	kfree(buf);
7276 	if (!sch->cgrp_path) {
7277 		ret = -ENOMEM;
7278 		goto err_free_lb_resched;
7279 	}
7280 
7281 	sch->cgrp = cgrp;
7282 	INIT_LIST_HEAD(&sch->children);
7283 	INIT_LIST_HEAD(&sch->sibling);
7284 #endif	/* CONFIG_EXT_SUB_SCHED */
7285 
7286 	/*
7287 	 * Publishing makes @sch visible to scx_prog_sched() readers. Failure
7288 	 * paths after this point must free @sch through kobject_put() whose
7289 	 * release path defers the actual freeing by an RCU grace period.
7290 	 */
7291 	rcu_assign_pointer(ops->priv, sch);
7292 
7293 	sch->kobj.kset = scx_kset;
7294 	INIT_LIST_HEAD(&sch->all);
7295 
7296 #ifdef CONFIG_EXT_SUB_SCHED
7297 	if (parent) {
7298 		/*
7299 		 * Pin @parent for @sch's lifetime. The kobject hierarchy pins
7300 		 * it only via @parent->sub_kset, which is dropped during
7301 		 * disable. Released in scx_sched_free_rcu_work().
7302 		 */
7303 		kobject_get(&parent->kobj);
7304 	}
7305 #endif	/* CONFIG_EXT_SUB_SCHED */
7306 
7307 	/*
7308 	 * Init the kobj but don't add to sysfs yet. The enable path calls
7309 	 * scx_sched_sysfs_add() once @sch's sysfs-visible state is initialized.
7310 	 */
7311 	kobject_init(&sch->kobj, &scx_ktype);
7312 
7313 	/*
7314 	 * Consume the arena_map ref bpf_scx_reg_cid() took. Defer to here so
7315 	 * earlier failure paths leave cmd->arena_map set and bpf_scx_reg_cid
7316 	 * drops the ref. After this point, sch owns the ref and any cleanup
7317 	 * runs through scx_sched_free_rcu_work() which puts it.
7318 	 */
7319 	sch->arena_map = cmd->arena_map;
7320 	/* BPF arena is only available on MMU && 64BIT */
7321 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
7322 	if (sch->arena_map)
7323 		sch->arena_kern_base = bpf_arena_map_kern_vm_start(sch->arena_map);
7324 #endif
7325 	cmd->arena_map = NULL;
7326 	return sch;
7327 
7328 #ifdef CONFIG_EXT_SUB_SCHED
7329 err_free_lb_resched:
7330 	free_cpumask_var(sch->stall_cpus);
7331 #endif
7332 err_free_lb_resched_cpumask:
7333 	free_cpumask_var(sch->bypass_lb_resched_cpumask);
7334 err_free_lb_cpumask:
7335 	free_cpumask_var(sch->bypass_lb_donee_cpumask);
7336 err_stop_helper:
7337 	kthread_destroy_worker(sch->helper);
7338 err_free_pcpu:
7339 	for_each_possible_cpu(cpu) {
7340 		struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu);
7341 
7342 		free_cpumask_var(pcpu->cpus_to_kick);
7343 		free_cpumask_var(pcpu->cpus_to_kick_if_idle);
7344 		free_cpumask_var(pcpu->cpus_to_preempt);
7345 		free_cpumask_var(pcpu->cpus_to_wait);
7346 	}
7347 	for_each_possible_cpu(cpu) {
7348 		if (cpu == bypass_fail_cpu)
7349 			break;
7350 		exit_dsq(scx_bypass_dsq(sch, cpu));
7351 	}
7352 	free_percpu(sch->pcpu);
7353 err_free_pnode:
7354 	for_each_node_state(node, N_POSSIBLE)
7355 		free_pnode(sch->pnode[node]);
7356 	kfree(sch->pnode);
7357 err_free_hash:
7358 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
7359 err_free_ei:
7360 	free_exit_info(sch->exit_info);
7361 err_free_sch:
7362 	kfree(sch);
7363 err_put_cgrp:
7364 #ifdef CONFIG_EXT_SUB_SCHED
7365 	cgroup_put(cgrp);
7366 #endif
7367 	return ERR_PTR(ret);
7368 }
7369 
7370 /*
7371  * Add @sch's kobject to sysfs, and create its sub_kset if the scheduler
7372  * implements ops.sub_attach. Called by the enable workfns once @sch's
7373  * sysfs-visible state is initialized.
7374  */
7375 int scx_sched_sysfs_add(struct scx_sched *sch)
7376 {
7377 #ifdef CONFIG_EXT_SUB_SCHED
7378 	struct scx_sched *parent = scx_parent(sch);
7379 	int ret;
7380 
7381 	if (parent)
7382 		ret = kobject_add(&sch->kobj, &parent->sub_kset->kobj,
7383 				  "sub-%llu", cgroup_id(sch_cgroup(sch)));
7384 	else
7385 		ret = kobject_add(&sch->kobj, NULL, "root");
7386 	if (ret < 0)
7387 		return ret;
7388 
7389 	if (sch->ops.sub_attach) {
7390 		sch->sub_kset = kset_create_and_add("sub", NULL, &sch->kobj);
7391 		if (!sch->sub_kset)
7392 			return -ENOMEM;
7393 	}
7394 	return 0;
7395 #else
7396 	return kobject_add(&sch->kobj, NULL, "root");
7397 #endif
7398 }
7399 
7400 static int check_hotplug_seq(struct scx_sched *sch,
7401 			      const struct sched_ext_ops *ops)
7402 {
7403 	unsigned long long global_hotplug_seq;
7404 
7405 	/*
7406 	 * If a hotplug event has occurred between when a scheduler was
7407 	 * initialized, and when we were able to attach, exit and notify user
7408 	 * space about it.
7409 	 */
7410 	if (ops->hotplug_seq) {
7411 		global_hotplug_seq = atomic_long_read(&scx_hotplug_seq);
7412 		if (ops->hotplug_seq != global_hotplug_seq) {
7413 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
7414 				 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
7415 				 "expected hotplug seq %llu did not match actual %llu",
7416 				 ops->hotplug_seq, global_hotplug_seq);
7417 			return -EBUSY;
7418 		}
7419 	}
7420 
7421 	return 0;
7422 }
7423 
7424 int scx_validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
7425 {
7426 	/*
7427 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
7428 	 * ops.enqueue() callback isn't implemented.
7429 	 */
7430 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
7431 		scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
7432 		return -EINVAL;
7433 	}
7434 
7435 	/*
7436 	 * SCX_OPS_TID_TO_TASK is enabled by the root scheduler. A sub-sched
7437 	 * may set it to declare a dependency; reject if the root hasn't
7438 	 * enabled it.
7439 	 */
7440 	if ((ops->flags & SCX_OPS_TID_TO_TASK) && scx_parent(sch) &&
7441 	    !(sch->ancestors[0]->ops.flags & SCX_OPS_TID_TO_TASK)) {
7442 		scx_error(sch, "SCX_OPS_TID_TO_TASK requires root scheduler to enable it");
7443 		return -EINVAL;
7444 	}
7445 
7446 	/*
7447 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle
7448 	 * selection policy to be enabled.
7449 	 */
7450 	if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) &&
7451 	    (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) {
7452 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled");
7453 		return -EINVAL;
7454 	}
7455 
7456 	/*
7457 	 * cid-form's struct is shorter and doesn't include the cpu_acquire /
7458 	 * cpu_release tail; reading those fields off a cid-form @ops would
7459 	 * run past the BPF allocation. Skip for cid-form.
7460 	 */
7461 	if (!sch->is_cid_type && (ops->cpu_acquire || ops->cpu_release))
7462 		pr_warn_ratelimited("ops->cpu_acquire/release() are deprecated, use sched_switch TP instead\n");
7463 
7464 	/*
7465 	 * Sub-scheduler support is tied to the cid-form struct_ops. A sub-sched
7466 	 * attaches through a cid-form-only interface (sub_attach/sub_detach),
7467 	 * and a root that accepts sub-scheds must expose cid-form state to
7468 	 * them. Reject cpu-form schedulers on either side.
7469 	 */
7470 	if (!sch->is_cid_type) {
7471 		if (scx_parent(sch)) {
7472 			scx_error(sch, "sub-sched requires cid-form struct_ops");
7473 			return -EINVAL;
7474 		}
7475 		if (ops->sub_attach || ops->sub_detach) {
7476 			scx_error(sch, "sub_attach/sub_detach requires cid-form struct_ops");
7477 			return -EINVAL;
7478 		}
7479 	}
7480 
7481 	return 0;
7482 }
7483 
7484 static void scx_root_enable_workfn(struct kthread_work *work)
7485 {
7486 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
7487 	struct sched_ext_ops *ops = cmd->ops;
7488 	struct cgroup *cgrp = root_cgroup();
7489 	struct scx_sched *sch;
7490 	struct scx_task_iter sti;
7491 	struct task_struct *p;
7492 	int i, cpu, ret;
7493 
7494 	mutex_lock(&scx_enable_mutex);
7495 
7496 	if (scx_enable_state() != SCX_DISABLED) {
7497 		ret = -EBUSY;
7498 		goto err_unlock;
7499 	}
7500 
7501 	/*
7502 	 * @ops->priv binds @ops to its scx_sched instance. It is set here by
7503 	 * scx_alloc_and_add_sched() and cleared at the tail of bpf_scx_unreg(),
7504 	 * which runs after scx_root_disable() has dropped scx_enable_mutex. If
7505 	 * it's still non-NULL here, a previous attachment on @ops has not
7506 	 * finished tearing down; proceeding would let the in-flight unreg's
7507 	 * RCU_INIT_POINTER(NULL) clobber the @ops->priv we are about to assign.
7508 	 */
7509 	if (rcu_access_pointer(ops->priv)) {
7510 		ret = -EBUSY;
7511 		goto err_unlock;
7512 	}
7513 
7514 	ret = alloc_kick_syncs();
7515 	if (ret)
7516 		goto err_unlock;
7517 
7518 	if (ops->flags & SCX_OPS_TID_TO_TASK) {
7519 		ret = rhashtable_init(&scx_tid_hash, &scx_tid_hash_params);
7520 		if (ret)
7521 			goto err_free_ksyncs;
7522 	}
7523 
7524 #ifdef CONFIG_EXT_SUB_SCHED
7525 	cgroup_get(cgrp);
7526 #endif
7527 	sch = scx_alloc_and_add_sched(cmd, cgrp, NULL);
7528 	if (IS_ERR(sch)) {
7529 		ret = PTR_ERR(sch);
7530 		goto err_free_tid_hash;
7531 	}
7532 
7533 	if (sch->is_cid_type)
7534 		static_branch_enable(&__scx_is_cid_type);
7535 
7536 	/*
7537 	 * Transition to ENABLING and clear exit info to arm the disable path.
7538 	 * Failure triggers full disabling from here on.
7539 	 */
7540 	WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED);
7541 	WARN_ON_ONCE(scx_root);
7542 
7543 	atomic_long_set(&scx_nr_rejected, 0);
7544 
7545 	for_each_possible_cpu(cpu) {
7546 		struct rq *rq = cpu_rq(cpu);
7547 
7548 		rq->scx.local_dsq.sched = sch;
7549 		rq->scx.cpuperf_target = SCX_CPUPERF_ONE;
7550 	}
7551 
7552 	scx_discard_stale_ecaps_syncs();
7553 	scx_rescue_set_knobs(sch);
7554 
7555 	/*
7556 	 * Keep CPUs stable during enable so that the BPF scheduler can track
7557 	 * online CPUs by watching ->on/offline_cpu() after ->init().
7558 	 */
7559 	cpus_read_lock();
7560 
7561 	/*
7562 	 * Build the cid mapping into a private under-construction set. It
7563 	 * becomes visible to readers only through scx_cid_publish_tables() once
7564 	 * ops.init_cids() has finalized the layout.
7565 	 */
7566 	ret = scx_cid_init(sch);
7567 	if (ret) {
7568 		cpus_read_unlock();
7569 		goto err_disable;
7570 	}
7571 
7572 	/*
7573 	 * Make the scheduler instance visible. Must be inside cpus_read_lock().
7574 	 * See handle_hotplug().
7575 	 */
7576 	rcu_assign_pointer(scx_root, sch);
7577 
7578 	ret = scx_link_sched(sch);
7579 	if (ret) {
7580 		cpus_read_unlock();
7581 		goto err_disable;
7582 	}
7583 
7584 	scx_idle_enable(ops);
7585 
7586 	/*
7587 	 * A cid-form scheduler finalizes its cid layout in ops.init_cids(),
7588 	 * which may call scx_bpf_cid_override(). Run it before the caps and
7589 	 * shard state are built so the final layout is in effect.
7590 	 */
7591 	if (sch->is_cid_type && sch->ops_cid.init_cids) {
7592 		ret = SCX_CALL_OP_RET(sch, init_cids, NULL);
7593 		if (ret) {
7594 			ret = scx_ops_sanitize_err(sch, "init_cids", ret);
7595 			cpus_read_unlock();
7596 			scx_error(sch, "ops.init_cids() failed (%d)", ret);
7597 			goto err_disable;
7598 		}
7599 	}
7600 
7601 	/* the cid layout is final, expose it to readers */
7602 	scx_cid_publish_tables();
7603 
7604 	ret = scx_arena_pool_init(sch);
7605 	if (ret) {
7606 		cpus_read_unlock();
7607 		goto err_disable;
7608 	}
7609 
7610 	ret = scx_set_cmask_scratch_alloc(sch);
7611 	if (ret) {
7612 		cpus_read_unlock();
7613 		goto err_disable;
7614 	}
7615 
7616 	ret = scx_alloc_pshards(sch);
7617 	if (ret) {
7618 		cpus_read_unlock();
7619 		goto err_disable;
7620 	}
7621 
7622 	scx_init_root_caps(sch);
7623 
7624 	/* the cid caps and shards are live now, so ops.init() can query them */
7625 	if (sch->ops.init) {
7626 		ret = SCX_CALL_OP_RET(sch, init, NULL);
7627 		if (ret) {
7628 			ret = scx_ops_sanitize_err(sch, "init", ret);
7629 			cpus_read_unlock();
7630 			scx_error(sch, "ops.init() failed (%d)", ret);
7631 			goto err_disable;
7632 		}
7633 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
7634 	}
7635 
7636 	ret = scx_sched_sysfs_add(sch);
7637 	if (ret) {
7638 		cpus_read_unlock();
7639 		goto err_disable;
7640 	}
7641 
7642 	for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++)
7643 		if (((void (**)(void))ops)[i])
7644 			set_bit(i, sch->has_op);
7645 
7646 	ret = check_hotplug_seq(sch, ops);
7647 	if (ret) {
7648 		cpus_read_unlock();
7649 		goto err_disable;
7650 	}
7651 	scx_idle_update_selcpu_topology(ops);
7652 
7653 	cpus_read_unlock();
7654 
7655 	ret = scx_validate_ops(sch, ops);
7656 	if (ret)
7657 		goto err_disable;
7658 
7659 	/*
7660 	 * Attach the ext_server bandwidth reservation before anything is
7661 	 * committed so that we can fail the enable if the root domain cannot
7662 	 * accommodate it. The matching fair_server detach is deferred to the
7663 	 * tail of this function, after the switch is fully committed and can no
7664 	 * longer fail.
7665 	 *
7666 	 * On failure, err_disable funnels into scx_root_disable() which
7667 	 * detaches ext_server, so partially-attached state is cleaned up
7668 	 * automatically.
7669 	 */
7670 	for_each_possible_cpu(cpu) {
7671 		struct rq *rq = cpu_rq(cpu);
7672 
7673 		scoped_guard(rq_lock_irqsave, rq) {
7674 			update_rq_clock(rq);
7675 			ret = dl_server_attach_bw(&rq->ext_server);
7676 		}
7677 		if (ret) {
7678 			pr_warn("sched_ext: failed to attach ext_server on CPU %d (%d)\n",
7679 				cpu, ret);
7680 			goto err_disable;
7681 		}
7682 	}
7683 
7684 	/*
7685 	 * Once __scx_enabled is set, %current can be switched to SCX anytime.
7686 	 * This can lead to stalls as some BPF schedulers (e.g. userspace
7687 	 * scheduling) may not function correctly before all tasks are switched.
7688 	 * Init in bypass mode to guarantee forward progress.
7689 	 */
7690 	scx_bypass(sch, true);
7691 
7692 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
7693 		if (((void (**)(void))ops)[i])
7694 			set_bit(i, sch->has_op);
7695 
7696 	if (sch->ops.cpu_acquire || sch->ops.cpu_release)
7697 		sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT;
7698 
7699 	/*
7700 	 * Lock out forks, cgroup on/offlining and moves before opening the
7701 	 * floodgate so that they don't wander into the operations prematurely.
7702 	 */
7703 	percpu_down_write(&scx_fork_rwsem);
7704 
7705 	WARN_ON_ONCE(scx_init_task_enabled);
7706 	scx_init_task_enabled = true;
7707 
7708 	/* flip under fork_rwsem; the iter below covers existing tasks */
7709 	if (ops->flags & SCX_OPS_TID_TO_TASK)
7710 		static_branch_enable(&__scx_tid_to_task_enabled);
7711 
7712 	/*
7713 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
7714 	 * preventing new tasks from being added. No need to exclude tasks
7715 	 * leaving as sched_ext_free() can handle both prepped and enabled
7716 	 * tasks. Prep all tasks first and then enable them with preemption
7717 	 * disabled.
7718 	 *
7719 	 * All cgroups should be initialized before scx_init_task() so that the
7720 	 * BPF scheduler can reliably track each task's cgroup membership from
7721 	 * scx_init_task(). Lock out cgroup on/offlining and task migrations
7722 	 * while tasks are being initialized so that scx_cgroup_can_attach()
7723 	 * never sees uninitialized tasks.
7724 	 */
7725 	scx_cgroup_lock();
7726 	set_cgroup_sched(sch_cgroup(sch), sch);
7727 	ret = scx_cgroup_init(sch);
7728 	if (ret)
7729 		goto err_disable_unlock_all;
7730 
7731 	WARN_ON_ONCE(scx_cgroup_enabled);
7732 	scx_cgroup_enabled = true;
7733 
7734 	scx_task_iter_start(&sti, NULL);
7735 	while ((p = scx_task_iter_next_locked(&sti))) {
7736 		/*
7737 		 * @p is in scx_tasks under scx_tasks_lock, and SCX_TASK_DEAD
7738 		 * tasks are filtered by scx_task_iter_next_locked().
7739 		 * sched_ext_dead() removes @p from scx_tasks under the same
7740 		 * lock before put_task_struct_rcu_user() runs, so @p->usage
7741 		 * is guaranteed > 0 here.
7742 		 */
7743 		get_task_struct(p);
7744 
7745 		/*
7746 		 * Set %INIT_BEGIN under the iter's rq lock so that a concurrent
7747 		 * sched_ext_dead() does not call ops.exit_task() on @p while
7748 		 * ops.init_task() is running. If sched_ext_dead() runs before
7749 		 * this store, it has already removed @p from scx_tasks and the
7750 		 * iter won't visit @p; if it runs after, it observes
7751 		 * %INIT_BEGIN and transitions to %DEAD without calling ops,
7752 		 * leaving the post-init recheck below to unwind.
7753 		 */
7754 		scx_set_task_state(p, SCX_TASK_INIT_BEGIN);
7755 		scx_task_iter_unlock(&sti);
7756 
7757 		ret = __scx_init_task(sch, p, NULL, false);
7758 
7759 		scx_task_iter_relock(&sti, p);
7760 
7761 		if (unlikely(ret)) {
7762 			if (scx_get_task_state(p) != SCX_TASK_DEAD)
7763 				scx_set_task_state(p, SCX_TASK_NONE);
7764 			scx_task_iter_stop(&sti);
7765 			scx_error(sch, "ops.init_task() failed (%d) for %s[%d]",
7766 				  ret, p->comm, p->pid);
7767 			put_task_struct(p);
7768 			goto err_disable_unlock_all;
7769 		}
7770 
7771 		if (scx_get_task_state(p) == SCX_TASK_DEAD) {
7772 			/*
7773 			 * sched_ext_dead() observed %INIT_BEGIN and set %DEAD.
7774 			 * ops.exit_task() is owed to the sched __scx_init_task()
7775 			 * ran against; call it now.
7776 			 */
7777 			scx_sub_init_cancel_task(sch, p);
7778 		} else {
7779 			scx_set_task_state(p, SCX_TASK_INIT);
7780 			scx_set_task_sched(p, sch);
7781 			scx_set_task_state(p, SCX_TASK_READY);
7782 		}
7783 
7784 		/*
7785 		 * Insert into the tid hash. scx_tasks_lock is held by the iter;
7786 		 * list_empty() guards against sched_ext_dead() having taken @p
7787 		 * off the list while init ran unlocked.
7788 		 */
7789 		if (scx_tid_to_task_enabled() && !list_empty(&p->scx.tasks_node))
7790 			scx_tid_hash_insert(p);
7791 
7792 		put_task_struct(p);
7793 	}
7794 	scx_task_iter_stop(&sti);
7795 	scx_cgroup_unlock();
7796 	percpu_up_write(&scx_fork_rwsem);
7797 
7798 	/*
7799 	 * All tasks are READY. It's safe to turn on scx_enabled() and switch
7800 	 * all eligible tasks.
7801 	 */
7802 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
7803 	static_branch_enable(&__scx_enabled);
7804 
7805 	/*
7806 	 * We're fully committed and can't fail. The task READY -> ENABLED
7807 	 * transitions here are synchronized against sched_ext_free() through
7808 	 * scx_tasks_lock.
7809 	 */
7810 	percpu_down_write(&scx_fork_rwsem);
7811 	scx_task_iter_start(&sti, NULL);
7812 	while ((p = scx_task_iter_next_locked(&sti))) {
7813 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
7814 		const struct sched_class *old_class = p->sched_class;
7815 		const struct sched_class *new_class = scx_setscheduler_class(p);
7816 
7817 		if (scx_get_task_state(p) != SCX_TASK_READY)
7818 			continue;
7819 
7820 		if (old_class != new_class)
7821 			queue_flags |= DEQUEUE_CLASS;
7822 
7823 		scoped_guard (sched_change, p, queue_flags) {
7824 			scx_set_task_slice(p, READ_ONCE(sch->slice_dfl));
7825 			p->sched_class = new_class;
7826 		}
7827 	}
7828 	scx_task_iter_stop(&sti);
7829 	percpu_up_write(&scx_fork_rwsem);
7830 
7831 	scx_bypass(sch, false);
7832 
7833 	if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) {
7834 		WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE);
7835 		ret = -EBUSY;
7836 		goto err_disable;
7837 	}
7838 
7839 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
7840 		static_branch_enable(&__scx_switched_all);
7841 
7842 	/*
7843 	 * Detach the fair_server bandwidth reservation now that the switch
7844 	 * is fully committed. In full mode (!SCX_OPS_SWITCH_PARTIAL) no
7845 	 * task will ever run in the fair class, so give that bandwidth
7846 	 * back to the RT class. The matching ext_server attach already
7847 	 * happened earlier; this only releases bandwidth and cannot fail.
7848 	 *
7849 	 * In partial mode keep fair_server attached.
7850 	 */
7851 	if (scx_switched_all()) {
7852 		for_each_possible_cpu(cpu) {
7853 			struct rq *rq = cpu_rq(cpu);
7854 
7855 			guard(rq_lock_irqsave)(rq);
7856 			update_rq_clock(rq);
7857 			dl_server_detach_bw(&rq->fair_server);
7858 		}
7859 	}
7860 
7861 	pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n",
7862 		sch->ops.name, scx_switched_all() ? "" : " (partial)");
7863 	kobject_uevent(&sch->kobj, KOBJ_ADD);
7864 	mutex_unlock(&scx_enable_mutex);
7865 
7866 	atomic_long_inc(&scx_enable_seq);
7867 
7868 	cmd->ret = 0;
7869 	return;
7870 
7871 err_free_tid_hash:
7872 	if (ops->flags & SCX_OPS_TID_TO_TASK)
7873 		rhashtable_free_and_destroy(&scx_tid_hash, NULL, NULL);
7874 err_free_ksyncs:
7875 	free_kick_syncs();
7876 err_unlock:
7877 	mutex_unlock(&scx_enable_mutex);
7878 	cmd->ret = ret;
7879 	return;
7880 
7881 err_disable_unlock_all:
7882 	scx_cgroup_unlock();
7883 	percpu_up_write(&scx_fork_rwsem);
7884 	/* we'll soon enter disable path, keep bypass on */
7885 err_disable:
7886 	mutex_unlock(&scx_enable_mutex);
7887 	/*
7888 	 * Returning an error code here would not pass all the error information
7889 	 * to userspace. Record errno using scx_error() for cases scx_error()
7890 	 * wasn't already invoked and exit indicating success so that the error
7891 	 * is notified through ops.exit() with all the details.
7892 	 *
7893 	 * Flush scx_disable_work to ensure that error is reported before init
7894 	 * completion. sch's base reference will be put by bpf_scx_unreg().
7895 	 */
7896 	scx_error(sch, "scx_root_enable() failed (%d)", ret);
7897 	scx_flush_disable_work(sch);
7898 	cmd->ret = 0;
7899 }
7900 
7901 static s32 scx_enable(struct scx_enable_cmd *cmd, struct bpf_link *link)
7902 {
7903 	static struct kthread_worker *helper;
7904 	static DEFINE_MUTEX(helper_mutex);
7905 
7906 	if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT)) {
7907 		pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n");
7908 		return -EINVAL;
7909 	}
7910 
7911 	if (!READ_ONCE(helper)) {
7912 		mutex_lock(&helper_mutex);
7913 		if (!helper) {
7914 			struct kthread_worker *w =
7915 				kthread_run_worker(0, "scx_enable_helper");
7916 			if (IS_ERR_OR_NULL(w)) {
7917 				mutex_unlock(&helper_mutex);
7918 				return -ENOMEM;
7919 			}
7920 			sched_set_fifo(w->task);
7921 			WRITE_ONCE(helper, w);
7922 		}
7923 		mutex_unlock(&helper_mutex);
7924 	}
7925 
7926 #ifdef CONFIG_EXT_SUB_SCHED
7927 	if (cmd->ops->sub_cgroup_id > 1)
7928 		kthread_init_work(&cmd->work, scx_sub_enable_workfn);
7929 	else
7930 #endif	/* CONFIG_EXT_SUB_SCHED */
7931 		kthread_init_work(&cmd->work, scx_root_enable_workfn);
7932 
7933 	kthread_queue_work(READ_ONCE(helper), &cmd->work);
7934 	kthread_flush_work(&cmd->work);
7935 	return cmd->ret;
7936 }
7937 
7938 
7939 /********************************************************************************
7940  * bpf_struct_ops plumbing.
7941  */
7942 #include <linux/bpf_verifier.h>
7943 #include <linux/bpf.h>
7944 #include <linux/btf.h>
7945 
7946 static const struct btf_type *task_struct_type;
7947 
7948 static bool bpf_scx_is_valid_access(int off, int size,
7949 				    enum bpf_access_type type,
7950 				    const struct bpf_prog *prog,
7951 				    struct bpf_insn_access_aux *info)
7952 {
7953 	if (type != BPF_READ)
7954 		return false;
7955 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
7956 		return false;
7957 	if (off % size != 0)
7958 		return false;
7959 
7960 	return btf_ctx_access(off, size, type, prog, info);
7961 }
7962 
7963 /* common to both forms: only scx.disallow is writable */
7964 static int bpf_scx_btf_struct_access_common(const struct bpf_reg_state *reg,
7965 					    int off, int size)
7966 {
7967 	const struct btf_type *t;
7968 
7969 	t = btf_type_by_id(reg->btf, reg->btf_id);
7970 	if (t == task_struct_type &&
7971 	    off >= offsetof(struct task_struct, scx.disallow) &&
7972 	    off + size <= offsetofend(struct task_struct, scx.disallow))
7973 		return SCALAR_VALUE;
7974 
7975 	return -EACCES;
7976 }
7977 
7978 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
7979 				     const struct bpf_reg_state *reg, int off,
7980 				     int size)
7981 {
7982 	const struct btf_type *t;
7983 
7984 	t = btf_type_by_id(reg->btf, reg->btf_id);
7985 	if (t == task_struct_type) {
7986 		if ((off >= offsetof(struct task_struct, scx.slice) &&
7987 		     off + size <= offsetofend(struct task_struct, scx.slice)) ||
7988 		    (off >= offsetof(struct task_struct, scx.dsq_vtime) &&
7989 		     off + size <= offsetofend(struct task_struct, scx.dsq_vtime)))
7990 			return SCALAR_VALUE;
7991 	}
7992 
7993 	return bpf_scx_btf_struct_access_common(reg, off, size);
7994 }
7995 
7996 /* cid-form rejects direct slice and dsq_vtime writes in favor of the kfuncs */
7997 static int bpf_scx_cid_btf_struct_access(struct bpf_verifier_log *log,
7998 					 const struct bpf_reg_state *reg, int off,
7999 					 int size)
8000 {
8001 	return bpf_scx_btf_struct_access_common(reg, off, size);
8002 }
8003 
8004 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
8005 	.get_func_proto = bpf_base_func_proto,
8006 	.is_valid_access = bpf_scx_is_valid_access,
8007 	.btf_struct_access = bpf_scx_btf_struct_access,
8008 };
8009 
8010 static const struct bpf_verifier_ops bpf_scx_cid_verifier_ops = {
8011 	.get_func_proto = bpf_base_func_proto,
8012 	.is_valid_access = bpf_scx_is_valid_access,
8013 	.btf_struct_access = bpf_scx_cid_btf_struct_access,
8014 };
8015 
8016 static int bpf_scx_init_member(const struct btf_type *t,
8017 			       const struct btf_member *member,
8018 			       void *kdata, const void *udata)
8019 {
8020 	const struct sched_ext_ops *uops = udata;
8021 	struct sched_ext_ops *ops = kdata;
8022 	u32 moff = __btf_member_bit_offset(t, member) / 8;
8023 	int ret;
8024 
8025 	switch (moff) {
8026 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
8027 		if (*(u32 *)(udata + moff) > INT_MAX)
8028 			return -E2BIG;
8029 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
8030 		return 1;
8031 	case offsetof(struct sched_ext_ops, flags):
8032 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
8033 			return -EINVAL;
8034 		ops->flags = *(u64 *)(udata + moff);
8035 		return 1;
8036 	case offsetof(struct sched_ext_ops, name):
8037 		ret = bpf_obj_name_cpy(ops->name, uops->name,
8038 				       sizeof(ops->name));
8039 		if (ret < 0)
8040 			return ret;
8041 		if (ret == 0)
8042 			return -EINVAL;
8043 		return 1;
8044 	case offsetof(struct sched_ext_ops, timeout_ms):
8045 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
8046 		    SCX_WATCHDOG_MAX_TIMEOUT)
8047 			return -E2BIG;
8048 		ops->timeout_ms = *(u32 *)(udata + moff);
8049 		return 1;
8050 	case offsetof(struct sched_ext_ops, exit_dump_len):
8051 		ops->exit_dump_len =
8052 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
8053 		return 1;
8054 	case offsetof(struct sched_ext_ops, hotplug_seq):
8055 		ops->hotplug_seq = *(u64 *)(udata + moff);
8056 		return 1;
8057 	case offsetof(struct sched_ext_ops, cid_shard_size):
8058 		ops->cid_shard_size = *(u32 *)(udata + moff);
8059 		return 1;
8060 	case offsetof(struct sched_ext_ops, rescue_bandwidth_ppt): {
8061 		u32 bw_ppt = *(u32 *)(udata + moff);
8062 
8063 		if (bw_ppt > SCX_RESCUE_MAX_BW_PPT && bw_ppt != SCX_RESCUE_DISABLE)
8064 			return -E2BIG;
8065 		ops->rescue_bandwidth_ppt = bw_ppt;
8066 		return 1;
8067 	}
8068 	case offsetof(struct sched_ext_ops, rescue_quantum_us): {
8069 		u32 quantum_us = *(u32 *)(udata + moff);
8070 
8071 		if (quantum_us > SCX_RESCUE_MAX_QUANTUM_US)
8072 			return -E2BIG;
8073 		if (quantum_us && quantum_us < SCX_RESCUE_MIN_QUANTUM_US)
8074 			return -EINVAL;
8075 		ops->rescue_quantum_us = quantum_us;
8076 		return 1;
8077 	}
8078 #ifdef CONFIG_EXT_SUB_SCHED
8079 	case offsetof(struct sched_ext_ops, sub_cgroup_id):
8080 		ops->sub_cgroup_id = *(u64 *)(udata + moff);
8081 		return 1;
8082 #endif	/* CONFIG_EXT_SUB_SCHED */
8083 	}
8084 
8085 	return 0;
8086 }
8087 
8088 static int bpf_scx_check_member(const struct btf_type *t,
8089 				const struct btf_member *member,
8090 				const struct bpf_prog *prog)
8091 {
8092 	u32 moff = __btf_member_bit_offset(t, member) / 8;
8093 
8094 	switch (moff) {
8095 	case offsetof(struct sched_ext_ops, init_task):
8096 #ifdef CONFIG_EXT_GROUP_SCHED
8097 	case offsetof(struct sched_ext_ops, cgroup_init):
8098 	case offsetof(struct sched_ext_ops, cgroup_exit):
8099 	case offsetof(struct sched_ext_ops, cgroup_prep_move):
8100 #endif
8101 	case offsetof(struct sched_ext_ops, cpu_online):
8102 	case offsetof(struct sched_ext_ops, cpu_offline):
8103 	case offsetof(struct sched_ext_ops, init_cids):
8104 	case offsetof(struct sched_ext_ops, init):
8105 	case offsetof(struct sched_ext_ops, exit):
8106 	case offsetof(struct sched_ext_ops, sub_attach):
8107 	case offsetof(struct sched_ext_ops, sub_detach):
8108 		break;
8109 	default:
8110 		if (prog->sleepable)
8111 			return -EINVAL;
8112 	}
8113 
8114 #ifdef CONFIG_EXT_SUB_SCHED
8115 	/*
8116 	 * Enable private stack for operations that can nest along the
8117 	 * hierarchy.
8118 	 *
8119 	 * XXX - Ideally, we should only do this for scheds that allow
8120 	 * sub-scheds and sub-scheds themselves but I don't know how to access
8121 	 * struct_ops from here.
8122 	 */
8123 	switch (moff) {
8124 	case offsetof(struct sched_ext_ops, dispatch):
8125 		prog->aux->priv_stack_requested = true;
8126 		prog->aux->recursion_detected = scx_pstack_recursion_on_dispatch;
8127 		break;
8128 	case offsetof(struct sched_ext_ops, sub_caps_updated):
8129 		prog->aux->priv_stack_requested = true;
8130 		prog->aux->recursion_detected = scx_pstack_recursion_on_caps_updated;
8131 		break;
8132 	}
8133 #endif	/* CONFIG_EXT_SUB_SCHED */
8134 
8135 	return 0;
8136 }
8137 
8138 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
8139 {
8140 	struct scx_enable_cmd cmd = { .ops = kdata };
8141 
8142 	return scx_enable(&cmd, link);
8143 }
8144 
8145 struct scx_arena_scan {
8146 	struct bpf_map	*arena;
8147 	int		err;
8148 };
8149 
8150 /*
8151  * The verifier enforces one arena per BPF program, so each struct_ops
8152  * member prog contributes at most one arena via bpf_prog_arena().
8153  * Require all non-NULL contributions to match.
8154  */
8155 static int scx_arena_scan_prog(struct bpf_prog *prog, void *data)
8156 {
8157 	struct scx_arena_scan *s = data;
8158 	struct bpf_map *arena = NULL;
8159 
8160 	/* arena.o, which defines these, is built only on MMU && 64BIT */
8161 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
8162 	arena = bpf_prog_arena(prog);
8163 #endif
8164 	if (!arena)
8165 		return 0;
8166 	if (s->arena && s->arena != arena) {
8167 		s->err = -EINVAL;
8168 		return 1;
8169 	}
8170 	s->arena = arena;
8171 	return 0;
8172 }
8173 
8174 static int bpf_scx_reg_cid(void *kdata, struct bpf_link *link)
8175 {
8176 	struct scx_enable_cmd cmd = { .ops_cid = kdata, .is_cid_type = true };
8177 	struct scx_arena_scan scan = {};
8178 	int ret;
8179 
8180 	bpf_struct_ops_for_each_prog(kdata, scx_arena_scan_prog, &scan);
8181 	if (scan.err) {
8182 		pr_err("sched_ext: cid-form scheduler uses multiple arena maps\n");
8183 		return scan.err;
8184 	}
8185 	if (!scan.arena) {
8186 		pr_err("sched_ext: cid-form scheduler must use a BPF arena map\n");
8187 		return -EINVAL;
8188 	}
8189 
8190 	bpf_map_inc(scan.arena);
8191 	cmd.arena_map = scan.arena;
8192 	ret = scx_enable(&cmd, link);
8193 	if (cmd.arena_map)		/* not consumed by scx_alloc_and_add_sched() */
8194 		bpf_map_put(cmd.arena_map);
8195 	return ret;
8196 }
8197 
8198 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
8199 {
8200 	struct sched_ext_ops *ops = kdata;
8201 	struct scx_sched *sch = rcu_dereference_protected(ops->priv, true);
8202 
8203 	scx_disable(sch, SCX_EXIT_UNREG);
8204 	scx_flush_disable_work(sch);
8205 	RCU_INIT_POINTER(ops->priv, NULL);
8206 	kobject_put(&sch->kobj);
8207 }
8208 
8209 static int bpf_scx_init(struct btf *btf)
8210 {
8211 	task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]);
8212 
8213 	return 0;
8214 }
8215 
8216 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
8217 {
8218 	/*
8219 	 * sched_ext does not support updating the actively-loaded BPF
8220 	 * scheduler, as registering a BPF scheduler can always fail if the
8221 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
8222 	 * etc. Similarly, we can always race with unregistration happening
8223 	 * elsewhere, such as with sysrq.
8224 	 */
8225 	return -EOPNOTSUPP;
8226 }
8227 
8228 static int bpf_scx_validate(void *kdata)
8229 {
8230 	return 0;
8231 }
8232 
8233 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
8234 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
8235 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
8236 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {}
8237 static void sched_ext_ops__tick(struct task_struct *p) {}
8238 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {}
8239 static void sched_ext_ops__running(struct task_struct *p) {}
8240 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {}
8241 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {}
8242 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; }
8243 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; }
8244 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {}
8245 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {}
8246 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {}
8247 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {}
8248 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {}
8249 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
8250 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {}
8251 static void sched_ext_ops__enable(struct task_struct *p) {}
8252 static void sched_ext_ops__disable(struct task_struct *p) {}
8253 #ifdef CONFIG_EXT_GROUP_SCHED
8254 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; }
8255 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {}
8256 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; }
8257 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
8258 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
8259 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
8260 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
8261 static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}
8262 #endif	/* CONFIG_EXT_GROUP_SCHED */
8263 static s32 sched_ext_ops__sub_attach(struct scx_sub_attach_args *args) { return -EINVAL; }
8264 static void sched_ext_ops__sub_detach(struct scx_sub_detach_args *args) {}
8265 static void sched_ext_ops__cpu_online(s32 cpu) {}
8266 static void sched_ext_ops__cpu_offline(s32 cpu) {}
8267 static s32 sched_ext_ops__init_cids(void) { return -EINVAL; }
8268 static s32 sched_ext_ops__init(void) { return -EINVAL; }
8269 static void sched_ext_ops__exit(struct scx_exit_info *info) {}
8270 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {}
8271 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {}
8272 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {}
8273 
8274 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
8275 	.select_cpu		= sched_ext_ops__select_cpu,
8276 	.enqueue		= sched_ext_ops__enqueue,
8277 	.dequeue		= sched_ext_ops__dequeue,
8278 	.dispatch		= sched_ext_ops__dispatch,
8279 	.tick			= sched_ext_ops__tick,
8280 	.runnable		= sched_ext_ops__runnable,
8281 	.running		= sched_ext_ops__running,
8282 	.stopping		= sched_ext_ops__stopping,
8283 	.quiescent		= sched_ext_ops__quiescent,
8284 	.yield			= sched_ext_ops__yield,
8285 	.core_sched_before	= sched_ext_ops__core_sched_before,
8286 	.set_weight		= sched_ext_ops__set_weight,
8287 	.set_cpumask		= sched_ext_ops__set_cpumask,
8288 	.update_idle		= sched_ext_ops__update_idle,
8289 	.cpu_acquire		= sched_ext_ops__cpu_acquire,
8290 	.cpu_release		= sched_ext_ops__cpu_release,
8291 	.init_task		= sched_ext_ops__init_task,
8292 	.exit_task		= sched_ext_ops__exit_task,
8293 	.enable			= sched_ext_ops__enable,
8294 	.disable		= sched_ext_ops__disable,
8295 #ifdef CONFIG_EXT_GROUP_SCHED
8296 	.cgroup_init		= sched_ext_ops__cgroup_init,
8297 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
8298 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
8299 	.cgroup_move		= sched_ext_ops__cgroup_move,
8300 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
8301 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
8302 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
8303 	.cgroup_set_idle	= sched_ext_ops__cgroup_set_idle,
8304 #endif
8305 	.sub_attach		= sched_ext_ops__sub_attach,
8306 	.sub_detach		= sched_ext_ops__sub_detach,
8307 	.cpu_online		= sched_ext_ops__cpu_online,
8308 	.cpu_offline		= sched_ext_ops__cpu_offline,
8309 	.init_cids		= sched_ext_ops__init_cids,
8310 	.init			= sched_ext_ops__init,
8311 	.exit			= sched_ext_ops__exit,
8312 	.dump			= sched_ext_ops__dump,
8313 	.dump_cpu		= sched_ext_ops__dump_cpu,
8314 	.dump_task		= sched_ext_ops__dump_task,
8315 };
8316 
8317 static struct bpf_struct_ops bpf_sched_ext_ops = {
8318 	.verifier_ops = &bpf_scx_verifier_ops,
8319 	.reg = bpf_scx_reg,
8320 	.unreg = bpf_scx_unreg,
8321 	.check_member = bpf_scx_check_member,
8322 	.init_member = bpf_scx_init_member,
8323 	.init = bpf_scx_init,
8324 	.update = bpf_scx_update,
8325 	.validate = bpf_scx_validate,
8326 	.name = "sched_ext_ops",
8327 	.owner = THIS_MODULE,
8328 	.cfi_stubs = &__bpf_ops_sched_ext_ops
8329 };
8330 
8331 /*
8332  * cid-form cfi stubs. Stubs whose signatures match the cpu-form (param types
8333  * identical, only param names differ across structs) are reused. Some need
8334  * fresh stubs, set_cmask due to an argument type difference and the sub-sched
8335  * notifiers because no cpu-form stub exists to reuse.
8336  */
8337 static void sched_ext_ops_cid__set_cmask(struct task_struct *p,
8338 					 const struct scx_cmask *cmask) {}
8339 static void sched_ext_ops__sub_caps_updated(const struct scx_cmask *cmask, u64 caps) {}
8340 static void sched_ext_ops__sub_ecaps_updated(s32 cid, u64 before, u64 after) {}
8341 
8342 static struct sched_ext_ops_cid __bpf_ops_sched_ext_ops_cid = {
8343 	.select_cid		= sched_ext_ops__select_cpu,
8344 	.enqueue		= sched_ext_ops__enqueue,
8345 	.dequeue		= sched_ext_ops__dequeue,
8346 	.dispatch		= sched_ext_ops__dispatch,
8347 	.tick			= sched_ext_ops__tick,
8348 	.runnable		= sched_ext_ops__runnable,
8349 	.running		= sched_ext_ops__running,
8350 	.stopping		= sched_ext_ops__stopping,
8351 	.quiescent		= sched_ext_ops__quiescent,
8352 	.yield			= sched_ext_ops__yield,
8353 	.core_sched_before	= sched_ext_ops__core_sched_before,
8354 	.set_weight		= sched_ext_ops__set_weight,
8355 	.set_cmask		= sched_ext_ops_cid__set_cmask,
8356 	.update_idle		= sched_ext_ops__update_idle,
8357 	.init_task		= sched_ext_ops__init_task,
8358 	.exit_task		= sched_ext_ops__exit_task,
8359 	.enable			= sched_ext_ops__enable,
8360 	.disable		= sched_ext_ops__disable,
8361 #ifdef CONFIG_EXT_GROUP_SCHED
8362 	.cpuctl_init		= sched_ext_ops__cgroup_init,
8363 	.cpuctl_exit		= sched_ext_ops__cgroup_exit,
8364 	.cpuctl_prep_move	= sched_ext_ops__cgroup_prep_move,
8365 	.cpuctl_move		= sched_ext_ops__cgroup_move,
8366 	.cpuctl_cancel_move	= sched_ext_ops__cgroup_cancel_move,
8367 	.cpuctl_set_weight	= sched_ext_ops__cgroup_set_weight,
8368 	.cpuctl_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
8369 	.cpuctl_set_idle	= sched_ext_ops__cgroup_set_idle,
8370 #endif
8371 	.sub_attach		= sched_ext_ops__sub_attach,
8372 	.sub_detach		= sched_ext_ops__sub_detach,
8373 	.sub_caps_updated	= sched_ext_ops__sub_caps_updated,
8374 	.sub_ecaps_updated	= sched_ext_ops__sub_ecaps_updated,
8375 	.cid_online		= sched_ext_ops__cpu_online,
8376 	.cid_offline		= sched_ext_ops__cpu_offline,
8377 	.init_cids		= sched_ext_ops__init_cids,
8378 	.init			= sched_ext_ops__init,
8379 	.exit			= sched_ext_ops__exit,
8380 	.dump			= sched_ext_ops__dump,
8381 	.dump_cid		= sched_ext_ops__dump_cpu,
8382 	.dump_task		= sched_ext_ops__dump_task,
8383 };
8384 
8385 /*
8386  * The cid-form struct_ops shares all bpf_struct_ops hooks with the cpu form.
8387  * init_member, check_member, reg, unreg, etc. process kdata as the byte block
8388  * verified to match by the BUILD_BUG_ON checks in scx_init().
8389  */
8390 static struct bpf_struct_ops bpf_sched_ext_ops_cid = {
8391 	.verifier_ops = &bpf_scx_cid_verifier_ops,
8392 	.reg = bpf_scx_reg_cid,
8393 	.unreg = bpf_scx_unreg,
8394 	.check_member = bpf_scx_check_member,
8395 	.init_member = bpf_scx_init_member,
8396 	.init = bpf_scx_init,
8397 	.update = bpf_scx_update,
8398 	.validate = bpf_scx_validate,
8399 	.name = "sched_ext_ops_cid",
8400 	.owner = THIS_MODULE,
8401 	.cfi_stubs = &__bpf_ops_sched_ext_ops_cid
8402 };
8403 
8404 
8405 /********************************************************************************
8406  * System integration and init.
8407  */
8408 
8409 static void sysrq_handle_sched_ext_reset(u8 key)
8410 {
8411 	struct scx_sched *sch;
8412 
8413 	sch = rcu_dereference(scx_root);
8414 	if (likely(sch))
8415 		scx_disable(sch, SCX_EXIT_SYSRQ);
8416 	else
8417 		pr_info("sched_ext: BPF schedulers not loaded\n");
8418 }
8419 
8420 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
8421 	.handler	= sysrq_handle_sched_ext_reset,
8422 	.help_msg	= "reset-sched-ext(S)",
8423 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
8424 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
8425 };
8426 
8427 static void sysrq_handle_sched_ext_dump(u8 key)
8428 {
8429 	struct scx_exit_info ei = {
8430 		.kind		= SCX_EXIT_NONE,
8431 		.exit_cpu	= -1,
8432 		.reason		= "SysRq-D",
8433 	};
8434 	struct scx_sched *sch;
8435 
8436 	list_for_each_entry_rcu(sch, &scx_sched_all, all)
8437 		scx_dump_state(sch, &ei, 0, false);
8438 }
8439 
8440 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
8441 	.handler	= sysrq_handle_sched_ext_dump,
8442 	.help_msg	= "dump-sched-ext(D)",
8443 	.action_msg	= "Trigger sched_ext debug dump",
8444 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
8445 };
8446 
8447 static bool can_skip_idle_kick(struct rq *rq)
8448 {
8449 	lockdep_assert_rq_held(rq);
8450 
8451 	/*
8452 	 * We can skip idle kicking if @rq is going to go through at least one
8453 	 * full SCX scheduling cycle before going idle. Just checking whether
8454 	 * curr is not idle is insufficient because we could be racing
8455 	 * balance_one() trying to pull the next task from a remote rq, which
8456 	 * may fail, and @rq may become idle afterwards.
8457 	 *
8458 	 * The race window is small and we don't and can't guarantee that @rq is
8459 	 * only kicked while idle anyway. Skip only when sure.
8460 	 */
8461 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_BALANCE);
8462 }
8463 
8464 static bool kick_one_cpu(s32 cpu, struct scx_sched_pcpu *pcpu, struct rq *this_rq,
8465 			 unsigned long *ksyncs)
8466 {
8467 	struct rq *rq = cpu_rq(cpu);
8468 	struct scx_rq *this_scx = &this_rq->scx;
8469 	const struct sched_class *cur_class;
8470 	bool should_wait = false;
8471 	bool kickable;
8472 	unsigned long flags;
8473 
8474 	raw_spin_rq_lock_irqsave(rq, flags);
8475 	cur_class = rq->curr->sched_class;
8476 
8477 	/*
8478 	 * During CPU hotplug, a CPU may depend on kicking itself to make
8479 	 * forward progress. Allow kicking self regardless of online state. If
8480 	 * @cpu is running a higher class task, we have no control over @cpu.
8481 	 * Skip kicking. A sub-sched lacking baseline access on @cid has no
8482 	 * business forcing a reschedule there - skip. This is the authoritative
8483 	 * cap check: ecaps is read here under @rq's lock.
8484 	 */
8485 	kickable = (cpu_online(cpu) || cpu == cpu_of(this_rq)) &&
8486 		   !sched_class_above(cur_class, &ext_sched_class);
8487 
8488 	if (kickable && !scx_missing_caps(pcpu->sch, cpu, SCX_CAP_BASE)) {
8489 		if (cpumask_test_cpu(cpu, pcpu->cpus_to_preempt)) {
8490 			if (cur_class == &ext_sched_class) {
8491 				u64 caps = scx_caps_for_preempt(pcpu->sch, rq, 0);
8492 
8493 				if (unlikely(scx_missing_caps(pcpu->sch, cpu, caps)))
8494 					__scx_add_event(pcpu->sch, SCX_EV_SUB_PREEMPT_DENIED, 1);
8495 				else if (unlikely(!scx_set_task_slice(rq->curr, 0)))
8496 					__scx_add_event(pcpu->sch, SCX_EV_SLICE_DENIED, 1);
8497 			}
8498 			cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt);
8499 		}
8500 
8501 		if (cpumask_test_cpu(cpu, pcpu->cpus_to_wait)) {
8502 			if (cur_class == &ext_sched_class) {
8503 				cpumask_set_cpu(cpu, this_scx->cpus_to_sync);
8504 				ksyncs[cpu] = rq->scx.kick_sync;
8505 				should_wait = true;
8506 			}
8507 			cpumask_clear_cpu(cpu, pcpu->cpus_to_wait);
8508 		}
8509 
8510 		resched_curr(rq);
8511 	} else {
8512 		/* a kickable cpu was skipped solely for the missing caps */
8513 		if (kickable)
8514 			__scx_add_event(pcpu->sch, SCX_EV_SUB_KICK_DENIED, 1);
8515 		cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt);
8516 		cpumask_clear_cpu(cpu, pcpu->cpus_to_wait);
8517 	}
8518 
8519 	scx_rq_lock_drop(rq);
8520 	raw_spin_rq_unlock_irqrestore(rq, flags);
8521 
8522 	return should_wait;
8523 }
8524 
8525 static void kick_one_cpu_if_idle(s32 cpu, struct scx_sched_pcpu *pcpu,
8526 				 struct rq *this_rq)
8527 {
8528 	struct rq *rq = cpu_rq(cpu);
8529 	unsigned long flags;
8530 
8531 	raw_spin_rq_lock_irqsave(rq, flags);
8532 
8533 	/* idle kicks need baseline access too, see kick_one_cpu() */
8534 	if (!can_skip_idle_kick(rq) &&
8535 	    (cpu_online(cpu) || cpu == cpu_of(this_rq))) {
8536 		if (likely(!scx_missing_caps(pcpu->sch, cpu, SCX_CAP_BASE)))
8537 			resched_curr(rq);
8538 		else
8539 			__scx_add_event(pcpu->sch, SCX_EV_SUB_KICK_DENIED, 1);
8540 	}
8541 
8542 	scx_rq_lock_drop(rq);
8543 	raw_spin_rq_unlock_irqrestore(rq, flags);
8544 }
8545 
8546 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
8547 {
8548 	struct rq *this_rq = this_rq();
8549 	struct scx_rq *this_scx = &this_rq->scx;
8550 	struct scx_kick_syncs __rcu *ksyncs_pcpu = __this_cpu_read(scx_kick_syncs);
8551 	struct scx_sched_pcpu *pcpu, *tmp;
8552 	bool should_wait = false;
8553 	unsigned long *ksyncs;
8554 	s32 cpu;
8555 
8556 	/* can race with free_kick_syncs() during scheduler disable */
8557 	if (unlikely(!ksyncs_pcpu))
8558 		return;
8559 
8560 	ksyncs = rcu_dereference_bh(ksyncs_pcpu)->syncs;
8561 
8562 	/*
8563 	 * Walk scheds with pending kicks on this cpu. scx_kick_cpu() adds to
8564 	 * the list under local_irq_save() and only this irq_work consumes it.
8565 	 * A plain list without locking is sufficient.
8566 	 */
8567 	list_for_each_entry_safe(pcpu, tmp, &this_scx->sched_pcpus_to_kick, to_kick_node) {
8568 		list_del_init(&pcpu->to_kick_node);
8569 
8570 		for_each_cpu(cpu, pcpu->cpus_to_kick) {
8571 			should_wait |= kick_one_cpu(cpu, pcpu, this_rq, ksyncs);
8572 			cpumask_clear_cpu(cpu, pcpu->cpus_to_kick);
8573 			cpumask_clear_cpu(cpu, pcpu->cpus_to_kick_if_idle);
8574 		}
8575 
8576 		for_each_cpu(cpu, pcpu->cpus_to_kick_if_idle) {
8577 			kick_one_cpu_if_idle(cpu, pcpu, this_rq);
8578 			cpumask_clear_cpu(cpu, pcpu->cpus_to_kick_if_idle);
8579 		}
8580 	}
8581 
8582 	/*
8583 	 * Can't wait in hardirq — kick_sync can't advance, deadlocking if
8584 	 * CPUs wait for each other. Defer to kick_sync_wait_bal_cb().
8585 	 */
8586 	if (should_wait) {
8587 		raw_spin_rq_lock(this_rq);
8588 		this_scx->kick_sync_pending = true;
8589 		resched_curr(this_rq);
8590 		scx_rq_lock_drop(this_rq);
8591 		raw_spin_rq_unlock(this_rq);
8592 	}
8593 }
8594 
8595 /**
8596  * print_scx_info - print out sched_ext scheduler state
8597  * @log_lvl: the log level to use when printing
8598  * @p: target task
8599  *
8600  * If a sched_ext scheduler is enabled, print the name and state of the
8601  * scheduler. If @p is on sched_ext, print further information about the task.
8602  *
8603  * This function can be safely called on any task as long as the task_struct
8604  * itself is accessible. While safe, this function isn't synchronized and may
8605  * print out mixups or garbages of limited length.
8606  */
8607 void print_scx_info(const char *log_lvl, struct task_struct *p)
8608 {
8609 	struct scx_sched *sch;
8610 	enum scx_enable_state state = scx_enable_state();
8611 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
8612 	char runnable_at_buf[22] = "?";
8613 	struct sched_class *class;
8614 	unsigned long runnable_at;
8615 
8616 	guard(rcu)();
8617 
8618 	sch = scx_task_sched_rcu(p);
8619 
8620 	if (!sch)
8621 		return;
8622 
8623 	/*
8624 	 * Carefully check if the task was running on sched_ext, and then
8625 	 * carefully copy the time it's been runnable, and its state.
8626 	 */
8627 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
8628 	    class != &ext_sched_class) {
8629 		printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name,
8630 		       scx_enable_state_str[state], all);
8631 		return;
8632 	}
8633 
8634 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
8635 				      sizeof(runnable_at)))
8636 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
8637 			  jiffies_delta_msecs(runnable_at, jiffies));
8638 
8639 	/* print everything onto one line to conserve console space */
8640 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
8641 	       log_lvl, sch->ops.name, scx_enable_state_str[state], all,
8642 	       runnable_at_buf);
8643 }
8644 
8645 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr)
8646 {
8647 	struct scx_sched *sch;
8648 
8649 	guard(rcu)();
8650 
8651 	sch = rcu_dereference(scx_root);
8652 	if (!sch)
8653 		return NOTIFY_OK;
8654 
8655 	/*
8656 	 * SCX schedulers often have userspace components which are sometimes
8657 	 * involved in critial scheduling paths. PM operations involve freezing
8658 	 * userspace which can lead to scheduling misbehaviors including stalls.
8659 	 * Let's bypass while PM operations are in progress.
8660 	 */
8661 	switch (event) {
8662 	case PM_HIBERNATION_PREPARE:
8663 	case PM_SUSPEND_PREPARE:
8664 	case PM_RESTORE_PREPARE:
8665 		scx_bypass(sch, true);
8666 		break;
8667 	case PM_POST_HIBERNATION:
8668 	case PM_POST_SUSPEND:
8669 	case PM_POST_RESTORE:
8670 		scx_bypass(sch, false);
8671 		break;
8672 	}
8673 
8674 	return NOTIFY_OK;
8675 }
8676 
8677 static struct notifier_block scx_pm_notifier = {
8678 	.notifier_call = scx_pm_handler,
8679 };
8680 
8681 void __init init_sched_ext_class(void)
8682 {
8683 	s32 cpu, v;
8684 
8685 	/*
8686 	 * The following is to prevent the compiler from optimizing out the enum
8687 	 * definitions so that BPF scheduler implementations can use them
8688 	 * through the generated vmlinux.h.
8689 	 */
8690 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT |
8691 		   SCX_TG_ONLINE);
8692 
8693 	scx_idle_init_masks();
8694 
8695 	for_each_possible_cpu(cpu) {
8696 		struct rq *rq = cpu_rq(cpu);
8697 		int  n = cpu_to_node(cpu);
8698 
8699 		/* local_dsq's sch will be set during scx_root_enable() */
8700 		BUG_ON(scx_init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL, NULL));
8701 #ifdef CONFIG_EXT_SUB_SCHED
8702 		BUG_ON(scx_init_dsq(&rq->scx.reject_dsq, SCX_DSQ_REJECT, NULL));
8703 		scx_rescue_init(rq);
8704 #endif
8705 
8706 		INIT_LIST_HEAD(&rq->scx.runnable_list);
8707 		INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals);
8708 
8709 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_sync, GFP_KERNEL, n));
8710 		INIT_LIST_HEAD(&rq->scx.sched_pcpus_to_kick);
8711 		raw_spin_lock_init(&rq->scx.deferred_reenq_lock);
8712 		INIT_LIST_HEAD(&rq->scx.deferred_reenq_locals);
8713 		INIT_LIST_HEAD(&rq->scx.deferred_reenq_users);
8714 		rq->scx.deferred_irq_work = IRQ_WORK_INIT_HARD(deferred_irq_workfn);
8715 		rq->scx.kick_cpus_irq_work = IRQ_WORK_INIT_HARD(kick_cpus_irq_workfn);
8716 
8717 		if (cpu_online(cpu))
8718 			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
8719 	}
8720 
8721 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
8722 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
8723 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
8724 
8725 #ifdef CONFIG_EXT_SUB_SCHED
8726 	BUG_ON(rhashtable_init(&scx_sched_hash, &scx_sched_hash_params));
8727 #endif	/* CONFIG_EXT_SUB_SCHED */
8728 }
8729 
8730 
8731 /********************************************************************************
8732  * Helpers that can be called from the BPF scheduler.
8733  */
8734 static bool scx_vet_enq_flags(struct scx_sched *sch, u64 dsq_id, u64 *enq_flags)
8735 {
8736 	bool is_local = dsq_id == SCX_DSQ_LOCAL ||
8737 		(dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON;
8738 
8739 	if (unlikely(*enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
8740 		scx_error(sch, "invalid enq_flags 0x%llx", *enq_flags);
8741 		return false;
8742 	}
8743 
8744 	if (*enq_flags & SCX_ENQ_IMMED) {
8745 		if (unlikely(!is_local)) {
8746 			scx_error(sch, "SCX_ENQ_IMMED on a non-local DSQ 0x%llx", dsq_id);
8747 			return false;
8748 		}
8749 	} else if ((sch->ops.flags & SCX_OPS_ALWAYS_ENQ_IMMED) && is_local) {
8750 		*enq_flags |= SCX_ENQ_IMMED;
8751 	}
8752 
8753 	if (unlikely((*enq_flags & SCX_ENQ_RESCUE) && !is_local)) {
8754 		scx_error(sch, "SCX_ENQ_RESCUE on a non-local DSQ 0x%llx", dsq_id);
8755 		return false;
8756 	}
8757 
8758 	return true;
8759 }
8760 
8761 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p,
8762 				    u64 dsq_id, u64 *enq_flags)
8763 {
8764 	lockdep_assert_irqs_disabled();
8765 
8766 	if (unlikely(!p)) {
8767 		scx_error(sch, "called with NULL task");
8768 		return false;
8769 	}
8770 
8771 	/* see SCX_EV_INSERT_NOT_OWNED definition */
8772 	if (unlikely(!scx_task_on_sched(sch, p))) {
8773 		__scx_add_event(sch, SCX_EV_INSERT_NOT_OWNED, 1);
8774 		return false;
8775 	}
8776 
8777 	if (!scx_vet_enq_flags(sch, dsq_id, enq_flags))
8778 		return false;
8779 
8780 	return true;
8781 }
8782 
8783 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p,
8784 				  u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
8785 {
8786 	struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
8787 	struct task_struct *ddsp_task;
8788 
8789 	ddsp_task = __this_cpu_read(direct_dispatch_task);
8790 	if (ddsp_task) {
8791 		mark_direct_dispatch(sch, ddsp_task, p, dsq_id, slice, vtime, enq_flags);
8792 		return;
8793 	}
8794 
8795 	if (unlikely(dspc->cursor >= sch->dsp_max_batch)) {
8796 		scx_error(sch, "dispatch buffer overflow");
8797 		return;
8798 	}
8799 
8800 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
8801 		.task = p,
8802 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
8803 		.dsq_id = dsq_id,
8804 		.slice = slice,
8805 		.vtime = vtime,
8806 		.enq_flags = enq_flags,
8807 	};
8808 }
8809 
8810 __bpf_kfunc_start_defs();
8811 
8812 /**
8813  * scx_bpf_dsq_insert___v2 - Insert a task into the FIFO queue of a DSQ
8814  * @p: task_struct to insert
8815  * @dsq_id: DSQ to insert into
8816  * @slice: duration @p can run for in nsecs, 0 to keep the current value
8817  * @enq_flags: SCX_ENQ_*
8818  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8819  *
8820  * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to
8821  * call this function spuriously. Can be called from ops.enqueue(),
8822  * ops.select_cpu(), and ops.dispatch().
8823  *
8824  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
8825  * and @p must match the task being enqueued.
8826  *
8827  * When called from ops.select_cpu(), @enq_flags and @dsq_id are stored, and @p
8828  * will be directly inserted into the corresponding dispatch queue after
8829  * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be
8830  * inserted into the local DSQ of the CPU returned by ops.select_cpu().
8831  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
8832  * task is inserted.
8833  *
8834  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
8835  * and this function can be called upto ops.dispatch_max_batch times to insert
8836  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
8837  * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the
8838  * counter.
8839  *
8840  * This function doesn't have any locking restrictions and may be called under
8841  * BPF locks (in the future when BPF introduces more flexible locking).
8842  *
8843  * @p is allowed to run for @slice. The scheduling path is triggered on slice
8844  * exhaustion. If zero, the current residual slice is maintained. If
8845  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
8846  * scx_bpf_kick_cpu() to trigger scheduling.
8847  *
8848  * Returns %true on successful insertion, %false on failure. On the root
8849  * scheduler, %false return triggers scheduler abort and the caller doesn't need
8850  * to check the return value.
8851  */
8852 __bpf_kfunc bool scx_bpf_dsq_insert___v2(struct task_struct *p, u64 dsq_id,
8853 					 u64 slice, u64 enq_flags,
8854 					 const struct bpf_prog_aux *aux)
8855 {
8856 	struct scx_sched *sch;
8857 
8858 	guard(rcu)();
8859 	sch = scx_prog_sched(aux);
8860 	if (unlikely(!sch))
8861 		return false;
8862 
8863 	if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags))
8864 		return false;
8865 
8866 	scx_dsq_insert_commit(sch, p, dsq_id, slice, 0, enq_flags);
8867 
8868 	return true;
8869 }
8870 
8871 /*
8872  * COMPAT: Will be removed in v6.23 along with the ___v2 suffix.
8873  */
8874 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id,
8875 				    u64 slice, u64 enq_flags,
8876 				    const struct bpf_prog_aux *aux)
8877 {
8878 	scx_bpf_dsq_insert___v2(p, dsq_id, slice, enq_flags, aux);
8879 }
8880 
8881 static bool scx_dsq_insert_vtime(struct scx_sched *sch, struct task_struct *p,
8882 				 u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
8883 {
8884 	if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags))
8885 		return false;
8886 
8887 	scx_dsq_insert_commit(sch, p, dsq_id, slice, vtime, enq_flags | SCX_ENQ_DSQ_PRIQ);
8888 
8889 	return true;
8890 }
8891 
8892 struct scx_bpf_dsq_insert_vtime_args {
8893 	/* @p can't be packed together as KF_RCU is not transitive */
8894 	u64			dsq_id;
8895 	u64			slice;
8896 	u64			vtime;
8897 	u64			enq_flags;
8898 };
8899 
8900 /**
8901  * __scx_bpf_dsq_insert_vtime - Arg-wrapped vtime DSQ insertion
8902  * @p: task_struct to insert
8903  * @args: struct containing the rest of the arguments
8904  *       @args->dsq_id: DSQ to insert into
8905  *       @args->slice: duration @p can run for in nsecs, 0 to keep the current value
8906  *       @args->vtime: @p's ordering inside the vtime-sorted queue of the target DSQ
8907  *       @args->enq_flags: SCX_ENQ_*
8908  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
8909  *
8910  * Wrapper kfunc that takes arguments via struct to work around BPF's 5 argument
8911  * limit. BPF programs should use scx_bpf_dsq_insert_vtime() which is provided
8912  * as an inline wrapper in common.bpf.h.
8913  *
8914  * Insert @p into the vtime priority queue of the DSQ identified by
8915  * @args->dsq_id. Tasks queued into the priority queue are ordered by
8916  * @args->vtime. All other aspects are identical to scx_bpf_dsq_insert().
8917  *
8918  * @args->vtime ordering is according to time_before64() which considers
8919  * wrapping. A numerically larger vtime may indicate an earlier position in the
8920  * ordering and vice-versa.
8921  *
8922  * A DSQ can only be used as a FIFO or priority queue at any given time and this
8923  * function must not be called on a DSQ which already has one or more FIFO tasks
8924  * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and
8925  * SCX_DSQ_GLOBAL) cannot be used as priority queues.
8926  *
8927  * Returns %true on successful insertion, %false on failure. On the root
8928  * scheduler, %false return triggers scheduler abort and the caller doesn't need
8929  * to check the return value.
8930  */
8931 __bpf_kfunc bool
8932 __scx_bpf_dsq_insert_vtime(struct task_struct *p,
8933 			   struct scx_bpf_dsq_insert_vtime_args *args,
8934 			   const struct bpf_prog_aux *aux)
8935 {
8936 	struct scx_sched *sch;
8937 
8938 	guard(rcu)();
8939 
8940 	sch = scx_prog_sched(aux);
8941 	if (unlikely(!sch))
8942 		return false;
8943 
8944 	return scx_dsq_insert_vtime(sch, p, args->dsq_id, args->slice,
8945 				    args->vtime, args->enq_flags);
8946 }
8947 
8948 /*
8949  * COMPAT: Will be removed in v6.23.
8950  */
8951 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id,
8952 					  u64 slice, u64 vtime, u64 enq_flags)
8953 {
8954 	struct scx_sched *sch;
8955 
8956 	guard(rcu)();
8957 
8958 	sch = rcu_dereference(scx_root);
8959 	if (unlikely(!sch))
8960 		return;
8961 
8962 #ifdef CONFIG_EXT_SUB_SCHED
8963 	/*
8964 	 * Disallow if any sub-scheds are attached. There is no way to tell
8965 	 * which scheduler called us, just error out @p's scheduler.
8966 	 */
8967 	if (unlikely(!list_empty(&sch->children))) {
8968 		scx_error(scx_task_sched(p), "__scx_bpf_dsq_insert_vtime() must be used");
8969 		return;
8970 	}
8971 #endif
8972 
8973 	scx_dsq_insert_vtime(sch, p, dsq_id, slice, vtime, enq_flags);
8974 }
8975 
8976 __bpf_kfunc_end_defs();
8977 
8978 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
8979 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_IMPLICIT_ARGS | KF_RCU)
8980 BTF_ID_FLAGS(func, scx_bpf_dsq_insert___v2, KF_IMPLICIT_ARGS | KF_RCU)
8981 BTF_ID_FLAGS(func, __scx_bpf_dsq_insert_vtime, KF_IMPLICIT_ARGS | KF_RCU)
8982 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU)
8983 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
8984 
8985 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
8986 	.owner			= THIS_MODULE,
8987 	.set			= &scx_kfunc_ids_enqueue_dispatch,
8988 	.filter			= scx_kfunc_context_filter,
8989 };
8990 
8991 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit,
8992 			 struct task_struct *p, u64 dsq_id, u64 enq_flags,
8993 			 bool priq)
8994 {
8995 	struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq;
8996 	struct scx_sched *sch;
8997 	struct rq *p_rq, *src_rq, *locked_rq;
8998 	bool dispatched = false;
8999 	unsigned long flags;
9000 
9001 	/*
9002 	 * The verifier considers an iterator slot initialized on any
9003 	 * KF_ITER_NEW return, so a BPF program may legally reach here after
9004 	 * bpf_iter_scx_dsq_new() failed and left @kit->dsq NULL.
9005 	 */
9006 	if (unlikely(!src_dsq))
9007 		return false;
9008 
9009 	sch = src_dsq->sched;
9010 
9011 	if (!scx_vet_enq_flags(sch, dsq_id, &enq_flags))
9012 		return false;
9013 
9014 	/* internal bit, can only go in after @enq_flags is vetted */
9015 	if (priq)
9016 		enq_flags |= SCX_ENQ_DSQ_PRIQ;
9017 
9018 	/*
9019 	 * If the BPF scheduler keeps calling this function repeatedly, it can
9020 	 * cause similar live-lock conditions as scx_consume_dispatch_q().
9021 	 */
9022 	if (unlikely(READ_ONCE(sch->aborting)))
9023 		return false;
9024 
9025 	if (unlikely(!scx_task_on_sched(sch, p))) {
9026 		scx_error(sch, "scx_bpf_dsq_move[_vtime]() on %s[%d] but the task belongs to a different scheduler",
9027 			  p->comm, p->pid);
9028 		return false;
9029 	}
9030 
9031 	/*
9032 	 * Can be called from either ops.dispatch() holding the dispatched rq's
9033 	 * lock or any context where no rq lock is held. If latter, lock @p's
9034 	 * task_rq which we'll likely need anyway.
9035 	 */
9036 	src_rq = task_rq(p);
9037 
9038 	local_irq_save(flags);
9039 
9040 	/*
9041 	 * Under core scheduling, dispatch can run for a sibling rq, so the
9042 	 * locked rq is not necessarily this CPU's.
9043 	 */
9044 	locked_rq = scx_locked_rq();
9045 
9046 	if (locked_rq) {
9047 		if (locked_rq != src_rq)
9048 			switch_rq_lock(locked_rq, src_rq);
9049 	} else {
9050 		raw_spin_rq_lock(src_rq);
9051 	}
9052 
9053 	p_rq = src_rq;
9054 	raw_spin_lock(&src_dsq->lock);
9055 
9056 	/* did someone else get to it while we dropped the locks? */
9057 	if (nldsq_cursor_lost_task(&kit->cursor, src_rq, src_dsq, p)) {
9058 		raw_spin_unlock(&src_dsq->lock);
9059 		goto out;
9060 	}
9061 
9062 	/* @p is still on $src_dsq and stable, determine the destination */
9063 	dst_dsq = find_dsq_for_dispatch(sch, locked_rq ?: this_rq(), dsq_id, task_cpu(p));
9064 
9065 	/*
9066 	 * Apply vtime and slice updates before moving. @p is still on $src_dsq
9067 	 * with both $src_dsq and its task_rq locked, satisfying the write
9068 	 * rules, and the PRIQ insertion into $dst_dsq reads the new vtime.
9069 	 */
9070 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME)
9071 		p->scx.dsq_vtime = kit->vtime;
9072 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE)
9073 		scx_set_task_slice(p, kit->slice);
9074 
9075 	/* execute move */
9076 	p_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq);
9077 	dispatched = true;
9078 out:
9079 	if (locked_rq) {
9080 		if (locked_rq != p_rq)
9081 			switch_rq_lock(p_rq, locked_rq);
9082 	} else {
9083 		scx_rq_lock_drop(p_rq);
9084 		raw_spin_rq_unlock_irqrestore(p_rq, flags);
9085 	}
9086 
9087 	kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE |
9088 			       __SCX_DSQ_ITER_HAS_VTIME);
9089 	return dispatched;
9090 }
9091 
9092 __bpf_kfunc_start_defs();
9093 
9094 /**
9095  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
9096  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9097  *
9098  * Can only be called from ops.dispatch().
9099  */
9100 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(const struct bpf_prog_aux *aux)
9101 {
9102 	struct scx_sched *sch;
9103 
9104 	guard(rcu)();
9105 
9106 	sch = scx_prog_sched(aux);
9107 	if (unlikely(!sch))
9108 		return 0;
9109 
9110 	return sch->dsp_max_batch - __this_cpu_read(sch->pcpu->dsp_ctx.cursor);
9111 }
9112 
9113 /**
9114  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
9115  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9116  *
9117  * Cancel the latest dispatch. Can be called multiple times to cancel further
9118  * dispatches. Can only be called from ops.dispatch().
9119  */
9120 __bpf_kfunc void scx_bpf_dispatch_cancel(const struct bpf_prog_aux *aux)
9121 {
9122 	struct scx_sched *sch;
9123 	struct scx_dsp_ctx *dspc;
9124 
9125 	guard(rcu)();
9126 
9127 	sch = scx_prog_sched(aux);
9128 	if (unlikely(!sch))
9129 		return;
9130 
9131 	dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
9132 
9133 	if (dspc->cursor > 0)
9134 		dspc->cursor--;
9135 	else
9136 		scx_error(sch, "dispatch buffer underflow");
9137 }
9138 
9139 /**
9140  * scx_bpf_dsq_move_to_local___v2 - move a task from a DSQ to the current CPU's local DSQ
9141  * @dsq_id: DSQ to move task from. Must be a user-created DSQ
9142  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9143  * @enq_flags: %SCX_ENQ_*
9144  *
9145  * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's
9146  * local DSQ for execution with @enq_flags applied. Can only be called from
9147  * ops.dispatch().
9148  *
9149  * Built-in DSQs (%SCX_DSQ_GLOBAL and %SCX_DSQ_LOCAL*) are not supported as
9150  * sources. Local DSQs support reenqueueing (a task can be picked up for
9151  * execution, dequeued for property changes, or reenqueued), but the BPF
9152  * scheduler cannot directly iterate or move tasks from them. %SCX_DSQ_GLOBAL
9153  * is similar but also doesn't support reenqueueing, as it maps to multiple
9154  * per-node DSQs making the scope difficult to define; this may change in the
9155  * future.
9156  *
9157  * This function flushes the in-flight dispatches from scx_bpf_dsq_insert()
9158  * before trying to move from the specified DSQ. It may also grab rq locks and
9159  * thus can't be called under any BPF locks.
9160  *
9161  * Returns %true if a task has been moved, %false if there isn't any task to
9162  * move.
9163  */
9164 __bpf_kfunc bool scx_bpf_dsq_move_to_local___v2(u64 dsq_id, u64 enq_flags,
9165 						const struct bpf_prog_aux *aux)
9166 {
9167 	struct scx_dispatch_q *dsq;
9168 	struct scx_sched *sch;
9169 	struct scx_dsp_ctx *dspc;
9170 
9171 	guard(rcu)();
9172 
9173 	sch = scx_prog_sched(aux);
9174 	if (unlikely(!sch))
9175 		return false;
9176 
9177 	if (!scx_vet_enq_flags(sch, SCX_DSQ_LOCAL, &enq_flags))
9178 		return false;
9179 
9180 	dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx;
9181 
9182 	scx_flush_dispatch_buf(sch, dspc->rq);
9183 
9184 	dsq = find_user_dsq(sch, dsq_id);
9185 	if (unlikely(!dsq)) {
9186 		scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id);
9187 		return false;
9188 	}
9189 
9190 	if (scx_consume_dispatch_q(sch, dspc->rq, dsq, enq_flags)) {
9191 		/*
9192 		 * A successfully consumed task can be dequeued before it starts
9193 		 * running while the CPU is trying to migrate other dispatched
9194 		 * tasks. Bump nr_tasks to tell balance_one() to retry on empty
9195 		 * local DSQ.
9196 		 */
9197 		dspc->nr_tasks++;
9198 		return true;
9199 	} else {
9200 		return false;
9201 	}
9202 }
9203 
9204 /*
9205  * COMPAT: ___v2 was introduced in v7.1. Remove this and ___v2 tag in the future.
9206  */
9207 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id, const struct bpf_prog_aux *aux)
9208 {
9209 	return scx_bpf_dsq_move_to_local___v2(dsq_id, 0, aux);
9210 }
9211 
9212 /**
9213  * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs
9214  * @it__iter: DSQ iterator in progress
9215  * @slice: duration the moved task can run for in nsecs
9216  *
9217  * Override the slice of the next task that will be moved from @it__iter using
9218  * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous
9219  * slice duration is kept.
9220  */
9221 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter,
9222 					    u64 slice)
9223 {
9224 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
9225 
9226 	kit->slice = slice;
9227 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE;
9228 }
9229 
9230 /**
9231  * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs
9232  * @it__iter: DSQ iterator in progress
9233  * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ
9234  *
9235  * Override the vtime of the next task that will be moved from @it__iter using
9236  * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice
9237  * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the
9238  * override is ignored and cleared.
9239  */
9240 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter,
9241 					    u64 vtime)
9242 {
9243 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
9244 
9245 	kit->vtime = vtime;
9246 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME;
9247 }
9248 
9249 /**
9250  * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ
9251  * @it__iter: DSQ iterator in progress
9252  * @p: task to transfer
9253  * @dsq_id: DSQ to move @p to
9254  * @enq_flags: SCX_ENQ_*
9255  *
9256  * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ
9257  * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can
9258  * be the destination.
9259  *
9260  * For the transfer to be successful, @p must still be on the DSQ and have been
9261  * queued before the DSQ iteration started. This function doesn't care whether
9262  * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have
9263  * been queued before the iteration started.
9264  *
9265  * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update.
9266  *
9267  * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq
9268  * lock (e.g. BPF timers or SYSCALL programs).
9269  *
9270  * Returns %true if @p has been consumed, %false if @p had already been
9271  * consumed, dequeued, or, for sub-scheds, @dsq_id points to a disallowed local
9272  * DSQ.
9273  */
9274 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter,
9275 				  struct task_struct *p, u64 dsq_id,
9276 				  u64 enq_flags)
9277 {
9278 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
9279 			    p, dsq_id, enq_flags, false);
9280 }
9281 
9282 /**
9283  * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ
9284  * @it__iter: DSQ iterator in progress
9285  * @p: task to transfer
9286  * @dsq_id: DSQ to move @p to
9287  * @enq_flags: SCX_ENQ_*
9288  *
9289  * Transfer @p which is on the DSQ currently iterated by @it__iter to the
9290  * priority queue of the DSQ specified by @dsq_id. The destination must be a
9291  * user DSQ as only user DSQs support priority queue.
9292  *
9293  * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice()
9294  * and scx_bpf_dsq_move_set_vtime() to update.
9295  *
9296  * All other aspects are identical to scx_bpf_dsq_move(). See
9297  * scx_bpf_dsq_insert_vtime() for more information on @vtime.
9298  */
9299 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter,
9300 					struct task_struct *p, u64 dsq_id,
9301 					u64 enq_flags)
9302 {
9303 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
9304 			    p, dsq_id, enq_flags, true);
9305 }
9306 
9307 __bpf_kfunc_end_defs();
9308 
9309 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
9310 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots, KF_IMPLICIT_ARGS)
9311 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel, KF_IMPLICIT_ARGS)
9312 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local, KF_IMPLICIT_ARGS)
9313 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local___v2, KF_IMPLICIT_ARGS)
9314 /* scx_bpf_dsq_move*() also in scx_kfunc_ids_unlocked: callable from unlocked contexts */
9315 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
9316 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
9317 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
9318 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
9319 #ifdef CONFIG_EXT_SUB_SCHED
9320 BTF_ID_FLAGS(func, scx_bpf_sub_dispatch, KF_IMPLICIT_ARGS)
9321 #endif
9322 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
9323 
9324 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
9325 	.owner			= THIS_MODULE,
9326 	.set			= &scx_kfunc_ids_dispatch,
9327 	.filter			= scx_kfunc_context_filter,
9328 };
9329 
9330 __bpf_kfunc_start_defs();
9331 
9332 /**
9333  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
9334  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9335  *
9336  * Iterate over all of the tasks currently enqueued on the local DSQ of the
9337  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
9338  * processed tasks. Can only be called from ops.cpu_release().
9339  */
9340 __bpf_kfunc u32 scx_bpf_reenqueue_local(const struct bpf_prog_aux *aux)
9341 {
9342 	struct scx_sched *sch;
9343 	struct rq *rq;
9344 
9345 	guard(rcu)();
9346 	sch = scx_prog_sched(aux);
9347 	if (unlikely(!sch))
9348 		return 0;
9349 
9350 	rq = cpu_rq(smp_processor_id());
9351 	lockdep_assert_rq_held(rq);
9352 
9353 	return reenq_local(sch, rq, SCX_REENQ_ANY);
9354 }
9355 
9356 __bpf_kfunc_end_defs();
9357 
9358 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
9359 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local, KF_IMPLICIT_ARGS)
9360 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
9361 
9362 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
9363 	.owner			= THIS_MODULE,
9364 	.set			= &scx_kfunc_ids_cpu_release,
9365 	.filter			= scx_kfunc_context_filter,
9366 };
9367 
9368 __bpf_kfunc_start_defs();
9369 
9370 /**
9371  * scx_bpf_create_dsq - Create a custom DSQ
9372  * @dsq_id: DSQ to create
9373  * @node: NUMA node to allocate from
9374  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9375  *
9376  * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable
9377  * scx callback, and any BPF_PROG_TYPE_SYSCALL prog.
9378  */
9379 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node, const struct bpf_prog_aux *aux)
9380 {
9381 	struct scx_dispatch_q *dsq;
9382 	struct scx_sched *sch;
9383 	s32 ret;
9384 
9385 	if (unlikely(node >= (int)nr_node_ids ||
9386 		     (node < 0 && node != NUMA_NO_NODE)))
9387 		return -EINVAL;
9388 
9389 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN))
9390 		return -EINVAL;
9391 
9392 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
9393 	if (!dsq)
9394 		return -ENOMEM;
9395 
9396 	/*
9397 	 * scx_init_dsq() must be called in GFP_KERNEL context. Init it with
9398 	 * NULL @sch and update afterwards.
9399 	 */
9400 	ret = scx_init_dsq(dsq, dsq_id, NULL);
9401 	if (ret) {
9402 		kfree(dsq);
9403 		return ret;
9404 	}
9405 
9406 	rcu_read_lock();
9407 
9408 	sch = scx_prog_sched(aux);
9409 	if (sch) {
9410 		dsq->sched = sch;
9411 		ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node,
9412 						    dsq_hash_params);
9413 	} else {
9414 		ret = -ENODEV;
9415 	}
9416 
9417 	rcu_read_unlock();
9418 	if (ret) {
9419 		exit_dsq(dsq);
9420 		kfree(dsq);
9421 	}
9422 	return ret;
9423 }
9424 
9425 __bpf_kfunc_end_defs();
9426 
9427 BTF_KFUNCS_START(scx_kfunc_ids_unlocked)
9428 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_IMPLICIT_ARGS | KF_SLEEPABLE)
9429 /* also in scx_kfunc_ids_dispatch: also callable from ops.dispatch() */
9430 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
9431 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
9432 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
9433 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
9434 /* also in scx_kfunc_ids_select_cpu: also callable from ops.select_cpu()/ops.enqueue() */
9435 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU)
9436 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU)
9437 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU)
9438 BTF_KFUNCS_END(scx_kfunc_ids_unlocked)
9439 
9440 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = {
9441 	.owner			= THIS_MODULE,
9442 	.set			= &scx_kfunc_ids_unlocked,
9443 	.filter			= scx_kfunc_context_filter,
9444 };
9445 
9446 __bpf_kfunc_start_defs();
9447 
9448 /**
9449  * scx_bpf_task_set_slice - Set task's time slice
9450  * @p: task of interest
9451  * @slice: time slice to set in nsecs
9452  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9453  *
9454  * Set @p's time slice. @p must be on the calling scheduler. The value is
9455  * applied whether or not the caller holds @p's rq lock - see the slice write
9456  * rules above for the ownership model.
9457  *
9458  * Raising the slice is honored only while the scheduler holds %SCX_CAP_BASE on
9459  * @p's cpu, otherwise it is counted in %SCX_EV_SLICE_DENIED. Shortening is
9460  * always allowed. On the stashed path the slice is packed into an atomic64_t
9461  * with the scheduler id and a flag bit, so a slice too large to fit is clamped
9462  * and counted in %SCX_EV_SLICE_CLAMPED. %SCX_SLICE_INF is preserved.
9463  *
9464  * Return %true on success, %false if @p is not on the calling scheduler.
9465  */
9466 __bpf_kfunc bool scx_bpf_task_set_slice(struct task_struct *p, u64 slice,
9467 					const struct bpf_prog_aux *aux)
9468 {
9469 	struct scx_sched *sch;
9470 	struct rq *locked_rq;
9471 
9472 	guard(rcu)();
9473 	sch = scx_prog_sched(aux);
9474 	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
9475 		return false;
9476 
9477 	/*
9478 	 * Directly write only when we hold the lock of the rq @p is queued or
9479 	 * running on. See the write rules above.
9480 	 *
9481 	 * While @p is queued on a user DSQ or in the BPF scheduler,
9482 	 * synchronization is the scheduler's responsibility. This write can
9483 	 * race a concurrent dispatch's commit, see apply_slice_vtime().
9484 	 *
9485 	 * Making this kfunc always go through the oob stash would leave the
9486 	 * commit as the only direct writer and close the race, but that would
9487 	 * require two more oob application points - the dispatch keep-prev test
9488 	 * and the tick-time expiry check.
9489 	 */
9490 	locked_rq = scx_locked_rq();
9491 	if (!locked_rq ||
9492 	    (READ_ONCE(p->scx.runnable_cpu) != cpu_of(locked_rq) &&
9493 	     !task_current(locked_rq, p))) {
9494 		set_task_slice_oob(sch, p, slice);
9495 		return true;
9496 	}
9497 
9498 	/* under the rq lock: apply now, extensions gated on baseline access */
9499 	if (slice > p->scx.slice &&
9500 	    unlikely(scx_missing_caps(sch, cpu_of(locked_rq), SCX_CAP_BASE))) {
9501 		__scx_add_event(sch, SCX_EV_SLICE_DENIED, 1);
9502 		return true;
9503 	}
9504 
9505 	if (unlikely(!scx_set_task_slice(p, slice)))
9506 		__scx_add_event(sch, SCX_EV_SLICE_DENIED, 1);
9507 
9508 	return true;
9509 }
9510 
9511 /**
9512  * scx_bpf_task_set_dsq_vtime - Set task's virtual time for DSQ ordering
9513  * @p: task of interest
9514  * @vtime: virtual time to set
9515  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9516  *
9517  * Set @p's virtual time to @vtime. Returns %true on success, %false if the
9518  * calling scheduler doesn't have authority over @p.
9519  */
9520 __bpf_kfunc bool scx_bpf_task_set_dsq_vtime(struct task_struct *p, u64 vtime,
9521 					    const struct bpf_prog_aux *aux)
9522 {
9523 	struct scx_sched *sch;
9524 
9525 	guard(rcu)();
9526 	sch = scx_prog_sched(aux);
9527 	if (unlikely(!sch || !scx_task_on_sched(sch, p)))
9528 		return false;
9529 
9530 	p->scx.dsq_vtime = vtime;
9531 	return true;
9532 }
9533 
9534 void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags)
9535 {
9536 	struct scx_sched_pcpu *pcpu;
9537 	struct rq *this_rq;
9538 	unsigned long irq_flags;
9539 
9540 	/*
9541 	 * The per-cpu kick list is guarded only by local_irq_save(), which does
9542 	 * not mask NMIs, so kicking from NMI could corrupt it and is unsupported.
9543 	 */
9544 	if (unlikely(in_nmi())) {
9545 		scx_error(sch, "scx_bpf_kick_cpu() called from NMI");
9546 		return;
9547 	}
9548 
9549 	local_irq_save(irq_flags);
9550 
9551 	this_rq = this_rq();
9552 	pcpu = this_cpu_ptr(sch->pcpu);
9553 
9554 	/*
9555 	 * While bypassing for PM ops, IRQ handling may not be online which can
9556 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
9557 	 * IRQ status update. Suppress kicking.
9558 	 */
9559 	if (scx_bypassing(sch, cpu_of(this_rq)))
9560 		goto out;
9561 
9562 	/*
9563 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
9564 	 * rq locks. We can probably be smarter and avoid bouncing if called
9565 	 * from ops which don't hold a rq lock.
9566 	 *
9567 	 * The kick masks are owned by @sch->pcpu, so that a preempt kick can be
9568 	 * attributed to @sch.
9569 	 */
9570 	if (flags & SCX_KICK_IDLE) {
9571 		struct rq *target_rq = cpu_rq(cpu);
9572 
9573 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT)))
9574 			scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
9575 
9576 		if (raw_spin_rq_trylock(target_rq)) {
9577 			if (can_skip_idle_kick(target_rq)) {
9578 				scx_rq_lock_drop(target_rq);
9579 				raw_spin_rq_unlock(target_rq);
9580 				goto out;
9581 			}
9582 			scx_rq_lock_drop(target_rq);
9583 			raw_spin_rq_unlock(target_rq);
9584 		}
9585 		cpumask_set_cpu(cpu, pcpu->cpus_to_kick_if_idle);
9586 	} else {
9587 		cpumask_set_cpu(cpu, pcpu->cpus_to_kick);
9588 
9589 		if (flags & SCX_KICK_PREEMPT)
9590 			cpumask_set_cpu(cpu, pcpu->cpus_to_preempt);
9591 		if (flags & SCX_KICK_WAIT)
9592 			cpumask_set_cpu(cpu, pcpu->cpus_to_wait);
9593 	}
9594 
9595 	if (list_empty(&pcpu->to_kick_node))
9596 		list_add_tail(&pcpu->to_kick_node, &this_rq->scx.sched_pcpus_to_kick);
9597 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
9598 out:
9599 	local_irq_restore(irq_flags);
9600 }
9601 
9602 /**
9603  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
9604  * @cpu: cpu to kick
9605  * @flags: %SCX_KICK_* flags
9606  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9607  *
9608  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
9609  * trigger rescheduling on a busy CPU. This can be called from any online
9610  * scx_ops operation and the actual kicking is performed asynchronously through
9611  * an irq work.
9612  */
9613 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags, const struct bpf_prog_aux *aux)
9614 {
9615 	struct scx_sched *sch;
9616 
9617 	guard(rcu)();
9618 	sch = scx_prog_sched(aux);
9619 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
9620 		scx_kick_cpu(sch, cpu, flags);
9621 }
9622 
9623 /**
9624  * scx_bpf_kick_cid - Trigger reschedule on the CPU mapped to @cid
9625  * @cid: cid to kick
9626  * @flags: %SCX_KICK_* flags
9627  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9628  *
9629  * cid-addressed equivalent of scx_bpf_kick_cpu(). An invalid @cid aborts the
9630  * scheduler via scx_cid_to_cpu(). Caps are enforced on the delivery path: a
9631  * kick is dropped if the caller lacks baseline access on @cid, and a
9632  * %SCX_KICK_PREEMPT degrades to a plain reschedule if the caller lacks
9633  * %SCX_CAP_PREEMPT for a task outside its subtree.
9634  */
9635 __bpf_kfunc void scx_bpf_kick_cid(s32 cid, u64 flags, const struct bpf_prog_aux *aux)
9636 {
9637 	struct scx_sched *sch;
9638 	s32 cpu;
9639 
9640 	guard(rcu)();
9641 	sch = scx_prog_sched(aux);
9642 	if (unlikely(!sch))
9643 		return;
9644 	cpu = scx_cid_to_cpu(sch, cid);
9645 	if (cpu < 0)
9646 		return;
9647 	scx_kick_cpu(sch, cpu, flags);
9648 }
9649 
9650 /**
9651  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
9652  * @dsq_id: id of the DSQ
9653  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9654  *
9655  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
9656  * -%ENOENT is returned.
9657  *
9658  * %SCX_DSQ_LOCAL resolves to the local DSQ of the rq the current scheduler
9659  * operation is locked to - e.g. the rq being dispatched for in ops.dispatch() -
9660  * or the calling CPU's when no rq is locked.
9661  */
9662 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id, const struct bpf_prog_aux *aux)
9663 {
9664 	struct scx_sched *sch;
9665 	struct scx_dispatch_q *dsq;
9666 	s32 ret;
9667 
9668 	preempt_disable();
9669 
9670 	sch = scx_prog_sched(aux);
9671 	if (unlikely(!sch)) {
9672 		ret = -ENODEV;
9673 		goto out;
9674 	}
9675 
9676 	if (dsq_id == SCX_DSQ_LOCAL) {
9677 		ret = READ_ONCE((scx_locked_rq() ?: this_rq())->scx.local_dsq.nr);
9678 		goto out;
9679 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
9680 		s32 cpu = scx_cpu_ret(sch, dsq_id & SCX_DSQ_LOCAL_CPU_MASK);
9681 
9682 		if (scx_cpu_valid(sch, cpu, NULL)) {
9683 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
9684 			goto out;
9685 		}
9686 	} else {
9687 		dsq = find_user_dsq(sch, dsq_id);
9688 		if (dsq) {
9689 			ret = READ_ONCE(dsq->nr);
9690 			goto out;
9691 		}
9692 	}
9693 	ret = -ENOENT;
9694 out:
9695 	preempt_enable();
9696 	return ret;
9697 }
9698 
9699 /**
9700  * scx_bpf_destroy_dsq - Destroy a custom DSQ
9701  * @dsq_id: DSQ to destroy
9702  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9703  *
9704  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
9705  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
9706  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
9707  * which doesn't exist. Can be called from any online scx_ops operations.
9708  */
9709 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id, const struct bpf_prog_aux *aux)
9710 {
9711 	struct scx_sched *sch;
9712 
9713 	guard(rcu)();
9714 	sch = scx_prog_sched(aux);
9715 	if (sch)
9716 		destroy_dsq(sch, dsq_id);
9717 }
9718 
9719 /**
9720  * bpf_iter_scx_dsq_new - Create a DSQ iterator
9721  * @it: iterator to initialize
9722  * @dsq_id: DSQ to iterate
9723  * @flags: %SCX_DSQ_ITER_*
9724  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9725  *
9726  * Initialize BPF iterator @it which can be used with bpf_for_each() to walk
9727  * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes
9728  * tasks which are already queued when this function is invoked.
9729  */
9730 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id,
9731 				     u64 flags, const struct bpf_prog_aux *aux)
9732 {
9733 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
9734 	struct scx_sched *sch;
9735 
9736 	BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) >
9737 		     sizeof(struct bpf_iter_scx_dsq));
9738 	BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) !=
9739 		     __alignof__(struct bpf_iter_scx_dsq));
9740 	BUILD_BUG_ON(__SCX_DSQ_ITER_ALL_FLAGS &
9741 		     ((1U << __SCX_DSQ_LNODE_PRIV_SHIFT) - 1));
9742 
9743 	/*
9744 	 * next() and destroy() will be called regardless of the return value.
9745 	 * Always clear $kit->dsq.
9746 	 */
9747 	kit->dsq = NULL;
9748 
9749 	sch = scx_prog_sched(aux);
9750 	if (unlikely(!sch))
9751 		return -ENODEV;
9752 
9753 	if (flags & ~__SCX_DSQ_ITER_USER_FLAGS)
9754 		return -EINVAL;
9755 
9756 	kit->dsq = find_user_dsq(sch, dsq_id);
9757 	if (!kit->dsq)
9758 		return -ENOENT;
9759 
9760 	kit->cursor = INIT_DSQ_LIST_CURSOR(kit->cursor, kit->dsq, flags);
9761 
9762 	return 0;
9763 }
9764 
9765 /**
9766  * bpf_iter_scx_dsq_next - Progress a DSQ iterator
9767  * @it: iterator to progress
9768  *
9769  * Return the next task. See bpf_iter_scx_dsq_new().
9770  */
9771 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it)
9772 {
9773 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
9774 
9775 	if (!kit->dsq)
9776 		return NULL;
9777 
9778 	guard(raw_spinlock_irqsave)(&kit->dsq->lock);
9779 
9780 	return nldsq_cursor_next_task(&kit->cursor, kit->dsq);
9781 }
9782 
9783 /**
9784  * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator
9785  * @it: iterator to destroy
9786  *
9787  * Undo scx_iter_scx_dsq_new().
9788  */
9789 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it)
9790 {
9791 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
9792 
9793 	if (!kit->dsq)
9794 		return;
9795 
9796 	if (!list_empty(&kit->cursor.node)) {
9797 		unsigned long flags;
9798 
9799 		raw_spin_lock_irqsave(&kit->dsq->lock, flags);
9800 		list_del_init(&kit->cursor.node);
9801 		raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
9802 	}
9803 	kit->dsq = NULL;
9804 }
9805 
9806 /**
9807  * scx_bpf_dsq_peek - Lockless peek at the first element.
9808  * @dsq_id: DSQ to examine.
9809  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9810  *
9811  * Read the first element in the DSQ. This is semantically equivalent to using
9812  * the DSQ iterator, but is lockfree. Of course, like any lockless operation,
9813  * this provides only a point-in-time snapshot, and the contents may change
9814  * by the time any subsequent locking operation reads the queue.
9815  *
9816  * Returns the pointer, or NULL indicates an empty queue OR internal error.
9817  */
9818 __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id,
9819 						 const struct bpf_prog_aux *aux)
9820 {
9821 	struct scx_sched *sch;
9822 	struct scx_dispatch_q *dsq;
9823 
9824 	sch = scx_prog_sched(aux);
9825 	if (unlikely(!sch))
9826 		return NULL;
9827 
9828 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) {
9829 		scx_error(sch, "peek disallowed on builtin DSQ 0x%llx", dsq_id);
9830 		return NULL;
9831 	}
9832 
9833 	dsq = find_user_dsq(sch, dsq_id);
9834 	if (unlikely(!dsq)) {
9835 		scx_error(sch, "peek on non-existent DSQ 0x%llx", dsq_id);
9836 		return NULL;
9837 	}
9838 
9839 	return rcu_dereference(dsq->first_task);
9840 }
9841 
9842 /**
9843  * scx_bpf_dsq_reenq - Re-enqueue tasks on a DSQ
9844  * @dsq_id: DSQ to re-enqueue
9845  * @reenq_flags: %SCX_RENQ_*
9846  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9847  *
9848  * Iterate over all of the tasks currently enqueued on the DSQ identified by
9849  * @dsq_id, and re-enqueue them in the BPF scheduler. The following DSQs are
9850  * supported:
9851  *
9852  * - Local DSQs (%SCX_DSQ_LOCAL or %SCX_DSQ_LOCAL_ON | $cpu)
9853  * - User DSQs
9854  *
9855  * Re-enqueues are performed asynchronously. Can be called from anywhere.
9856  *
9857  * %SCX_DSQ_LOCAL resolves to the local DSQ of the rq the current scheduler
9858  * operation is locked to - e.g. the rq being dispatched for in ops.dispatch() -
9859  * or the calling CPU's when no rq is locked.
9860  */
9861 __bpf_kfunc void scx_bpf_dsq_reenq(u64 dsq_id, u64 reenq_flags,
9862 				   const struct bpf_prog_aux *aux)
9863 {
9864 	struct rq *locked_rq = scx_locked_rq();
9865 	struct scx_sched *sch;
9866 	struct scx_dispatch_q *dsq;
9867 
9868 	guard(preempt)();
9869 
9870 	sch = scx_prog_sched(aux);
9871 	if (unlikely(!sch))
9872 		return;
9873 
9874 	if (unlikely(reenq_flags & ~__SCX_REENQ_USER_MASK)) {
9875 		scx_error(sch, "invalid SCX_REENQ flags 0x%llx", reenq_flags);
9876 		return;
9877 	}
9878 
9879 	/* not specifying any filter bits is the same as %SCX_REENQ_ANY */
9880 	if (!(reenq_flags & __SCX_REENQ_FILTER_MASK))
9881 		reenq_flags |= SCX_REENQ_ANY;
9882 
9883 	dsq = find_dsq_for_dispatch(sch, locked_rq ?: this_rq(), dsq_id, smp_processor_id());
9884 	schedule_dsq_reenq(sch, dsq, reenq_flags, locked_rq);
9885 }
9886 
9887 /**
9888  * scx_bpf_reenqueue_local___v2 - Re-enqueue tasks on a local DSQ
9889  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9890  *
9891  * Iterate over all of the tasks currently enqueued on the local DSQ of the
9892  * caller's CPU, and re-enqueue them in the BPF scheduler. Can be called from
9893  * anywhere.
9894  *
9895  * This is now a special case of scx_bpf_dsq_reenq() and may be removed in the
9896  * future.
9897  */
9898 __bpf_kfunc void scx_bpf_reenqueue_local___v2(const struct bpf_prog_aux *aux)
9899 {
9900 	scx_bpf_dsq_reenq(SCX_DSQ_LOCAL, 0, aux);
9901 }
9902 
9903 __bpf_kfunc_end_defs();
9904 
9905 __printf(5, 0)
9906 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
9907 			 size_t line_size, char *fmt, unsigned long long *data,
9908 			 u32 data__sz)
9909 {
9910 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
9911 	s32 ret;
9912 
9913 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
9914 	    (data__sz && !data)) {
9915 		scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz);
9916 		return -EINVAL;
9917 	}
9918 
9919 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
9920 	if (ret < 0) {
9921 		scx_error(sch, "failed to read data fields (%d)", ret);
9922 		return ret;
9923 	}
9924 
9925 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
9926 				  &bprintf_data);
9927 	if (ret < 0) {
9928 		scx_error(sch, "format preparation failed (%d)", ret);
9929 		return ret;
9930 	}
9931 
9932 	ret = bstr_printf(line_buf, line_size, fmt,
9933 			  bprintf_data.bin_args);
9934 	bpf_bprintf_cleanup(&bprintf_data);
9935 	if (ret < 0) {
9936 		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
9937 		return ret;
9938 	}
9939 
9940 	return ret;
9941 }
9942 
9943 /*
9944  * Exit @sch with the reason formatted from a BPF-supplied bstr format. The exit
9945  * is claimed first and the reason is formatted directly into the winner-owned
9946  * exit_info buffer, which allows use from any context including NMI.
9947  *
9948  * @fmt_blame is the sched blamed for formatting failures through the
9949  * scx_error() calls in __bstr_format() and differs from @sch when a parent
9950  * supplies the kill reason for a child. A formatting failure doesn't revert the
9951  * claim - @sch still exits with the claimed kind and a fallback message.
9952  */
9953 __printf(5, 0)
9954 bool scx_exit_bstr(struct scx_sched *sch, enum scx_exit_kind kind,
9955 		   s64 exit_code, struct scx_sched *fmt_blame, char *fmt,
9956 		   unsigned long long *data, u32 data__sz)
9957 {
9958 	struct scx_exit_info *ei = sch->exit_info;
9959 	u64 data_buf[MAX_BPRINTF_VARARGS];
9960 	s32 ret;
9961 
9962 	guard(preempt)();
9963 
9964 	if (!scx_claim_exit(sch, kind))
9965 		return false;
9966 
9967 	ret = __bstr_format(fmt_blame, data_buf, ei->msg, SCX_EXIT_MSG_LEN,
9968 			    fmt, data, data__sz);
9969 	if (ret < 0)
9970 		scnprintf(ei->msg, SCX_EXIT_MSG_LEN,
9971 			  "exit message formatting failed (%d)", ret);
9972 
9973 	scx_finish_exit(sch, kind, exit_code, raw_smp_processor_id());
9974 	return true;
9975 }
9976 
9977 __bpf_kfunc_start_defs();
9978 
9979 /**
9980  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
9981  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
9982  * @fmt: error message format string
9983  * @data: format string parameters packaged using ___bpf_fill() macro
9984  * @data__sz: @data len, must end in '__sz' for the verifier
9985  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
9986  *
9987  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
9988  * disabling.
9989  */
9990 __printf(2, 0)
9991 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
9992 				   unsigned long long *data, u32 data__sz,
9993 				   const struct bpf_prog_aux *aux)
9994 {
9995 	struct scx_sched *sch;
9996 
9997 	guard(rcu)();
9998 
9999 	sch = scx_prog_sched(aux);
10000 	if (likely(sch))
10001 		scx_exit_bstr(sch, SCX_EXIT_UNREG_BPF, exit_code, sch, fmt,
10002 			      data, data__sz);
10003 }
10004 
10005 /**
10006  * scx_bpf_error_bstr - Indicate fatal error
10007  * @fmt: error message format string
10008  * @data: format string parameters packaged using ___bpf_fill() macro
10009  * @data__sz: @data len, must end in '__sz' for the verifier
10010  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10011  *
10012  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
10013  * disabling.
10014  */
10015 __printf(1, 0)
10016 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
10017 				    u32 data__sz, const struct bpf_prog_aux *aux)
10018 {
10019 	struct scx_sched *sch;
10020 
10021 	guard(rcu)();
10022 
10023 	sch = scx_prog_sched(aux);
10024 	if (likely(sch))
10025 		scx_exit_bstr(sch, SCX_EXIT_ERROR_BPF, 0, sch, fmt, data,
10026 			      data__sz);
10027 }
10028 
10029 /**
10030  * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler
10031  * @fmt: format string
10032  * @data: format string parameters packaged using ___bpf_fill() macro
10033  * @data__sz: @data len, must end in '__sz' for the verifier
10034  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10035  *
10036  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
10037  * dump_task() to generate extra debug dump specific to the BPF scheduler.
10038  *
10039  * The extra dump may be multiple lines. A single line may be split over
10040  * multiple calls. The last line is automatically terminated.
10041  */
10042 __printf(1, 0)
10043 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
10044 				   u32 data__sz, const struct bpf_prog_aux *aux)
10045 {
10046 	struct scx_sched *sch;
10047 	struct scx_dump_data *dd = &scx_dump_data;
10048 	struct scx_bstr_buf *buf = &dd->buf;
10049 	s32 ret;
10050 
10051 	guard(rcu)();
10052 
10053 	sch = scx_prog_sched(aux);
10054 	if (unlikely(!sch))
10055 		return;
10056 
10057 	if (raw_smp_processor_id() != dd->cpu) {
10058 		scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends");
10059 		return;
10060 	}
10061 
10062 	/* append the formatted string to the line buf */
10063 	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
10064 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
10065 	if (ret < 0) {
10066 		scx_dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
10067 			      dd->prefix, fmt, data, data__sz, ret);
10068 		return;
10069 	}
10070 
10071 	dd->cursor += ret;
10072 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
10073 
10074 	if (!dd->cursor)
10075 		return;
10076 
10077 	/*
10078 	 * If the line buf overflowed or ends in a newline, flush it into the
10079 	 * dump. This is to allow the caller to generate a single line over
10080 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
10081 	 * the line buf, the only case which can lead to an unexpected
10082 	 * truncation is when the caller keeps generating newlines in the middle
10083 	 * instead of the end consecutively. Don't do that.
10084 	 */
10085 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
10086 		ops_dump_flush();
10087 }
10088 
10089 /**
10090  * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU
10091  * @cpu: CPU of interest
10092  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10093  *
10094  * Return the maximum relative capacity of @cpu in relation to the most
10095  * performant CPU in the system. The return value is in the range [1,
10096  * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur().
10097  */
10098 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu, const struct bpf_prog_aux *aux)
10099 {
10100 	struct scx_sched *sch;
10101 
10102 	guard(rcu)();
10103 
10104 	sch = scx_prog_sched(aux);
10105 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
10106 		return arch_scale_cpu_capacity(cpu);
10107 	else
10108 		return SCX_CPUPERF_ONE;
10109 }
10110 
10111 /**
10112  * scx_bpf_cidperf_cap - Query the maximum relative capacity of the CPU at @cid
10113  * @cid: cid of the CPU to query
10114  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10115  *
10116  * cid-addressed equivalent of scx_bpf_cpuperf_cap().
10117  */
10118 __bpf_kfunc u32 scx_bpf_cidperf_cap(s32 cid, const struct bpf_prog_aux *aux)
10119 {
10120 	struct scx_sched *sch;
10121 	s32 cpu;
10122 
10123 	guard(rcu)();
10124 
10125 	sch = scx_prog_sched(aux);
10126 	if (unlikely(!sch))
10127 		return SCX_CPUPERF_ONE;
10128 	cpu = scx_cid_to_cpu(sch, cid);
10129 	if (cpu < 0)
10130 		return SCX_CPUPERF_ONE;
10131 	return arch_scale_cpu_capacity(cpu);
10132 }
10133 
10134 /**
10135  * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU
10136  * @cpu: CPU of interest
10137  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10138  *
10139  * Return the current relative performance of @cpu in relation to its maximum.
10140  * The return value is in the range [1, %SCX_CPUPERF_ONE].
10141  *
10142  * The current performance level of a CPU in relation to the maximum performance
10143  * available in the system can be calculated as follows:
10144  *
10145  *   scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE
10146  *
10147  * The result is in the range [1, %SCX_CPUPERF_ONE].
10148  */
10149 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu, const struct bpf_prog_aux *aux)
10150 {
10151 	struct scx_sched *sch;
10152 
10153 	guard(rcu)();
10154 
10155 	sch = scx_prog_sched(aux);
10156 	if (likely(sch) && scx_cpu_valid(sch, cpu, NULL))
10157 		return arch_scale_freq_capacity(cpu);
10158 	else
10159 		return SCX_CPUPERF_ONE;
10160 }
10161 
10162 /**
10163  * scx_bpf_cidperf_cur - Query the current performance of the CPU at @cid
10164  * @cid: cid of the CPU to query
10165  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10166  *
10167  * cid-addressed equivalent of scx_bpf_cpuperf_cur().
10168  */
10169 __bpf_kfunc u32 scx_bpf_cidperf_cur(s32 cid, const struct bpf_prog_aux *aux)
10170 {
10171 	struct scx_sched *sch;
10172 	s32 cpu;
10173 
10174 	guard(rcu)();
10175 
10176 	sch = scx_prog_sched(aux);
10177 	if (unlikely(!sch))
10178 		return SCX_CPUPERF_ONE;
10179 	cpu = scx_cid_to_cpu(sch, cid);
10180 	if (cpu < 0)
10181 		return SCX_CPUPERF_ONE;
10182 	return arch_scale_freq_capacity(cpu);
10183 }
10184 
10185 /* validate and apply a cpuperf target, see scx_bpf_cpuperf_set() */
10186 static s32 scx_cpuperf_set(struct scx_sched *sch, s32 cpu, u32 perf)
10187 {
10188 	struct rq *rq, *locked_rq;
10189 	struct rq_flags rf;
10190 	s32 ret;
10191 
10192 	if (unlikely(perf > SCX_CPUPERF_ONE)) {
10193 		scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu);
10194 		return -EINVAL;
10195 	}
10196 
10197 	if (!scx_cpu_valid(sch, cpu, NULL))
10198 		return -EINVAL;
10199 
10200 	rq = cpu_rq(cpu);
10201 	locked_rq = scx_locked_rq();
10202 
10203 	/*
10204 	 * When called with an rq lock held, restrict the operation to the
10205 	 * corresponding CPU to prevent ABBA deadlocks.
10206 	 */
10207 	if (locked_rq && rq != locked_rq) {
10208 		scx_error(sch, "Invalid target CPU %d", cpu);
10209 		return -EINVAL;
10210 	}
10211 
10212 	/*
10213 	 * If no rq lock is held, allow to operate on any CPU by acquiring
10214 	 * the corresponding rq lock.
10215 	 */
10216 	if (!locked_rq) {
10217 		rq_lock_irqsave(rq, &rf);
10218 		update_rq_clock(rq);
10219 	}
10220 
10221 	/*
10222 	 * ecaps updates are folded under the rq lock, making this test
10223 	 * authoritative: a write can never land after a revoke has taken
10224 	 * effect on @cpu.
10225 	 */
10226 	if (likely(!scx_missing_caps(sch, cpu, SCX_CAP_PERF))) {
10227 		rq->scx.cpuperf_target = perf;
10228 		cpufreq_update_util(rq, 0);
10229 		ret = 0;
10230 	} else {
10231 		__scx_add_event(sch, SCX_EV_SUB_CIDPERF_DENIED, 1);
10232 		ret = -EACCES;
10233 	}
10234 
10235 	if (!locked_rq)
10236 		rq_unlock_irqrestore(rq, &rf);
10237 
10238 	return ret;
10239 }
10240 
10241 /**
10242  * scx_bpf_cpuperf_set - Set the relative performance target of a CPU
10243  * @cpu: CPU of interest
10244  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
10245  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10246  *
10247  * Set the target performance level of @cpu to @perf. @perf is in linear
10248  * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the
10249  * schedutil cpufreq governor chooses the target frequency.
10250  *
10251  * The actual performance level chosen, CPU grouping, and the overhead and
10252  * latency of the operations are dependent on the hardware and cpufreq driver in
10253  * use. Consult hardware and cpufreq documentation for more information. The
10254  * current performance level can be monitored using scx_bpf_cpuperf_cur().
10255  */
10256 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf, const struct bpf_prog_aux *aux)
10257 {
10258 	struct scx_sched *sch;
10259 
10260 	guard(rcu)();
10261 
10262 	sch = scx_prog_sched(aux);
10263 	if (unlikely(!sch))
10264 		return;
10265 
10266 	scx_cpuperf_set(sch, cpu, perf);
10267 }
10268 
10269 /**
10270  * scx_bpf_cidperf_set - Set the performance target of the CPU at @cid
10271  * @cid: cid of the CPU to target
10272  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
10273  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10274  *
10275  * cid-addressed equivalent of scx_bpf_cpuperf_set(). A sub-sched needs
10276  * SCX_CAP_PERF on @cid. Returns 0 if the target was applied, -%EACCES if
10277  * the write was denied for missing caps, other -errnos if @cid didn't
10278  * resolve.
10279  */
10280 __bpf_kfunc s32 scx_bpf_cidperf_set(s32 cid, u32 perf,
10281 				    const struct bpf_prog_aux *aux)
10282 {
10283 	struct scx_sched *sch;
10284 	s32 cpu;
10285 
10286 	guard(rcu)();
10287 
10288 	sch = scx_prog_sched(aux);
10289 	if (unlikely(!sch))
10290 		return -ENODEV;
10291 	cpu = scx_cid_to_cpu(sch, cid);
10292 	if (cpu < 0)
10293 		return cpu;
10294 
10295 	return scx_cpuperf_set(sch, cpu, perf);
10296 }
10297 
10298 /**
10299  * scx_bpf_nr_node_ids - Return the number of possible node IDs
10300  *
10301  * All valid node IDs in the system are smaller than the returned value.
10302  */
10303 __bpf_kfunc u32 scx_bpf_nr_node_ids(void)
10304 {
10305 	return nr_node_ids;
10306 }
10307 
10308 /**
10309  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
10310  *
10311  * All valid CPU IDs in the system are smaller than the returned value.
10312  */
10313 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
10314 {
10315 	return nr_cpu_ids;
10316 }
10317 
10318 /**
10319  * scx_bpf_nr_cids - Return the size of the cid space
10320  *
10321  * Equals num_possible_cpus(). All valid cids are in [0, return value).
10322  */
10323 __bpf_kfunc u32 scx_bpf_nr_cids(void)
10324 {
10325 	return num_possible_cpus();
10326 }
10327 
10328 /**
10329  * scx_bpf_nr_online_cids - Return current count of online CPUs in cid space
10330  *
10331  * Return num_online_cpus(). The standard model restarts the scheduler on
10332  * hotplug, which lets schedulers treat [0, nr_online_cids) as the online
10333  * range. Schedulers that prefer to handle hotplug without a restart should
10334  * install a custom mapping via scx_bpf_cid_override() and track onlining
10335  * through the ops.cid_online / ops.cid_offline callbacks.
10336  */
10337 __bpf_kfunc u32 scx_bpf_nr_online_cids(void)
10338 {
10339 	return num_online_cpus();
10340 }
10341 
10342 /**
10343  * scx_bpf_this_cid - Return the cid of the CPU this program is running on
10344  *
10345  * cid-addressed equivalent of bpf_get_smp_processor_id() for scx programs.
10346  * The current cpu is trivially valid, so this is just a table lookup. Return
10347  * -EINVAL if called before any scheduler has ever published its cid tables.
10348  */
10349 __bpf_kfunc s32 scx_bpf_this_cid(void)
10350 {
10351 	s16 *tbl;
10352 
10353 	guard(rcu)();
10354 
10355 	tbl = rcu_dereference(scx_cpu_to_cid_tbl);
10356 	if (!tbl)
10357 		return -EINVAL;
10358 	return tbl[raw_smp_processor_id()];
10359 }
10360 
10361 /**
10362  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
10363  */
10364 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
10365 {
10366 	return cpu_possible_mask;
10367 }
10368 
10369 /**
10370  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
10371  */
10372 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
10373 {
10374 	return cpu_online_mask;
10375 }
10376 
10377 /**
10378  * scx_bpf_put_cpumask - Release a possible/online cpumask
10379  * @cpumask: cpumask to release
10380  */
10381 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
10382 {
10383 	/*
10384 	 * Empty function body because we aren't actually acquiring or releasing
10385 	 * a reference to a global cpumask, which is read-only in the caller and
10386 	 * is never released. The acquire / release semantics here are just used
10387 	 * to make the cpumask is a trusted pointer in the caller.
10388 	 */
10389 }
10390 
10391 /**
10392  * scx_bpf_task_running - Is task currently running?
10393  * @p: task of interest
10394  */
10395 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
10396 {
10397 	return task_rq(p)->curr == p;
10398 }
10399 
10400 /**
10401  * scx_bpf_task_cpu - CPU a task is currently associated with
10402  * @p: task of interest
10403  */
10404 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
10405 {
10406 	return task_cpu(p);
10407 }
10408 
10409 /**
10410  * scx_bpf_task_cid - cid a task is currently associated with
10411  * @p: task of interest
10412  *
10413  * cid-addressed equivalent of scx_bpf_task_cpu(). task_cpu(p) is always a
10414  * valid cpu, so this is just a table lookup. Return -EINVAL if called before
10415  * any scheduler has ever published its cid tables.
10416  */
10417 __bpf_kfunc s32 scx_bpf_task_cid(const struct task_struct *p)
10418 {
10419 	s16 *tbl;
10420 
10421 	/* KF_RCU covers only @p - a sleepable program holds no RCU lock */
10422 	guard(rcu)();
10423 
10424 	tbl = rcu_dereference(scx_cpu_to_cid_tbl);
10425 	if (!tbl)
10426 		return -EINVAL;
10427 	return tbl[task_cpu(p)];
10428 }
10429 
10430 /**
10431  * scx_bpf_locked_rq - Return the rq currently locked by SCX
10432  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10433  *
10434  * Returns the rq if a rq lock is currently held by SCX.
10435  * Otherwise emits an error and returns NULL.
10436  */
10437 __bpf_kfunc struct rq *scx_bpf_locked_rq(const struct bpf_prog_aux *aux)
10438 {
10439 	struct scx_sched *sch;
10440 	struct rq *rq;
10441 
10442 	guard(preempt)();
10443 
10444 	sch = scx_prog_sched(aux);
10445 	if (unlikely(!sch))
10446 		return NULL;
10447 
10448 	rq = scx_locked_rq();
10449 	if (!rq) {
10450 		scx_error(sch, "accessing rq without holding rq lock");
10451 		return NULL;
10452 	}
10453 
10454 	return rq;
10455 }
10456 
10457 /**
10458  * scx_bpf_cpu_curr - Return remote CPU's curr task
10459  * @cpu: CPU of interest
10460  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10461  *
10462  * Callers must hold RCU read lock (KF_RCU).
10463  */
10464 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_aux *aux)
10465 {
10466 	struct scx_sched *sch;
10467 
10468 	guard(rcu)();
10469 
10470 	sch = scx_prog_sched(aux);
10471 	if (unlikely(!sch))
10472 		return NULL;
10473 
10474 	if (!scx_cpu_valid(sch, cpu, NULL))
10475 		return NULL;
10476 
10477 	return rcu_dereference(cpu_rq(cpu)->curr);
10478 }
10479 
10480 /**
10481  * scx_bpf_cid_curr - Return the curr task on the CPU at @cid
10482  * @cid: cid of interest
10483  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10484  *
10485  * cid-addressed equivalent of scx_bpf_cpu_curr(). Callers must hold RCU
10486  * read lock (KF_RCU).
10487  */
10488 __bpf_kfunc struct task_struct *scx_bpf_cid_curr(s32 cid, const struct bpf_prog_aux *aux)
10489 {
10490 	struct scx_sched *sch;
10491 	s32 cpu;
10492 
10493 	guard(rcu)();
10494 
10495 	sch = scx_prog_sched(aux);
10496 	if (unlikely(!sch))
10497 		return NULL;
10498 	cpu = scx_cid_to_cpu(sch, cid);
10499 	if (cpu < 0)
10500 		return NULL;
10501 	return rcu_dereference(cpu_rq(cpu)->curr);
10502 }
10503 
10504 /**
10505  * scx_bpf_tid_to_task - Look up a task by its scx tid
10506  * @tid: task ID previously read from p->scx.tid
10507  *
10508  * Returns the task with the given tid, or NULL if no such task exists. The
10509  * returned pointer is valid until the end of the current RCU read section
10510  * (KF_RCU_PROTECTED). Requires SCX_OPS_TID_TO_TASK to be set on the root
10511  * scheduler; otherwise an error is raised and NULL returned.
10512  */
10513 __bpf_kfunc struct task_struct *scx_bpf_tid_to_task(u64 tid)
10514 {
10515 	struct sched_ext_entity *scx;
10516 
10517 	if (!scx_tid_to_task_enabled()) {
10518 		struct scx_sched *sch = rcu_dereference(scx_root);
10519 
10520 		if (sch)
10521 			scx_error(sch, "scx_bpf_tid_to_task() called without SCX_OPS_TID_TO_TASK");
10522 		return NULL;
10523 	}
10524 
10525 	scx = rhashtable_lookup(&scx_tid_hash, &tid, scx_tid_hash_params);
10526 	if (!scx)
10527 		return NULL;
10528 
10529 	return container_of(scx, struct task_struct, scx);
10530 }
10531 
10532 u64 __scx_bpf_now(struct rq *rq)
10533 {
10534 	/* the caller must be on @rq's cpu or hold its lock */
10535 	lockdep_assert((rq == this_rq() && !preemptible()) ||
10536 		       lockdep_is_held(__rq_lockp(rq)));
10537 
10538 	if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) {
10539 		/* if the rq clock is valid, use the cached rq clock */
10540 		return READ_ONCE(rq->scx.clock);
10541 	} else {
10542 		/*
10543 		 * Otherwise, return a fresh rq clock.
10544 		 *
10545 		 * The rq clock is updated outside of the rq lock.
10546 		 * In this case, keep the updated rq clock invalid so the next
10547 		 * read outside the rq lock gets a fresh rq clock.
10548 		 */
10549 		return sched_clock_cpu(cpu_of(rq));
10550 	}
10551 }
10552 
10553 /**
10554  * scx_bpf_now - Returns a high-performance monotonically non-decreasing
10555  * clock for the current CPU. The clock returned is in nanoseconds.
10556  *
10557  * It provides the following properties:
10558  *
10559  * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently
10560  *  to account for execution time and track tasks' runtime properties.
10561  *  Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which
10562  *  eventually reads a hardware timestamp counter -- is neither performant nor
10563  *  scalable. scx_bpf_now() aims to provide a high-performance clock by
10564  *  using the rq clock in the scheduler core whenever possible.
10565  *
10566  * 2) High enough resolution for the BPF scheduler use cases: In most BPF
10567  *  scheduler use cases, the required clock resolution is lower than the most
10568  *  accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically
10569  *  uses the rq clock in the scheduler core whenever it is valid. It considers
10570  *  that the rq clock is valid from the time the rq clock is updated
10571  *  (update_rq_clock) until the rq is unlocked (rq_unpin_lock).
10572  *
10573  * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now()
10574  *  guarantees the clock never goes backward when comparing them in the same
10575  *  CPU. On the other hand, when comparing clocks in different CPUs, there
10576  *  is no such guarantee -- the clock can go backward. It provides a
10577  *  monotonically *non-decreasing* clock so that it would provide the same
10578  *  clock values in two different scx_bpf_now() calls in the same CPU
10579  *  during the same period of when the rq clock is valid.
10580  */
10581 __bpf_kfunc u64 scx_bpf_now(void)
10582 {
10583 	/*
10584 	 * Note that scx_bpf_now() is re-entrant between a process context and
10585 	 * an interrupt context (e.g., timer interrupt). However, we don't need
10586 	 * to consider the race between them because such race is not observable
10587 	 * from a caller.
10588 	 */
10589 	guard(preempt)();
10590 	return __scx_bpf_now(this_rq());
10591 }
10592 
10593 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events)
10594 {
10595 	int cpu;
10596 
10597 	/* Aggregate per-CPU event counters into @events. */
10598 	memset(events, 0, sizeof(*events));
10599 	for_each_possible_cpu(cpu) {
10600 		struct scx_event_stats *e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats;
10601 #define SCX_EVENT(name)	(events->name += READ_ONCE(e_cpu->name))
10602 		SCX_EVENTS_LIST(SCX_EVENT);
10603 #undef SCX_EVENT
10604 	}
10605 }
10606 
10607 /**
10608  * scx_bpf_events - Read the event counters of the calling scheduler
10609  * @events: output buffer from a BPF program
10610  * @events__sz: @events len, must end in '__sz' for the verifier
10611  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10612  *
10613  * Read the event counters of the scheduler associated with the calling program.
10614  * @events is zeroed when no scheduler can be resolved.
10615  */
10616 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events, size_t events__sz,
10617 				const struct bpf_prog_aux *aux)
10618 {
10619 	struct scx_sched *sch;
10620 	struct scx_event_stats e_sys;
10621 
10622 	rcu_read_lock();
10623 	sch = scx_prog_sched(aux);
10624 	if (sch)
10625 		scx_read_events(sch, &e_sys);
10626 	else
10627 		memset(&e_sys, 0, sizeof(e_sys));
10628 	rcu_read_unlock();
10629 
10630 	/*
10631 	 * We cannot entirely trust a BPF-provided size since a BPF program
10632 	 * might be compiled against a different vmlinux.h, of which
10633 	 * scx_event_stats would be larger (a newer vmlinux.h) or smaller
10634 	 * (an older vmlinux.h). Hence, we use the smaller size to avoid
10635 	 * memory corruption.
10636 	 */
10637 	events__sz = min(events__sz, sizeof(*events));
10638 	memcpy(events, &e_sys, events__sz);
10639 }
10640 
10641 #ifdef CONFIG_CGROUP_SCHED
10642 /**
10643  * scx_bpf_task_cgroup - Return the sched cgroup of a task
10644  * @p: task of interest
10645  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
10646  *
10647  * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with
10648  * from the scheduler's POV. SCX operations should use this function to
10649  * determine @p's current cgroup as, unlike following @p->cgroups,
10650  * @p->sched_task_group is stable for the duration of the SCX op. See
10651  * SCX_CALL_OP_TASK() for details.
10652  */
10653 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p,
10654 					       const struct bpf_prog_aux *aux)
10655 {
10656 	struct task_group *tg = p->sched_task_group;
10657 	struct cgroup *cgrp = &cgrp_dfl_root.cgrp;
10658 	struct scx_sched *sch;
10659 
10660 	guard(rcu)();
10661 
10662 	sch = scx_prog_sched(aux);
10663 	if (unlikely(!sch))
10664 		goto out;
10665 
10666 	if (!scx_kf_arg_task_ok(sch, p))
10667 		goto out;
10668 
10669 	cgrp = tg_cgrp(tg);
10670 
10671 out:
10672 	cgroup_get(cgrp);
10673 	return cgrp;
10674 }
10675 #endif	/* CONFIG_CGROUP_SCHED */
10676 
10677 #ifndef CONFIG_EXT_SUB_SCHED
10678 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps,
10679 				  const struct scx_cmask *cmask__ign,
10680 				  struct scx_cmask *denied_out__ign,
10681 				  const struct bpf_prog_aux *aux)
10682 {
10683 	return -EOPNOTSUPP;
10684 }
10685 
10686 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps,
10687 				    const struct scx_cmask *cmask__ign,
10688 				    const struct bpf_prog_aux *aux)
10689 {
10690 }
10691 
10692 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__ign,
10693 				 const struct bpf_prog_aux *aux)
10694 {
10695 	return -EOPNOTSUPP;
10696 }
10697 
10698 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt,
10699 				      unsigned long long *data, u32 data__sz,
10700 				      const struct bpf_prog_aux *aux)
10701 {
10702 	return -EOPNOTSUPP;
10703 }
10704 #endif	/* !CONFIG_EXT_SUB_SCHED */
10705 
10706 __bpf_kfunc_end_defs();
10707 
10708 BTF_KFUNCS_START(scx_kfunc_ids_any)
10709 BTF_ID_FLAGS(func, scx_bpf_task_set_slice, KF_IMPLICIT_ARGS | KF_RCU);
10710 BTF_ID_FLAGS(func, scx_bpf_task_set_dsq_vtime, KF_IMPLICIT_ARGS | KF_RCU);
10711 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
10712 BTF_ID_FLAGS(func, scx_bpf_kick_cid, KF_IMPLICIT_ARGS)
10713 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued, KF_IMPLICIT_ARGS)
10714 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS)
10715 BTF_ID_FLAGS(func, scx_bpf_dsq_peek, KF_IMPLICIT_ARGS | KF_RCU_PROTECTED | KF_RET_NULL)
10716 BTF_ID_FLAGS(func, scx_bpf_dsq_reenq, KF_IMPLICIT_ARGS)
10717 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local___v2, KF_IMPLICIT_ARGS)
10718 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_IMPLICIT_ARGS | KF_ITER_NEW | KF_RCU_PROTECTED)
10719 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
10720 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
10721 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_IMPLICIT_ARGS)
10722 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_IMPLICIT_ARGS)
10723 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_IMPLICIT_ARGS)
10724 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS)
10725 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS)
10726 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
10727 BTF_ID_FLAGS(func, scx_bpf_cidperf_cap, KF_IMPLICIT_ARGS)
10728 BTF_ID_FLAGS(func, scx_bpf_cidperf_cur, KF_IMPLICIT_ARGS)
10729 BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS)
10730 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
10731 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
10732 BTF_ID_FLAGS(func, scx_bpf_nr_cids)
10733 BTF_ID_FLAGS(func, scx_bpf_nr_online_cids)
10734 BTF_ID_FLAGS(func, scx_bpf_this_cid)
10735 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
10736 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
10737 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
10738 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
10739 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
10740 BTF_ID_FLAGS(func, scx_bpf_task_cid, KF_RCU)
10741 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL)
10742 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
10743 BTF_ID_FLAGS(func, scx_bpf_cid_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
10744 BTF_ID_FLAGS(func, scx_bpf_tid_to_task, KF_RET_NULL | KF_RCU_PROTECTED)
10745 BTF_ID_FLAGS(func, scx_bpf_now)
10746 BTF_ID_FLAGS(func, scx_bpf_events, KF_IMPLICIT_ARGS)
10747 #ifdef CONFIG_CGROUP_SCHED
10748 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_IMPLICIT_ARGS | KF_RCU | KF_ACQUIRE)
10749 #endif
10750 BTF_ID_FLAGS(func, scx_bpf_sub_grant, KF_IMPLICIT_ARGS)
10751 BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS)
10752 BTF_ID_FLAGS(func, scx_bpf_sub_caps, KF_IMPLICIT_ARGS)
10753 BTF_ID_FLAGS(func, scx_bpf_sub_kill_bstr, KF_IMPLICIT_ARGS)
10754 BTF_KFUNCS_END(scx_kfunc_ids_any)
10755 
10756 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
10757 	.owner			= THIS_MODULE,
10758 	.set			= &scx_kfunc_ids_any,
10759 	.filter			= scx_kfunc_context_filter,
10760 };
10761 
10762 /*
10763  * cpu-form kfuncs that are forbidden from cid-form schedulers
10764  * (bpf_sched_ext_ops_cid). Programs targeting the cid struct_ops type must
10765  * use the cid-form alternative (cid/cmask kfuncs).
10766  *
10767  * Membership overlaps with scx_kfunc_ids_{any,idle,select_cpu}; the filter
10768  * tests this set independently and rejects matches before the per-op
10769  * allow-list check runs.
10770  *
10771  * pahole/resolve_btfids scans every BTF_ID_FLAGS() at build time and
10772  * intersects flags across duplicate entries, so each entry must carry the
10773  * same flags as the kfunc's primary declaration; otherwise the flags get
10774  * dropped globally.
10775  */
10776 BTF_KFUNCS_START(scx_kfunc_ids_cpu_only)
10777 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
10778 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
10779 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
10780 BTF_ID_FLAGS(func, scx_bpf_cpu_node, KF_IMPLICIT_ARGS)
10781 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS)
10782 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS)
10783 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
10784 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
10785 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
10786 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
10787 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU)
10788 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU)
10789 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU)
10790 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10791 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10792 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10793 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE)
10794 BTF_ID_FLAGS(func, scx_bpf_put_idle_cpumask, KF_RELEASE)
10795 BTF_ID_FLAGS(func, scx_bpf_test_and_clear_cpu_idle, KF_IMPLICIT_ARGS)
10796 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu, KF_IMPLICIT_ARGS | KF_RCU)
10797 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu_node, KF_IMPLICIT_ARGS | KF_RCU)
10798 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu, KF_IMPLICIT_ARGS | KF_RCU)
10799 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu_node, KF_IMPLICIT_ARGS | KF_RCU)
10800 BTF_KFUNCS_END(scx_kfunc_ids_cpu_only)
10801 
10802 /*
10803  * Per-op kfunc allow flags. Each bit corresponds to a context-sensitive kfunc
10804  * group; an op may permit zero or more groups, with the union expressed in
10805  * scx_kf_allow_flags[]. The verifier-time filter (scx_kfunc_context_filter())
10806  * consults this table to decide whether a context-sensitive kfunc is callable
10807  * from a given SCX op.
10808  */
10809 enum scx_kf_allow_flags {
10810 	SCX_KF_ALLOW_UNLOCKED		= 1 << 0,
10811 	SCX_KF_ALLOW_INIT_CIDS		= 1 << 1,
10812 	SCX_KF_ALLOW_CPU_RELEASE	= 1 << 2,
10813 	SCX_KF_ALLOW_DISPATCH		= 1 << 3,
10814 	SCX_KF_ALLOW_ENQUEUE		= 1 << 4,
10815 	SCX_KF_ALLOW_SELECT_CPU		= 1 << 5,
10816 };
10817 
10818 /*
10819  * Map each SCX op to the union of kfunc groups it permits, indexed by
10820  * SCX_OP_IDX(op). Ops not listed only permit kfuncs that are not
10821  * context-sensitive.
10822  */
10823 static const u32 scx_kf_allow_flags[] = {
10824 	[SCX_OP_IDX(select_cpu)]	= SCX_KF_ALLOW_SELECT_CPU | SCX_KF_ALLOW_ENQUEUE,
10825 	[SCX_OP_IDX(enqueue)]		= SCX_KF_ALLOW_SELECT_CPU | SCX_KF_ALLOW_ENQUEUE,
10826 	[SCX_OP_IDX(dispatch)]		= SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH,
10827 	[SCX_OP_IDX(cpu_release)]	= SCX_KF_ALLOW_CPU_RELEASE,
10828 	[SCX_OP_IDX(init_task)]		= SCX_KF_ALLOW_UNLOCKED,
10829 	[SCX_OP_IDX(dump)]		= SCX_KF_ALLOW_UNLOCKED,
10830 #ifdef CONFIG_EXT_GROUP_SCHED
10831 	[SCX_OP_IDX(cgroup_init)]	= SCX_KF_ALLOW_UNLOCKED,
10832 	[SCX_OP_IDX(cgroup_exit)]	= SCX_KF_ALLOW_UNLOCKED,
10833 	[SCX_OP_IDX(cgroup_prep_move)]	= SCX_KF_ALLOW_UNLOCKED,
10834 	[SCX_OP_IDX(cgroup_cancel_move)] = SCX_KF_ALLOW_UNLOCKED,
10835 	[SCX_OP_IDX(cgroup_set_weight)]	= SCX_KF_ALLOW_UNLOCKED,
10836 	[SCX_OP_IDX(cgroup_set_bandwidth)] = SCX_KF_ALLOW_UNLOCKED,
10837 	[SCX_OP_IDX(cgroup_set_idle)]	= SCX_KF_ALLOW_UNLOCKED,
10838 #endif	/* CONFIG_EXT_GROUP_SCHED */
10839 	[SCX_OP_IDX(sub_attach)]	= SCX_KF_ALLOW_UNLOCKED,
10840 	[SCX_OP_IDX(sub_detach)]	= SCX_KF_ALLOW_UNLOCKED,
10841 	[SCX_OP_IDX(sub_ecaps_updated)]	= SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH,
10842 	[SCX_OP_IDX(cpu_online)]	= SCX_KF_ALLOW_UNLOCKED,
10843 	[SCX_OP_IDX(cpu_offline)]	= SCX_KF_ALLOW_UNLOCKED,
10844 	[SCX_OP_IDX(init_cids)]		= SCX_KF_ALLOW_UNLOCKED | SCX_KF_ALLOW_INIT_CIDS,
10845 	[SCX_OP_IDX(init)]		= SCX_KF_ALLOW_UNLOCKED,
10846 	[SCX_OP_IDX(exit)]		= SCX_KF_ALLOW_UNLOCKED,
10847 };
10848 
10849 /*
10850  * Verifier-time filter for SCX kfuncs. Registered via the .filter field on
10851  * each per-group btf_kfunc_id_set. The BPF core invokes this for every kfunc
10852  * call in the registered hook (BPF_PROG_TYPE_STRUCT_OPS or
10853  * BPF_PROG_TYPE_SYSCALL), regardless of which set originally introduced the
10854  * kfunc - so the filter must short-circuit on kfuncs it doesn't govern by
10855  * falling through to "allow" when none of the SCX sets contain the kfunc.
10856  */
10857 int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id)
10858 {
10859 	bool in_unlocked = btf_id_set8_contains(&scx_kfunc_ids_unlocked, kfunc_id);
10860 	bool in_init_cids = btf_id_set8_contains(&scx_kfunc_ids_init_cids, kfunc_id);
10861 	bool in_select_cpu = btf_id_set8_contains(&scx_kfunc_ids_select_cpu, kfunc_id);
10862 	bool in_enqueue = btf_id_set8_contains(&scx_kfunc_ids_enqueue_dispatch, kfunc_id);
10863 	bool in_dispatch = btf_id_set8_contains(&scx_kfunc_ids_dispatch, kfunc_id);
10864 	bool in_cpu_release = btf_id_set8_contains(&scx_kfunc_ids_cpu_release, kfunc_id);
10865 	bool in_idle = btf_id_set8_contains(&scx_kfunc_ids_idle, kfunc_id);
10866 	bool in_any = btf_id_set8_contains(&scx_kfunc_ids_any, kfunc_id);
10867 	bool in_cpu_only = btf_id_set8_contains(&scx_kfunc_ids_cpu_only, kfunc_id);
10868 	bool in_cid = btf_id_set8_contains(&scx_kfunc_ids_cid, 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 || in_cid))
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 || in_cid) ? 0 : -EACCES;
10879 
10880 	if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
10881 		return (in_any || in_idle || in_cid) ? 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 || in_cid)
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