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