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