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