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