xref: /linux/kernel/sched/ext.c (revision 5aff3b319997eb8d0e25b8d2e3b5c88ed07395ac)
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/btf_ids.h>
10 #include "ext_idle.h"
11 
12 /*
13  * NOTE: sched_ext is in the process of growing multiple scheduler support and
14  * scx_root usage is in a transitional state. Naked dereferences are safe if the
15  * caller is one of the tasks attached to SCX and explicit RCU dereference is
16  * necessary otherwise. Naked scx_root dereferences trigger sparse warnings but
17  * are used as temporary markers to indicate that the dereferences need to be
18  * updated to point to the associated scheduler instances rather than scx_root.
19  */
20 static struct scx_sched __rcu *scx_root;
21 
22 /*
23  * During exit, a task may schedule after losing its PIDs. When disabling the
24  * BPF scheduler, we need to be able to iterate tasks in every state to
25  * guarantee system safety. Maintain a dedicated task list which contains every
26  * task between its fork and eventual free.
27  */
28 static DEFINE_SPINLOCK(scx_tasks_lock);
29 static LIST_HEAD(scx_tasks);
30 
31 /* ops enable/disable */
32 static DEFINE_MUTEX(scx_enable_mutex);
33 DEFINE_STATIC_KEY_FALSE(__scx_enabled);
34 DEFINE_STATIC_PERCPU_RWSEM(scx_fork_rwsem);
35 static atomic_t scx_enable_state_var = ATOMIC_INIT(SCX_DISABLED);
36 static unsigned long scx_in_softlockup;
37 static atomic_t scx_breather_depth = ATOMIC_INIT(0);
38 static int scx_bypass_depth;
39 static bool scx_init_task_enabled;
40 static bool scx_switching_all;
41 DEFINE_STATIC_KEY_FALSE(__scx_switched_all);
42 
43 static atomic_long_t scx_nr_rejected = ATOMIC_LONG_INIT(0);
44 static atomic_long_t scx_hotplug_seq = ATOMIC_LONG_INIT(0);
45 
46 /*
47  * A monotically increasing sequence number that is incremented every time a
48  * scheduler is enabled. This can be used by to check if any custom sched_ext
49  * scheduler has ever been used in the system.
50  */
51 static atomic_long_t scx_enable_seq = ATOMIC_LONG_INIT(0);
52 
53 /*
54  * The maximum amount of time in jiffies that a task may be runnable without
55  * being scheduled on a CPU. If this timeout is exceeded, it will trigger
56  * scx_error().
57  */
58 static unsigned long scx_watchdog_timeout;
59 
60 /*
61  * The last time the delayed work was run. This delayed work relies on
62  * ksoftirqd being able to run to service timer interrupts, so it's possible
63  * that this work itself could get wedged. To account for this, we check that
64  * it's not stalled in the timer tick, and trigger an error if it is.
65  */
66 static unsigned long scx_watchdog_timestamp = INITIAL_JIFFIES;
67 
68 static struct delayed_work scx_watchdog_work;
69 
70 /*
71  * For %SCX_KICK_WAIT: Each CPU has a pointer to an array of pick_task sequence
72  * numbers. The arrays are allocated with kvzalloc() as size can exceed percpu
73  * allocator limits on large machines. O(nr_cpu_ids^2) allocation, allocated
74  * lazily when enabling and freed when disabling to avoid waste when sched_ext
75  * isn't active.
76  */
77 struct scx_kick_pseqs {
78 	struct rcu_head		rcu;
79 	unsigned long		seqs[];
80 };
81 
82 static DEFINE_PER_CPU(struct scx_kick_pseqs __rcu *, scx_kick_pseqs);
83 
84 /*
85  * Direct dispatch marker.
86  *
87  * Non-NULL values are used for direct dispatch from enqueue path. A valid
88  * pointer points to the task currently being enqueued. An ERR_PTR value is used
89  * to indicate that direct dispatch has already happened.
90  */
91 static DEFINE_PER_CPU(struct task_struct *, direct_dispatch_task);
92 
93 static const struct rhashtable_params dsq_hash_params = {
94 	.key_len		= sizeof_field(struct scx_dispatch_q, id),
95 	.key_offset		= offsetof(struct scx_dispatch_q, id),
96 	.head_offset		= offsetof(struct scx_dispatch_q, hash_node),
97 };
98 
99 static LLIST_HEAD(dsqs_to_free);
100 
101 /* dispatch buf */
102 struct scx_dsp_buf_ent {
103 	struct task_struct	*task;
104 	unsigned long		qseq;
105 	u64			dsq_id;
106 	u64			enq_flags;
107 };
108 
109 static u32 scx_dsp_max_batch;
110 
111 struct scx_dsp_ctx {
112 	struct rq		*rq;
113 	u32			cursor;
114 	u32			nr_tasks;
115 	struct scx_dsp_buf_ent	buf[];
116 };
117 
118 static struct scx_dsp_ctx __percpu *scx_dsp_ctx;
119 
120 /* string formatting from BPF */
121 struct scx_bstr_buf {
122 	u64			data[MAX_BPRINTF_VARARGS];
123 	char			line[SCX_EXIT_MSG_LEN];
124 };
125 
126 static DEFINE_RAW_SPINLOCK(scx_exit_bstr_buf_lock);
127 static struct scx_bstr_buf scx_exit_bstr_buf;
128 
129 /* ops debug dump */
130 struct scx_dump_data {
131 	s32			cpu;
132 	bool			first;
133 	s32			cursor;
134 	struct seq_buf		*s;
135 	const char		*prefix;
136 	struct scx_bstr_buf	buf;
137 };
138 
139 static struct scx_dump_data scx_dump_data = {
140 	.cpu			= -1,
141 };
142 
143 /* /sys/kernel/sched_ext interface */
144 static struct kset *scx_kset;
145 
146 #define CREATE_TRACE_POINTS
147 #include <trace/events/sched_ext.h>
148 
149 static void process_ddsp_deferred_locals(struct rq *rq);
150 static void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags);
151 static void scx_vexit(struct scx_sched *sch, enum scx_exit_kind kind,
152 		      s64 exit_code, const char *fmt, va_list args);
153 
154 static __printf(4, 5) void scx_exit(struct scx_sched *sch,
155 				    enum scx_exit_kind kind, s64 exit_code,
156 				    const char *fmt, ...)
157 {
158 	va_list args;
159 
160 	va_start(args, fmt);
161 	scx_vexit(sch, kind, exit_code, fmt, args);
162 	va_end(args);
163 }
164 
165 #define scx_error(sch, fmt, args...)	scx_exit((sch), SCX_EXIT_ERROR, 0, fmt, ##args)
166 
167 #define SCX_HAS_OP(sch, op)	test_bit(SCX_OP_IDX(op), (sch)->has_op)
168 
169 static long jiffies_delta_msecs(unsigned long at, unsigned long now)
170 {
171 	if (time_after(at, now))
172 		return jiffies_to_msecs(at - now);
173 	else
174 		return -(long)jiffies_to_msecs(now - at);
175 }
176 
177 /* if the highest set bit is N, return a mask with bits [N+1, 31] set */
178 static u32 higher_bits(u32 flags)
179 {
180 	return ~((1 << fls(flags)) - 1);
181 }
182 
183 /* return the mask with only the highest bit set */
184 static u32 highest_bit(u32 flags)
185 {
186 	int bit = fls(flags);
187 	return ((u64)1 << bit) >> 1;
188 }
189 
190 static bool u32_before(u32 a, u32 b)
191 {
192 	return (s32)(a - b) < 0;
193 }
194 
195 static struct scx_dispatch_q *find_global_dsq(struct scx_sched *sch,
196 					      struct task_struct *p)
197 {
198 	return sch->global_dsqs[cpu_to_node(task_cpu(p))];
199 }
200 
201 static struct scx_dispatch_q *find_user_dsq(struct scx_sched *sch, u64 dsq_id)
202 {
203 	return rhashtable_lookup_fast(&sch->dsq_hash, &dsq_id, dsq_hash_params);
204 }
205 
206 /*
207  * scx_kf_mask enforcement. Some kfuncs can only be called from specific SCX
208  * ops. When invoking SCX ops, SCX_CALL_OP[_RET]() should be used to indicate
209  * the allowed kfuncs and those kfuncs should use scx_kf_allowed() to check
210  * whether it's running from an allowed context.
211  *
212  * @mask is constant, always inline to cull the mask calculations.
213  */
214 static __always_inline void scx_kf_allow(u32 mask)
215 {
216 	/* nesting is allowed only in increasing scx_kf_mask order */
217 	WARN_ONCE((mask | higher_bits(mask)) & current->scx.kf_mask,
218 		  "invalid nesting current->scx.kf_mask=0x%x mask=0x%x\n",
219 		  current->scx.kf_mask, mask);
220 	current->scx.kf_mask |= mask;
221 	barrier();
222 }
223 
224 static void scx_kf_disallow(u32 mask)
225 {
226 	barrier();
227 	current->scx.kf_mask &= ~mask;
228 }
229 
230 /*
231  * Track the rq currently locked.
232  *
233  * This allows kfuncs to safely operate on rq from any scx ops callback,
234  * knowing which rq is already locked.
235  */
236 DEFINE_PER_CPU(struct rq *, scx_locked_rq_state);
237 
238 static inline void update_locked_rq(struct rq *rq)
239 {
240 	/*
241 	 * Check whether @rq is actually locked. This can help expose bugs
242 	 * or incorrect assumptions about the context in which a kfunc or
243 	 * callback is executed.
244 	 */
245 	if (rq)
246 		lockdep_assert_rq_held(rq);
247 	__this_cpu_write(scx_locked_rq_state, rq);
248 }
249 
250 #define SCX_CALL_OP(sch, mask, op, rq, args...)					\
251 do {										\
252 	if (rq)									\
253 		update_locked_rq(rq);						\
254 	if (mask) {								\
255 		scx_kf_allow(mask);						\
256 		(sch)->ops.op(args);						\
257 		scx_kf_disallow(mask);						\
258 	} else {								\
259 		(sch)->ops.op(args);						\
260 	}									\
261 	if (rq)									\
262 		update_locked_rq(NULL);						\
263 } while (0)
264 
265 #define SCX_CALL_OP_RET(sch, mask, op, rq, args...)				\
266 ({										\
267 	__typeof__((sch)->ops.op(args)) __ret;					\
268 										\
269 	if (rq)									\
270 		update_locked_rq(rq);						\
271 	if (mask) {								\
272 		scx_kf_allow(mask);						\
273 		__ret = (sch)->ops.op(args);					\
274 		scx_kf_disallow(mask);						\
275 	} else {								\
276 		__ret = (sch)->ops.op(args);					\
277 	}									\
278 	if (rq)									\
279 		update_locked_rq(NULL);						\
280 	__ret;									\
281 })
282 
283 /*
284  * Some kfuncs are allowed only on the tasks that are subjects of the
285  * in-progress scx_ops operation for, e.g., locking guarantees. To enforce such
286  * restrictions, the following SCX_CALL_OP_*() variants should be used when
287  * invoking scx_ops operations that take task arguments. These can only be used
288  * for non-nesting operations due to the way the tasks are tracked.
289  *
290  * kfuncs which can only operate on such tasks can in turn use
291  * scx_kf_allowed_on_arg_tasks() to test whether the invocation is allowed on
292  * the specific task.
293  */
294 #define SCX_CALL_OP_TASK(sch, mask, op, rq, task, args...)			\
295 do {										\
296 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
297 	current->scx.kf_tasks[0] = task;					\
298 	SCX_CALL_OP((sch), mask, op, rq, task, ##args);				\
299 	current->scx.kf_tasks[0] = NULL;					\
300 } while (0)
301 
302 #define SCX_CALL_OP_TASK_RET(sch, mask, op, rq, task, args...)			\
303 ({										\
304 	__typeof__((sch)->ops.op(task, ##args)) __ret;				\
305 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
306 	current->scx.kf_tasks[0] = task;					\
307 	__ret = SCX_CALL_OP_RET((sch), mask, op, rq, task, ##args);		\
308 	current->scx.kf_tasks[0] = NULL;					\
309 	__ret;									\
310 })
311 
312 #define SCX_CALL_OP_2TASKS_RET(sch, mask, op, rq, task0, task1, args...)	\
313 ({										\
314 	__typeof__((sch)->ops.op(task0, task1, ##args)) __ret;			\
315 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
316 	current->scx.kf_tasks[0] = task0;					\
317 	current->scx.kf_tasks[1] = task1;					\
318 	__ret = SCX_CALL_OP_RET((sch), mask, op, rq, task0, task1, ##args);	\
319 	current->scx.kf_tasks[0] = NULL;					\
320 	current->scx.kf_tasks[1] = NULL;					\
321 	__ret;									\
322 })
323 
324 /* @mask is constant, always inline to cull unnecessary branches */
325 static __always_inline bool scx_kf_allowed(struct scx_sched *sch, u32 mask)
326 {
327 	if (unlikely(!(current->scx.kf_mask & mask))) {
328 		scx_error(sch, "kfunc with mask 0x%x called from an operation only allowing 0x%x",
329 			  mask, current->scx.kf_mask);
330 		return false;
331 	}
332 
333 	/*
334 	 * Enforce nesting boundaries. e.g. A kfunc which can be called from
335 	 * DISPATCH must not be called if we're running DEQUEUE which is nested
336 	 * inside ops.dispatch(). We don't need to check boundaries for any
337 	 * blocking kfuncs as the verifier ensures they're only called from
338 	 * sleepable progs.
339 	 */
340 	if (unlikely(highest_bit(mask) == SCX_KF_CPU_RELEASE &&
341 		     (current->scx.kf_mask & higher_bits(SCX_KF_CPU_RELEASE)))) {
342 		scx_error(sch, "cpu_release kfunc called from a nested operation");
343 		return false;
344 	}
345 
346 	if (unlikely(highest_bit(mask) == SCX_KF_DISPATCH &&
347 		     (current->scx.kf_mask & higher_bits(SCX_KF_DISPATCH)))) {
348 		scx_error(sch, "dispatch kfunc called from a nested operation");
349 		return false;
350 	}
351 
352 	return true;
353 }
354 
355 /* see SCX_CALL_OP_TASK() */
356 static __always_inline bool scx_kf_allowed_on_arg_tasks(struct scx_sched *sch,
357 							u32 mask,
358 							struct task_struct *p)
359 {
360 	if (!scx_kf_allowed(sch, mask))
361 		return false;
362 
363 	if (unlikely((p != current->scx.kf_tasks[0] &&
364 		      p != current->scx.kf_tasks[1]))) {
365 		scx_error(sch, "called on a task not being operated on");
366 		return false;
367 	}
368 
369 	return true;
370 }
371 
372 /**
373  * nldsq_next_task - Iterate to the next task in a non-local DSQ
374  * @dsq: user dsq being iterated
375  * @cur: current position, %NULL to start iteration
376  * @rev: walk backwards
377  *
378  * Returns %NULL when iteration is finished.
379  */
380 static struct task_struct *nldsq_next_task(struct scx_dispatch_q *dsq,
381 					   struct task_struct *cur, bool rev)
382 {
383 	struct list_head *list_node;
384 	struct scx_dsq_list_node *dsq_lnode;
385 
386 	lockdep_assert_held(&dsq->lock);
387 
388 	if (cur)
389 		list_node = &cur->scx.dsq_list.node;
390 	else
391 		list_node = &dsq->list;
392 
393 	/* find the next task, need to skip BPF iteration cursors */
394 	do {
395 		if (rev)
396 			list_node = list_node->prev;
397 		else
398 			list_node = list_node->next;
399 
400 		if (list_node == &dsq->list)
401 			return NULL;
402 
403 		dsq_lnode = container_of(list_node, struct scx_dsq_list_node,
404 					 node);
405 	} while (dsq_lnode->flags & SCX_DSQ_LNODE_ITER_CURSOR);
406 
407 	return container_of(dsq_lnode, struct task_struct, scx.dsq_list);
408 }
409 
410 #define nldsq_for_each_task(p, dsq)						\
411 	for ((p) = nldsq_next_task((dsq), NULL, false); (p);			\
412 	     (p) = nldsq_next_task((dsq), (p), false))
413 
414 
415 /*
416  * BPF DSQ iterator. Tasks in a non-local DSQ can be iterated in [reverse]
417  * dispatch order. BPF-visible iterator is opaque and larger to allow future
418  * changes without breaking backward compatibility. Can be used with
419  * bpf_for_each(). See bpf_iter_scx_dsq_*().
420  */
421 enum scx_dsq_iter_flags {
422 	/* iterate in the reverse dispatch order */
423 	SCX_DSQ_ITER_REV		= 1U << 16,
424 
425 	__SCX_DSQ_ITER_HAS_SLICE	= 1U << 30,
426 	__SCX_DSQ_ITER_HAS_VTIME	= 1U << 31,
427 
428 	__SCX_DSQ_ITER_USER_FLAGS	= SCX_DSQ_ITER_REV,
429 	__SCX_DSQ_ITER_ALL_FLAGS	= __SCX_DSQ_ITER_USER_FLAGS |
430 					  __SCX_DSQ_ITER_HAS_SLICE |
431 					  __SCX_DSQ_ITER_HAS_VTIME,
432 };
433 
434 struct bpf_iter_scx_dsq_kern {
435 	struct scx_dsq_list_node	cursor;
436 	struct scx_dispatch_q		*dsq;
437 	u64				slice;
438 	u64				vtime;
439 } __attribute__((aligned(8)));
440 
441 struct bpf_iter_scx_dsq {
442 	u64				__opaque[6];
443 } __attribute__((aligned(8)));
444 
445 
446 /*
447  * SCX task iterator.
448  */
449 struct scx_task_iter {
450 	struct sched_ext_entity		cursor;
451 	struct task_struct		*locked_task;
452 	struct rq			*rq;
453 	struct rq_flags			rf;
454 	u32				cnt;
455 	bool				list_locked;
456 };
457 
458 /**
459  * scx_task_iter_start - Lock scx_tasks_lock and start a task iteration
460  * @iter: iterator to init
461  *
462  * Initialize @iter and return with scx_tasks_lock held. Once initialized, @iter
463  * must eventually be stopped with scx_task_iter_stop().
464  *
465  * scx_tasks_lock and the rq lock may be released using scx_task_iter_unlock()
466  * between this and the first next() call or between any two next() calls. If
467  * the locks are released between two next() calls, the caller is responsible
468  * for ensuring that the task being iterated remains accessible either through
469  * RCU read lock or obtaining a reference count.
470  *
471  * All tasks which existed when the iteration started are guaranteed to be
472  * visited as long as they still exist.
473  */
474 static void scx_task_iter_start(struct scx_task_iter *iter)
475 {
476 	BUILD_BUG_ON(__SCX_DSQ_ITER_ALL_FLAGS &
477 		     ((1U << __SCX_DSQ_LNODE_PRIV_SHIFT) - 1));
478 
479 	spin_lock_irq(&scx_tasks_lock);
480 
481 	iter->cursor = (struct sched_ext_entity){ .flags = SCX_TASK_CURSOR };
482 	list_add(&iter->cursor.tasks_node, &scx_tasks);
483 	iter->locked_task = NULL;
484 	iter->cnt = 0;
485 	iter->list_locked = true;
486 }
487 
488 static void __scx_task_iter_rq_unlock(struct scx_task_iter *iter)
489 {
490 	if (iter->locked_task) {
491 		task_rq_unlock(iter->rq, iter->locked_task, &iter->rf);
492 		iter->locked_task = NULL;
493 	}
494 }
495 
496 /**
497  * scx_task_iter_unlock - Unlock rq and scx_tasks_lock held by a task iterator
498  * @iter: iterator to unlock
499  *
500  * If @iter is in the middle of a locked iteration, it may be locking the rq of
501  * the task currently being visited in addition to scx_tasks_lock. Unlock both.
502  * This function can be safely called anytime during an iteration. The next
503  * iterator operation will automatically restore the necessary locking.
504  */
505 static void scx_task_iter_unlock(struct scx_task_iter *iter)
506 {
507 	__scx_task_iter_rq_unlock(iter);
508 	if (iter->list_locked) {
509 		iter->list_locked = false;
510 		spin_unlock_irq(&scx_tasks_lock);
511 	}
512 }
513 
514 static void __scx_task_iter_maybe_relock(struct scx_task_iter *iter)
515 {
516 	if (!iter->list_locked) {
517 		spin_lock_irq(&scx_tasks_lock);
518 		iter->list_locked = true;
519 	}
520 }
521 
522 /**
523  * scx_task_iter_stop - Stop a task iteration and unlock scx_tasks_lock
524  * @iter: iterator to exit
525  *
526  * Exit a previously initialized @iter. Must be called with scx_tasks_lock held
527  * which is released on return. If the iterator holds a task's rq lock, that rq
528  * lock is also released. See scx_task_iter_start() for details.
529  */
530 static void scx_task_iter_stop(struct scx_task_iter *iter)
531 {
532 	__scx_task_iter_maybe_relock(iter);
533 	list_del_init(&iter->cursor.tasks_node);
534 	scx_task_iter_unlock(iter);
535 }
536 
537 /**
538  * scx_task_iter_next - Next task
539  * @iter: iterator to walk
540  *
541  * Visit the next task. See scx_task_iter_start() for details. Locks are dropped
542  * and re-acquired every %SCX_TASK_ITER_BATCH iterations to avoid causing stalls
543  * by holding scx_tasks_lock for too long.
544  */
545 static struct task_struct *scx_task_iter_next(struct scx_task_iter *iter)
546 {
547 	struct list_head *cursor = &iter->cursor.tasks_node;
548 	struct sched_ext_entity *pos;
549 
550 	__scx_task_iter_maybe_relock(iter);
551 
552 	if (!(++iter->cnt % SCX_TASK_ITER_BATCH)) {
553 		scx_task_iter_unlock(iter);
554 		cond_resched();
555 		__scx_task_iter_maybe_relock(iter);
556 	}
557 
558 	list_for_each_entry(pos, cursor, tasks_node) {
559 		if (&pos->tasks_node == &scx_tasks)
560 			return NULL;
561 		if (!(pos->flags & SCX_TASK_CURSOR)) {
562 			list_move(cursor, &pos->tasks_node);
563 			return container_of(pos, struct task_struct, scx);
564 		}
565 	}
566 
567 	/* can't happen, should always terminate at scx_tasks above */
568 	BUG();
569 }
570 
571 /**
572  * scx_task_iter_next_locked - Next non-idle task with its rq locked
573  * @iter: iterator to walk
574  *
575  * Visit the non-idle task with its rq lock held. Allows callers to specify
576  * whether they would like to filter out dead tasks. See scx_task_iter_start()
577  * for details.
578  */
579 static struct task_struct *scx_task_iter_next_locked(struct scx_task_iter *iter)
580 {
581 	struct task_struct *p;
582 
583 	__scx_task_iter_rq_unlock(iter);
584 
585 	while ((p = scx_task_iter_next(iter))) {
586 		/*
587 		 * scx_task_iter is used to prepare and move tasks into SCX
588 		 * while loading the BPF scheduler and vice-versa while
589 		 * unloading. The init_tasks ("swappers") should be excluded
590 		 * from the iteration because:
591 		 *
592 		 * - It's unsafe to use __setschduler_prio() on an init_task to
593 		 *   determine the sched_class to use as it won't preserve its
594 		 *   idle_sched_class.
595 		 *
596 		 * - ops.init/exit_task() can easily be confused if called with
597 		 *   init_tasks as they, e.g., share PID 0.
598 		 *
599 		 * As init_tasks are never scheduled through SCX, they can be
600 		 * skipped safely. Note that is_idle_task() which tests %PF_IDLE
601 		 * doesn't work here:
602 		 *
603 		 * - %PF_IDLE may not be set for an init_task whose CPU hasn't
604 		 *   yet been onlined.
605 		 *
606 		 * - %PF_IDLE can be set on tasks that are not init_tasks. See
607 		 *   play_idle_precise() used by CONFIG_IDLE_INJECT.
608 		 *
609 		 * Test for idle_sched_class as only init_tasks are on it.
610 		 */
611 		if (p->sched_class != &idle_sched_class)
612 			break;
613 	}
614 	if (!p)
615 		return NULL;
616 
617 	iter->rq = task_rq_lock(p, &iter->rf);
618 	iter->locked_task = p;
619 
620 	return p;
621 }
622 
623 /**
624  * scx_add_event - Increase an event counter for 'name' by 'cnt'
625  * @sch: scx_sched to account events for
626  * @name: an event name defined in struct scx_event_stats
627  * @cnt: the number of the event occurred
628  *
629  * This can be used when preemption is not disabled.
630  */
631 #define scx_add_event(sch, name, cnt) do {					\
632 	this_cpu_add((sch)->pcpu->event_stats.name, (cnt));			\
633 	trace_sched_ext_event(#name, (cnt));					\
634 } while(0)
635 
636 /**
637  * __scx_add_event - Increase an event counter for 'name' by 'cnt'
638  * @sch: scx_sched to account events for
639  * @name: an event name defined in struct scx_event_stats
640  * @cnt: the number of the event occurred
641  *
642  * This should be used only when preemption is disabled.
643  */
644 #define __scx_add_event(sch, name, cnt) do {					\
645 	__this_cpu_add((sch)->pcpu->event_stats.name, (cnt));			\
646 	trace_sched_ext_event(#name, cnt);					\
647 } while(0)
648 
649 /**
650  * scx_agg_event - Aggregate an event counter 'kind' from 'src_e' to 'dst_e'
651  * @dst_e: destination event stats
652  * @src_e: source event stats
653  * @kind: a kind of event to be aggregated
654  */
655 #define scx_agg_event(dst_e, src_e, kind) do {					\
656 	(dst_e)->kind += READ_ONCE((src_e)->kind);				\
657 } while(0)
658 
659 /**
660  * scx_dump_event - Dump an event 'kind' in 'events' to 's'
661  * @s: output seq_buf
662  * @events: event stats
663  * @kind: a kind of event to dump
664  */
665 #define scx_dump_event(s, events, kind) do {					\
666 	dump_line(&(s), "%40s: %16lld", #kind, (events)->kind);			\
667 } while (0)
668 
669 
670 static void scx_read_events(struct scx_sched *sch,
671 			    struct scx_event_stats *events);
672 
673 static enum scx_enable_state scx_enable_state(void)
674 {
675 	return atomic_read(&scx_enable_state_var);
676 }
677 
678 static enum scx_enable_state scx_set_enable_state(enum scx_enable_state to)
679 {
680 	return atomic_xchg(&scx_enable_state_var, to);
681 }
682 
683 static bool scx_tryset_enable_state(enum scx_enable_state to,
684 				    enum scx_enable_state from)
685 {
686 	int from_v = from;
687 
688 	return atomic_try_cmpxchg(&scx_enable_state_var, &from_v, to);
689 }
690 
691 /**
692  * wait_ops_state - Busy-wait the specified ops state to end
693  * @p: target task
694  * @opss: state to wait the end of
695  *
696  * Busy-wait for @p to transition out of @opss. This can only be used when the
697  * state part of @opss is %SCX_QUEUEING or %SCX_DISPATCHING. This function also
698  * has load_acquire semantics to ensure that the caller can see the updates made
699  * in the enqueueing and dispatching paths.
700  */
701 static void wait_ops_state(struct task_struct *p, unsigned long opss)
702 {
703 	do {
704 		cpu_relax();
705 	} while (atomic_long_read_acquire(&p->scx.ops_state) == opss);
706 }
707 
708 static inline bool __cpu_valid(s32 cpu)
709 {
710 	return likely(cpu >= 0 && cpu < nr_cpu_ids && cpu_possible(cpu));
711 }
712 
713 /**
714  * ops_cpu_valid - Verify a cpu number, to be used on ops input args
715  * @sch: scx_sched to abort on error
716  * @cpu: cpu number which came from a BPF ops
717  * @where: extra information reported on error
718  *
719  * @cpu is a cpu number which came from the BPF scheduler and can be any value.
720  * Verify that it is in range and one of the possible cpus. If invalid, trigger
721  * an ops error.
722  */
723 static bool ops_cpu_valid(struct scx_sched *sch, s32 cpu, const char *where)
724 {
725 	if (__cpu_valid(cpu)) {
726 		return true;
727 	} else {
728 		scx_error(sch, "invalid CPU %d%s%s", cpu, where ? " " : "", where ?: "");
729 		return false;
730 	}
731 }
732 
733 /**
734  * ops_sanitize_err - Sanitize a -errno value
735  * @sch: scx_sched to error out on error
736  * @ops_name: operation to blame on failure
737  * @err: -errno value to sanitize
738  *
739  * Verify @err is a valid -errno. If not, trigger scx_error() and return
740  * -%EPROTO. This is necessary because returning a rogue -errno up the chain can
741  * cause misbehaviors. For an example, a large negative return from
742  * ops.init_task() triggers an oops when passed up the call chain because the
743  * value fails IS_ERR() test after being encoded with ERR_PTR() and then is
744  * handled as a pointer.
745  */
746 static int ops_sanitize_err(struct scx_sched *sch, const char *ops_name, s32 err)
747 {
748 	if (err < 0 && err >= -MAX_ERRNO)
749 		return err;
750 
751 	scx_error(sch, "ops.%s() returned an invalid errno %d", ops_name, err);
752 	return -EPROTO;
753 }
754 
755 static void run_deferred(struct rq *rq)
756 {
757 	process_ddsp_deferred_locals(rq);
758 }
759 
760 static void deferred_bal_cb_workfn(struct rq *rq)
761 {
762 	run_deferred(rq);
763 }
764 
765 static void deferred_irq_workfn(struct irq_work *irq_work)
766 {
767 	struct rq *rq = container_of(irq_work, struct rq, scx.deferred_irq_work);
768 
769 	raw_spin_rq_lock(rq);
770 	run_deferred(rq);
771 	raw_spin_rq_unlock(rq);
772 }
773 
774 /**
775  * schedule_deferred - Schedule execution of deferred actions on an rq
776  * @rq: target rq
777  *
778  * Schedule execution of deferred actions on @rq. Must be called with @rq
779  * locked. Deferred actions are executed with @rq locked but unpinned, and thus
780  * can unlock @rq to e.g. migrate tasks to other rqs.
781  */
782 static void schedule_deferred(struct rq *rq)
783 {
784 	lockdep_assert_rq_held(rq);
785 
786 	/*
787 	 * If in the middle of waking up a task, task_woken_scx() will be called
788 	 * afterwards which will then run the deferred actions, no need to
789 	 * schedule anything.
790 	 */
791 	if (rq->scx.flags & SCX_RQ_IN_WAKEUP)
792 		return;
793 
794 	/* Don't do anything if there already is a deferred operation. */
795 	if (rq->scx.flags & SCX_RQ_BAL_PENDING)
796 		return;
797 
798 	/*
799 	 * If in balance, the balance callbacks will be called before rq lock is
800 	 * released. Schedule one.
801 	 *
802 	 *
803 	 * We can't directly insert the callback into the
804 	 * rq's list: The call can drop its lock and make the pending balance
805 	 * callback visible to unrelated code paths that call rq_pin_lock().
806 	 *
807 	 * Just let balance_one() know that it must do it itself.
808 	 */
809 	if (rq->scx.flags & SCX_RQ_IN_BALANCE) {
810 		rq->scx.flags |= SCX_RQ_BAL_CB_PENDING;
811 		return;
812 	}
813 
814 	/*
815 	 * No scheduler hooks available. Queue an irq work. They are executed on
816 	 * IRQ re-enable which may take a bit longer than the scheduler hooks.
817 	 * The above WAKEUP and BALANCE paths should cover most of the cases and
818 	 * the time to IRQ re-enable shouldn't be long.
819 	 */
820 	irq_work_queue(&rq->scx.deferred_irq_work);
821 }
822 
823 /**
824  * touch_core_sched - Update timestamp used for core-sched task ordering
825  * @rq: rq to read clock from, must be locked
826  * @p: task to update the timestamp for
827  *
828  * Update @p->scx.core_sched_at timestamp. This is used by scx_prio_less() to
829  * implement global or local-DSQ FIFO ordering for core-sched. Should be called
830  * when a task becomes runnable and its turn on the CPU ends (e.g. slice
831  * exhaustion).
832  */
833 static void touch_core_sched(struct rq *rq, struct task_struct *p)
834 {
835 	lockdep_assert_rq_held(rq);
836 
837 #ifdef CONFIG_SCHED_CORE
838 	/*
839 	 * It's okay to update the timestamp spuriously. Use
840 	 * sched_core_disabled() which is cheaper than enabled().
841 	 *
842 	 * As this is used to determine ordering between tasks of sibling CPUs,
843 	 * it may be better to use per-core dispatch sequence instead.
844 	 */
845 	if (!sched_core_disabled())
846 		p->scx.core_sched_at = sched_clock_cpu(cpu_of(rq));
847 #endif
848 }
849 
850 /**
851  * touch_core_sched_dispatch - Update core-sched timestamp on dispatch
852  * @rq: rq to read clock from, must be locked
853  * @p: task being dispatched
854  *
855  * If the BPF scheduler implements custom core-sched ordering via
856  * ops.core_sched_before(), @p->scx.core_sched_at is used to implement FIFO
857  * ordering within each local DSQ. This function is called from dispatch paths
858  * and updates @p->scx.core_sched_at if custom core-sched ordering is in effect.
859  */
860 static void touch_core_sched_dispatch(struct rq *rq, struct task_struct *p)
861 {
862 	lockdep_assert_rq_held(rq);
863 
864 #ifdef CONFIG_SCHED_CORE
865 	if (unlikely(SCX_HAS_OP(scx_root, core_sched_before)))
866 		touch_core_sched(rq, p);
867 #endif
868 }
869 
870 static void update_curr_scx(struct rq *rq)
871 {
872 	struct task_struct *curr = rq->curr;
873 	s64 delta_exec;
874 
875 	delta_exec = update_curr_common(rq);
876 	if (unlikely(delta_exec <= 0))
877 		return;
878 
879 	if (curr->scx.slice != SCX_SLICE_INF) {
880 		curr->scx.slice -= min_t(u64, curr->scx.slice, delta_exec);
881 		if (!curr->scx.slice)
882 			touch_core_sched(rq, curr);
883 	}
884 }
885 
886 static bool scx_dsq_priq_less(struct rb_node *node_a,
887 			      const struct rb_node *node_b)
888 {
889 	const struct task_struct *a =
890 		container_of(node_a, struct task_struct, scx.dsq_priq);
891 	const struct task_struct *b =
892 		container_of(node_b, struct task_struct, scx.dsq_priq);
893 
894 	return time_before64(a->scx.dsq_vtime, b->scx.dsq_vtime);
895 }
896 
897 static void dsq_mod_nr(struct scx_dispatch_q *dsq, s32 delta)
898 {
899 	/* scx_bpf_dsq_nr_queued() reads ->nr without locking, use WRITE_ONCE() */
900 	WRITE_ONCE(dsq->nr, dsq->nr + delta);
901 }
902 
903 static void refill_task_slice_dfl(struct scx_sched *sch, struct task_struct *p)
904 {
905 	p->scx.slice = SCX_SLICE_DFL;
906 	__scx_add_event(sch, SCX_EV_REFILL_SLICE_DFL, 1);
907 }
908 
909 static void dispatch_enqueue(struct scx_sched *sch, struct scx_dispatch_q *dsq,
910 			     struct task_struct *p, u64 enq_flags)
911 {
912 	bool is_local = dsq->id == SCX_DSQ_LOCAL;
913 
914 	WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node));
915 	WARN_ON_ONCE((p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) ||
916 		     !RB_EMPTY_NODE(&p->scx.dsq_priq));
917 
918 	if (!is_local) {
919 		raw_spin_lock(&dsq->lock);
920 		if (unlikely(dsq->id == SCX_DSQ_INVALID)) {
921 			scx_error(sch, "attempting to dispatch to a destroyed dsq");
922 			/* fall back to the global dsq */
923 			raw_spin_unlock(&dsq->lock);
924 			dsq = find_global_dsq(sch, p);
925 			raw_spin_lock(&dsq->lock);
926 		}
927 	}
928 
929 	if (unlikely((dsq->id & SCX_DSQ_FLAG_BUILTIN) &&
930 		     (enq_flags & SCX_ENQ_DSQ_PRIQ))) {
931 		/*
932 		 * SCX_DSQ_LOCAL and SCX_DSQ_GLOBAL DSQs always consume from
933 		 * their FIFO queues. To avoid confusion and accidentally
934 		 * starving vtime-dispatched tasks by FIFO-dispatched tasks, we
935 		 * disallow any internal DSQ from doing vtime ordering of
936 		 * tasks.
937 		 */
938 		scx_error(sch, "cannot use vtime ordering for built-in DSQs");
939 		enq_flags &= ~SCX_ENQ_DSQ_PRIQ;
940 	}
941 
942 	if (enq_flags & SCX_ENQ_DSQ_PRIQ) {
943 		struct rb_node *rbp;
944 
945 		/*
946 		 * A PRIQ DSQ shouldn't be using FIFO enqueueing. As tasks are
947 		 * linked to both the rbtree and list on PRIQs, this can only be
948 		 * tested easily when adding the first task.
949 		 */
950 		if (unlikely(RB_EMPTY_ROOT(&dsq->priq) &&
951 			     nldsq_next_task(dsq, NULL, false)))
952 			scx_error(sch, "DSQ ID 0x%016llx already had FIFO-enqueued tasks",
953 				  dsq->id);
954 
955 		p->scx.dsq_flags |= SCX_TASK_DSQ_ON_PRIQ;
956 		rb_add(&p->scx.dsq_priq, &dsq->priq, scx_dsq_priq_less);
957 
958 		/*
959 		 * Find the previous task and insert after it on the list so
960 		 * that @dsq->list is vtime ordered.
961 		 */
962 		rbp = rb_prev(&p->scx.dsq_priq);
963 		if (rbp) {
964 			struct task_struct *prev =
965 				container_of(rbp, struct task_struct,
966 					     scx.dsq_priq);
967 			list_add(&p->scx.dsq_list.node, &prev->scx.dsq_list.node);
968 			/* first task unchanged - no update needed */
969 		} else {
970 			list_add(&p->scx.dsq_list.node, &dsq->list);
971 			/* not builtin and new task is at head - use fastpath */
972 			rcu_assign_pointer(dsq->first_task, p);
973 		}
974 	} else {
975 		/* a FIFO DSQ shouldn't be using PRIQ enqueuing */
976 		if (unlikely(!RB_EMPTY_ROOT(&dsq->priq)))
977 			scx_error(sch, "DSQ ID 0x%016llx already had PRIQ-enqueued tasks",
978 				  dsq->id);
979 
980 		if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT)) {
981 			list_add(&p->scx.dsq_list.node, &dsq->list);
982 			/* new task inserted at head - use fastpath */
983 			if (!(dsq->id & SCX_DSQ_FLAG_BUILTIN))
984 				rcu_assign_pointer(dsq->first_task, p);
985 		} else {
986 			bool was_empty;
987 
988 			was_empty = list_empty(&dsq->list);
989 			list_add_tail(&p->scx.dsq_list.node, &dsq->list);
990 			if (was_empty && !(dsq->id & SCX_DSQ_FLAG_BUILTIN))
991 				rcu_assign_pointer(dsq->first_task, p);
992 		}
993 	}
994 
995 	/* seq records the order tasks are queued, used by BPF DSQ iterator */
996 	dsq->seq++;
997 	p->scx.dsq_seq = dsq->seq;
998 
999 	dsq_mod_nr(dsq, 1);
1000 	p->scx.dsq = dsq;
1001 
1002 	/*
1003 	 * scx.ddsp_dsq_id and scx.ddsp_enq_flags are only relevant on the
1004 	 * direct dispatch path, but we clear them here because the direct
1005 	 * dispatch verdict may be overridden on the enqueue path during e.g.
1006 	 * bypass.
1007 	 */
1008 	p->scx.ddsp_dsq_id = SCX_DSQ_INVALID;
1009 	p->scx.ddsp_enq_flags = 0;
1010 
1011 	/*
1012 	 * We're transitioning out of QUEUEING or DISPATCHING. store_release to
1013 	 * match waiters' load_acquire.
1014 	 */
1015 	if (enq_flags & SCX_ENQ_CLEAR_OPSS)
1016 		atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1017 
1018 	if (is_local) {
1019 		struct rq *rq = container_of(dsq, struct rq, scx.local_dsq);
1020 		bool preempt = false;
1021 
1022 		if ((enq_flags & SCX_ENQ_PREEMPT) && p != rq->curr &&
1023 		    rq->curr->sched_class == &ext_sched_class) {
1024 			rq->curr->scx.slice = 0;
1025 			preempt = true;
1026 		}
1027 
1028 		if (preempt || sched_class_above(&ext_sched_class,
1029 						 rq->curr->sched_class))
1030 			resched_curr(rq);
1031 	} else {
1032 		raw_spin_unlock(&dsq->lock);
1033 	}
1034 }
1035 
1036 static void task_unlink_from_dsq(struct task_struct *p,
1037 				 struct scx_dispatch_q *dsq)
1038 {
1039 	WARN_ON_ONCE(list_empty(&p->scx.dsq_list.node));
1040 
1041 	if (p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) {
1042 		rb_erase(&p->scx.dsq_priq, &dsq->priq);
1043 		RB_CLEAR_NODE(&p->scx.dsq_priq);
1044 		p->scx.dsq_flags &= ~SCX_TASK_DSQ_ON_PRIQ;
1045 	}
1046 
1047 	if (!(dsq->id & SCX_DSQ_FLAG_BUILTIN) && dsq->first_task == p) {
1048 		struct task_struct *first_task;
1049 
1050 		first_task = nldsq_next_task(dsq, NULL, false);
1051 		rcu_assign_pointer(dsq->first_task, first_task);
1052 	}
1053 
1054 	list_del_init(&p->scx.dsq_list.node);
1055 	dsq_mod_nr(dsq, -1);
1056 }
1057 
1058 static void dispatch_dequeue(struct rq *rq, struct task_struct *p)
1059 {
1060 	struct scx_dispatch_q *dsq = p->scx.dsq;
1061 	bool is_local = dsq == &rq->scx.local_dsq;
1062 
1063 	if (!dsq) {
1064 		/*
1065 		 * If !dsq && on-list, @p is on @rq's ddsp_deferred_locals.
1066 		 * Unlinking is all that's needed to cancel.
1067 		 */
1068 		if (unlikely(!list_empty(&p->scx.dsq_list.node)))
1069 			list_del_init(&p->scx.dsq_list.node);
1070 
1071 		/*
1072 		 * When dispatching directly from the BPF scheduler to a local
1073 		 * DSQ, the task isn't associated with any DSQ but
1074 		 * @p->scx.holding_cpu may be set under the protection of
1075 		 * %SCX_OPSS_DISPATCHING.
1076 		 */
1077 		if (p->scx.holding_cpu >= 0)
1078 			p->scx.holding_cpu = -1;
1079 
1080 		return;
1081 	}
1082 
1083 	if (!is_local)
1084 		raw_spin_lock(&dsq->lock);
1085 
1086 	/*
1087 	 * Now that we hold @dsq->lock, @p->holding_cpu and @p->scx.dsq_* can't
1088 	 * change underneath us.
1089 	*/
1090 	if (p->scx.holding_cpu < 0) {
1091 		/* @p must still be on @dsq, dequeue */
1092 		task_unlink_from_dsq(p, dsq);
1093 	} else {
1094 		/*
1095 		 * We're racing against dispatch_to_local_dsq() which already
1096 		 * removed @p from @dsq and set @p->scx.holding_cpu. Clear the
1097 		 * holding_cpu which tells dispatch_to_local_dsq() that it lost
1098 		 * the race.
1099 		 */
1100 		WARN_ON_ONCE(!list_empty(&p->scx.dsq_list.node));
1101 		p->scx.holding_cpu = -1;
1102 	}
1103 	p->scx.dsq = NULL;
1104 
1105 	if (!is_local)
1106 		raw_spin_unlock(&dsq->lock);
1107 }
1108 
1109 static struct scx_dispatch_q *find_dsq_for_dispatch(struct scx_sched *sch,
1110 						    struct rq *rq, u64 dsq_id,
1111 						    struct task_struct *p)
1112 {
1113 	struct scx_dispatch_q *dsq;
1114 
1115 	if (dsq_id == SCX_DSQ_LOCAL)
1116 		return &rq->scx.local_dsq;
1117 
1118 	if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
1119 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
1120 
1121 		if (!ops_cpu_valid(sch, cpu, "in SCX_DSQ_LOCAL_ON dispatch verdict"))
1122 			return find_global_dsq(sch, p);
1123 
1124 		return &cpu_rq(cpu)->scx.local_dsq;
1125 	}
1126 
1127 	if (dsq_id == SCX_DSQ_GLOBAL)
1128 		dsq = find_global_dsq(sch, p);
1129 	else
1130 		dsq = find_user_dsq(sch, dsq_id);
1131 
1132 	if (unlikely(!dsq)) {
1133 		scx_error(sch, "non-existent DSQ 0x%llx for %s[%d]",
1134 			  dsq_id, p->comm, p->pid);
1135 		return find_global_dsq(sch, p);
1136 	}
1137 
1138 	return dsq;
1139 }
1140 
1141 static void mark_direct_dispatch(struct scx_sched *sch,
1142 				 struct task_struct *ddsp_task,
1143 				 struct task_struct *p, u64 dsq_id,
1144 				 u64 enq_flags)
1145 {
1146 	/*
1147 	 * Mark that dispatch already happened from ops.select_cpu() or
1148 	 * ops.enqueue() by spoiling direct_dispatch_task with a non-NULL value
1149 	 * which can never match a valid task pointer.
1150 	 */
1151 	__this_cpu_write(direct_dispatch_task, ERR_PTR(-ESRCH));
1152 
1153 	/* @p must match the task on the enqueue path */
1154 	if (unlikely(p != ddsp_task)) {
1155 		if (IS_ERR(ddsp_task))
1156 			scx_error(sch, "%s[%d] already direct-dispatched",
1157 				  p->comm, p->pid);
1158 		else
1159 			scx_error(sch, "scheduling for %s[%d] but trying to direct-dispatch %s[%d]",
1160 				  ddsp_task->comm, ddsp_task->pid,
1161 				  p->comm, p->pid);
1162 		return;
1163 	}
1164 
1165 	WARN_ON_ONCE(p->scx.ddsp_dsq_id != SCX_DSQ_INVALID);
1166 	WARN_ON_ONCE(p->scx.ddsp_enq_flags);
1167 
1168 	p->scx.ddsp_dsq_id = dsq_id;
1169 	p->scx.ddsp_enq_flags = enq_flags;
1170 }
1171 
1172 static void direct_dispatch(struct scx_sched *sch, struct task_struct *p,
1173 			    u64 enq_flags)
1174 {
1175 	struct rq *rq = task_rq(p);
1176 	struct scx_dispatch_q *dsq =
1177 		find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, p);
1178 
1179 	touch_core_sched_dispatch(rq, p);
1180 
1181 	p->scx.ddsp_enq_flags |= enq_flags;
1182 
1183 	/*
1184 	 * We are in the enqueue path with @rq locked and pinned, and thus can't
1185 	 * double lock a remote rq and enqueue to its local DSQ. For
1186 	 * DSQ_LOCAL_ON verdicts targeting the local DSQ of a remote CPU, defer
1187 	 * the enqueue so that it's executed when @rq can be unlocked.
1188 	 */
1189 	if (dsq->id == SCX_DSQ_LOCAL && dsq != &rq->scx.local_dsq) {
1190 		unsigned long opss;
1191 
1192 		opss = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_STATE_MASK;
1193 
1194 		switch (opss & SCX_OPSS_STATE_MASK) {
1195 		case SCX_OPSS_NONE:
1196 			break;
1197 		case SCX_OPSS_QUEUEING:
1198 			/*
1199 			 * As @p was never passed to the BPF side, _release is
1200 			 * not strictly necessary. Still do it for consistency.
1201 			 */
1202 			atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1203 			break;
1204 		default:
1205 			WARN_ONCE(true, "sched_ext: %s[%d] has invalid ops state 0x%lx in direct_dispatch()",
1206 				  p->comm, p->pid, opss);
1207 			atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1208 			break;
1209 		}
1210 
1211 		WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node));
1212 		list_add_tail(&p->scx.dsq_list.node,
1213 			      &rq->scx.ddsp_deferred_locals);
1214 		schedule_deferred(rq);
1215 		return;
1216 	}
1217 
1218 	dispatch_enqueue(sch, dsq, p,
1219 			 p->scx.ddsp_enq_flags | SCX_ENQ_CLEAR_OPSS);
1220 }
1221 
1222 static bool scx_rq_online(struct rq *rq)
1223 {
1224 	/*
1225 	 * Test both cpu_active() and %SCX_RQ_ONLINE. %SCX_RQ_ONLINE indicates
1226 	 * the online state as seen from the BPF scheduler. cpu_active() test
1227 	 * guarantees that, if this function returns %true, %SCX_RQ_ONLINE will
1228 	 * stay set until the current scheduling operation is complete even if
1229 	 * we aren't locking @rq.
1230 	 */
1231 	return likely((rq->scx.flags & SCX_RQ_ONLINE) && cpu_active(cpu_of(rq)));
1232 }
1233 
1234 static void do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags,
1235 			    int sticky_cpu)
1236 {
1237 	struct scx_sched *sch = scx_root;
1238 	struct task_struct **ddsp_taskp;
1239 	unsigned long qseq;
1240 
1241 	WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_QUEUED));
1242 
1243 	/* rq migration */
1244 	if (sticky_cpu == cpu_of(rq))
1245 		goto local_norefill;
1246 
1247 	/*
1248 	 * If !scx_rq_online(), we already told the BPF scheduler that the CPU
1249 	 * is offline and are just running the hotplug path. Don't bother the
1250 	 * BPF scheduler.
1251 	 */
1252 	if (!scx_rq_online(rq))
1253 		goto local;
1254 
1255 	if (scx_rq_bypassing(rq)) {
1256 		__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
1257 		goto global;
1258 	}
1259 
1260 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
1261 		goto direct;
1262 
1263 	/* see %SCX_OPS_ENQ_EXITING */
1264 	if (!(sch->ops.flags & SCX_OPS_ENQ_EXITING) &&
1265 	    unlikely(p->flags & PF_EXITING)) {
1266 		__scx_add_event(sch, SCX_EV_ENQ_SKIP_EXITING, 1);
1267 		goto local;
1268 	}
1269 
1270 	/* see %SCX_OPS_ENQ_MIGRATION_DISABLED */
1271 	if (!(sch->ops.flags & SCX_OPS_ENQ_MIGRATION_DISABLED) &&
1272 	    is_migration_disabled(p)) {
1273 		__scx_add_event(sch, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED, 1);
1274 		goto local;
1275 	}
1276 
1277 	if (unlikely(!SCX_HAS_OP(sch, enqueue)))
1278 		goto global;
1279 
1280 	/* DSQ bypass didn't trigger, enqueue on the BPF scheduler */
1281 	qseq = rq->scx.ops_qseq++ << SCX_OPSS_QSEQ_SHIFT;
1282 
1283 	WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
1284 	atomic_long_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq);
1285 
1286 	ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
1287 	WARN_ON_ONCE(*ddsp_taskp);
1288 	*ddsp_taskp = p;
1289 
1290 	SCX_CALL_OP_TASK(sch, SCX_KF_ENQUEUE, enqueue, rq, p, enq_flags);
1291 
1292 	*ddsp_taskp = NULL;
1293 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
1294 		goto direct;
1295 
1296 	/*
1297 	 * If not directly dispatched, QUEUEING isn't clear yet and dispatch or
1298 	 * dequeue may be waiting. The store_release matches their load_acquire.
1299 	 */
1300 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_QUEUED | qseq);
1301 	return;
1302 
1303 direct:
1304 	direct_dispatch(sch, p, enq_flags);
1305 	return;
1306 
1307 local:
1308 	/*
1309 	 * For task-ordering, slice refill must be treated as implying the end
1310 	 * of the current slice. Otherwise, the longer @p stays on the CPU, the
1311 	 * higher priority it becomes from scx_prio_less()'s POV.
1312 	 */
1313 	touch_core_sched(rq, p);
1314 	refill_task_slice_dfl(sch, p);
1315 local_norefill:
1316 	dispatch_enqueue(sch, &rq->scx.local_dsq, p, enq_flags);
1317 	return;
1318 
1319 global:
1320 	touch_core_sched(rq, p);	/* see the comment in local: */
1321 	refill_task_slice_dfl(sch, p);
1322 	dispatch_enqueue(sch, find_global_dsq(sch, p), p, enq_flags);
1323 }
1324 
1325 static bool task_runnable(const struct task_struct *p)
1326 {
1327 	return !list_empty(&p->scx.runnable_node);
1328 }
1329 
1330 static void set_task_runnable(struct rq *rq, struct task_struct *p)
1331 {
1332 	lockdep_assert_rq_held(rq);
1333 
1334 	if (p->scx.flags & SCX_TASK_RESET_RUNNABLE_AT) {
1335 		p->scx.runnable_at = jiffies;
1336 		p->scx.flags &= ~SCX_TASK_RESET_RUNNABLE_AT;
1337 	}
1338 
1339 	/*
1340 	 * list_add_tail() must be used. scx_bypass() depends on tasks being
1341 	 * appended to the runnable_list.
1342 	 */
1343 	list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list);
1344 }
1345 
1346 static void clr_task_runnable(struct task_struct *p, bool reset_runnable_at)
1347 {
1348 	list_del_init(&p->scx.runnable_node);
1349 	if (reset_runnable_at)
1350 		p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
1351 }
1352 
1353 static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int enq_flags)
1354 {
1355 	struct scx_sched *sch = scx_root;
1356 	int sticky_cpu = p->scx.sticky_cpu;
1357 
1358 	if (enq_flags & ENQUEUE_WAKEUP)
1359 		rq->scx.flags |= SCX_RQ_IN_WAKEUP;
1360 
1361 	enq_flags |= rq->scx.extra_enq_flags;
1362 
1363 	if (sticky_cpu >= 0)
1364 		p->scx.sticky_cpu = -1;
1365 
1366 	/*
1367 	 * Restoring a running task will be immediately followed by
1368 	 * set_next_task_scx() which expects the task to not be on the BPF
1369 	 * scheduler as tasks can only start running through local DSQs. Force
1370 	 * direct-dispatch into the local DSQ by setting the sticky_cpu.
1371 	 */
1372 	if (unlikely(enq_flags & ENQUEUE_RESTORE) && task_current(rq, p))
1373 		sticky_cpu = cpu_of(rq);
1374 
1375 	if (p->scx.flags & SCX_TASK_QUEUED) {
1376 		WARN_ON_ONCE(!task_runnable(p));
1377 		goto out;
1378 	}
1379 
1380 	set_task_runnable(rq, p);
1381 	p->scx.flags |= SCX_TASK_QUEUED;
1382 	rq->scx.nr_running++;
1383 	add_nr_running(rq, 1);
1384 
1385 	if (SCX_HAS_OP(sch, runnable) && !task_on_rq_migrating(p))
1386 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, runnable, rq, p, enq_flags);
1387 
1388 	if (enq_flags & SCX_ENQ_WAKEUP)
1389 		touch_core_sched(rq, p);
1390 
1391 	do_enqueue_task(rq, p, enq_flags, sticky_cpu);
1392 out:
1393 	rq->scx.flags &= ~SCX_RQ_IN_WAKEUP;
1394 
1395 	if ((enq_flags & SCX_ENQ_CPU_SELECTED) &&
1396 	    unlikely(cpu_of(rq) != p->scx.selected_cpu))
1397 		__scx_add_event(sch, SCX_EV_SELECT_CPU_FALLBACK, 1);
1398 }
1399 
1400 static void ops_dequeue(struct rq *rq, struct task_struct *p, u64 deq_flags)
1401 {
1402 	struct scx_sched *sch = scx_root;
1403 	unsigned long opss;
1404 
1405 	/* dequeue is always temporary, don't reset runnable_at */
1406 	clr_task_runnable(p, false);
1407 
1408 	/* acquire ensures that we see the preceding updates on QUEUED */
1409 	opss = atomic_long_read_acquire(&p->scx.ops_state);
1410 
1411 	switch (opss & SCX_OPSS_STATE_MASK) {
1412 	case SCX_OPSS_NONE:
1413 		break;
1414 	case SCX_OPSS_QUEUEING:
1415 		/*
1416 		 * QUEUEING is started and finished while holding @p's rq lock.
1417 		 * As we're holding the rq lock now, we shouldn't see QUEUEING.
1418 		 */
1419 		BUG();
1420 	case SCX_OPSS_QUEUED:
1421 		if (SCX_HAS_OP(sch, dequeue))
1422 			SCX_CALL_OP_TASK(sch, SCX_KF_REST, dequeue, rq,
1423 					 p, deq_flags);
1424 
1425 		if (atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
1426 					    SCX_OPSS_NONE))
1427 			break;
1428 		fallthrough;
1429 	case SCX_OPSS_DISPATCHING:
1430 		/*
1431 		 * If @p is being dispatched from the BPF scheduler to a DSQ,
1432 		 * wait for the transfer to complete so that @p doesn't get
1433 		 * added to its DSQ after dequeueing is complete.
1434 		 *
1435 		 * As we're waiting on DISPATCHING with the rq locked, the
1436 		 * dispatching side shouldn't try to lock the rq while
1437 		 * DISPATCHING is set. See dispatch_to_local_dsq().
1438 		 *
1439 		 * DISPATCHING shouldn't have qseq set and control can reach
1440 		 * here with NONE @opss from the above QUEUED case block.
1441 		 * Explicitly wait on %SCX_OPSS_DISPATCHING instead of @opss.
1442 		 */
1443 		wait_ops_state(p, SCX_OPSS_DISPATCHING);
1444 		BUG_ON(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
1445 		break;
1446 	}
1447 }
1448 
1449 static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int deq_flags)
1450 {
1451 	struct scx_sched *sch = scx_root;
1452 
1453 	if (!(p->scx.flags & SCX_TASK_QUEUED)) {
1454 		WARN_ON_ONCE(task_runnable(p));
1455 		return true;
1456 	}
1457 
1458 	ops_dequeue(rq, p, deq_flags);
1459 
1460 	/*
1461 	 * A currently running task which is going off @rq first gets dequeued
1462 	 * and then stops running. As we want running <-> stopping transitions
1463 	 * to be contained within runnable <-> quiescent transitions, trigger
1464 	 * ->stopping() early here instead of in put_prev_task_scx().
1465 	 *
1466 	 * @p may go through multiple stopping <-> running transitions between
1467 	 * here and put_prev_task_scx() if task attribute changes occur while
1468 	 * balance_scx() leaves @rq unlocked. However, they don't contain any
1469 	 * information meaningful to the BPF scheduler and can be suppressed by
1470 	 * skipping the callbacks if the task is !QUEUED.
1471 	 */
1472 	if (SCX_HAS_OP(sch, stopping) && task_current(rq, p)) {
1473 		update_curr_scx(rq);
1474 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, stopping, rq, p, false);
1475 	}
1476 
1477 	if (SCX_HAS_OP(sch, quiescent) && !task_on_rq_migrating(p))
1478 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, quiescent, rq, p, deq_flags);
1479 
1480 	if (deq_flags & SCX_DEQ_SLEEP)
1481 		p->scx.flags |= SCX_TASK_DEQD_FOR_SLEEP;
1482 	else
1483 		p->scx.flags &= ~SCX_TASK_DEQD_FOR_SLEEP;
1484 
1485 	p->scx.flags &= ~SCX_TASK_QUEUED;
1486 	rq->scx.nr_running--;
1487 	sub_nr_running(rq, 1);
1488 
1489 	dispatch_dequeue(rq, p);
1490 	return true;
1491 }
1492 
1493 static void yield_task_scx(struct rq *rq)
1494 {
1495 	struct scx_sched *sch = scx_root;
1496 	struct task_struct *p = rq->curr;
1497 
1498 	if (SCX_HAS_OP(sch, yield))
1499 		SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, yield, rq, p, NULL);
1500 	else
1501 		p->scx.slice = 0;
1502 }
1503 
1504 static bool yield_to_task_scx(struct rq *rq, struct task_struct *to)
1505 {
1506 	struct scx_sched *sch = scx_root;
1507 	struct task_struct *from = rq->curr;
1508 
1509 	if (SCX_HAS_OP(sch, yield))
1510 		return SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, yield, rq,
1511 					      from, to);
1512 	else
1513 		return false;
1514 }
1515 
1516 static void move_local_task_to_local_dsq(struct task_struct *p, u64 enq_flags,
1517 					 struct scx_dispatch_q *src_dsq,
1518 					 struct rq *dst_rq)
1519 {
1520 	struct scx_dispatch_q *dst_dsq = &dst_rq->scx.local_dsq;
1521 
1522 	/* @dsq is locked and @p is on @dst_rq */
1523 	lockdep_assert_held(&src_dsq->lock);
1524 	lockdep_assert_rq_held(dst_rq);
1525 
1526 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
1527 
1528 	if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT))
1529 		list_add(&p->scx.dsq_list.node, &dst_dsq->list);
1530 	else
1531 		list_add_tail(&p->scx.dsq_list.node, &dst_dsq->list);
1532 
1533 	dsq_mod_nr(dst_dsq, 1);
1534 	p->scx.dsq = dst_dsq;
1535 }
1536 
1537 /**
1538  * move_remote_task_to_local_dsq - Move a task from a foreign rq to a local DSQ
1539  * @p: task to move
1540  * @enq_flags: %SCX_ENQ_*
1541  * @src_rq: rq to move the task from, locked on entry, released on return
1542  * @dst_rq: rq to move the task into, locked on return
1543  *
1544  * Move @p which is currently on @src_rq to @dst_rq's local DSQ.
1545  */
1546 static void move_remote_task_to_local_dsq(struct task_struct *p, u64 enq_flags,
1547 					  struct rq *src_rq, struct rq *dst_rq)
1548 {
1549 	lockdep_assert_rq_held(src_rq);
1550 
1551 	/* the following marks @p MIGRATING which excludes dequeue */
1552 	deactivate_task(src_rq, p, 0);
1553 	set_task_cpu(p, cpu_of(dst_rq));
1554 	p->scx.sticky_cpu = cpu_of(dst_rq);
1555 
1556 	raw_spin_rq_unlock(src_rq);
1557 	raw_spin_rq_lock(dst_rq);
1558 
1559 	/*
1560 	 * We want to pass scx-specific enq_flags but activate_task() will
1561 	 * truncate the upper 32 bit. As we own @rq, we can pass them through
1562 	 * @rq->scx.extra_enq_flags instead.
1563 	 */
1564 	WARN_ON_ONCE(!cpumask_test_cpu(cpu_of(dst_rq), p->cpus_ptr));
1565 	WARN_ON_ONCE(dst_rq->scx.extra_enq_flags);
1566 	dst_rq->scx.extra_enq_flags = enq_flags;
1567 	activate_task(dst_rq, p, 0);
1568 	dst_rq->scx.extra_enq_flags = 0;
1569 }
1570 
1571 /*
1572  * Similar to kernel/sched/core.c::is_cpu_allowed(). However, there are two
1573  * differences:
1574  *
1575  * - is_cpu_allowed() asks "Can this task run on this CPU?" while
1576  *   task_can_run_on_remote_rq() asks "Can the BPF scheduler migrate the task to
1577  *   this CPU?".
1578  *
1579  *   While migration is disabled, is_cpu_allowed() has to say "yes" as the task
1580  *   must be allowed to finish on the CPU that it's currently on regardless of
1581  *   the CPU state. However, task_can_run_on_remote_rq() must say "no" as the
1582  *   BPF scheduler shouldn't attempt to migrate a task which has migration
1583  *   disabled.
1584  *
1585  * - The BPF scheduler is bypassed while the rq is offline and we can always say
1586  *   no to the BPF scheduler initiated migrations while offline.
1587  *
1588  * The caller must ensure that @p and @rq are on different CPUs.
1589  */
1590 static bool task_can_run_on_remote_rq(struct scx_sched *sch,
1591 				      struct task_struct *p, struct rq *rq,
1592 				      bool enforce)
1593 {
1594 	int cpu = cpu_of(rq);
1595 
1596 	WARN_ON_ONCE(task_cpu(p) == cpu);
1597 
1598 	/*
1599 	 * If @p has migration disabled, @p->cpus_ptr is updated to contain only
1600 	 * the pinned CPU in migrate_disable_switch() while @p is being switched
1601 	 * out. However, put_prev_task_scx() is called before @p->cpus_ptr is
1602 	 * updated and thus another CPU may see @p on a DSQ inbetween leading to
1603 	 * @p passing the below task_allowed_on_cpu() check while migration is
1604 	 * disabled.
1605 	 *
1606 	 * Test the migration disabled state first as the race window is narrow
1607 	 * and the BPF scheduler failing to check migration disabled state can
1608 	 * easily be masked if task_allowed_on_cpu() is done first.
1609 	 */
1610 	if (unlikely(is_migration_disabled(p))) {
1611 		if (enforce)
1612 			scx_error(sch, "SCX_DSQ_LOCAL[_ON] cannot move migration disabled %s[%d] from CPU %d to %d",
1613 				  p->comm, p->pid, task_cpu(p), cpu);
1614 		return false;
1615 	}
1616 
1617 	/*
1618 	 * We don't require the BPF scheduler to avoid dispatching to offline
1619 	 * CPUs mostly for convenience but also because CPUs can go offline
1620 	 * between scx_bpf_dsq_insert() calls and here. Trigger error iff the
1621 	 * picked CPU is outside the allowed mask.
1622 	 */
1623 	if (!task_allowed_on_cpu(p, cpu)) {
1624 		if (enforce)
1625 			scx_error(sch, "SCX_DSQ_LOCAL[_ON] target CPU %d not allowed for %s[%d]",
1626 				  cpu, p->comm, p->pid);
1627 		return false;
1628 	}
1629 
1630 	if (!scx_rq_online(rq)) {
1631 		if (enforce)
1632 			__scx_add_event(sch, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE, 1);
1633 		return false;
1634 	}
1635 
1636 	return true;
1637 }
1638 
1639 /**
1640  * unlink_dsq_and_lock_src_rq() - Unlink task from its DSQ and lock its task_rq
1641  * @p: target task
1642  * @dsq: locked DSQ @p is currently on
1643  * @src_rq: rq @p is currently on, stable with @dsq locked
1644  *
1645  * Called with @dsq locked but no rq's locked. We want to move @p to a different
1646  * DSQ, including any local DSQ, but are not locking @src_rq. Locking @src_rq is
1647  * required when transferring into a local DSQ. Even when transferring into a
1648  * non-local DSQ, it's better to use the same mechanism to protect against
1649  * dequeues and maintain the invariant that @p->scx.dsq can only change while
1650  * @src_rq is locked, which e.g. scx_dump_task() depends on.
1651  *
1652  * We want to grab @src_rq but that can deadlock if we try while locking @dsq,
1653  * so we want to unlink @p from @dsq, drop its lock and then lock @src_rq. As
1654  * this may race with dequeue, which can't drop the rq lock or fail, do a little
1655  * dancing from our side.
1656  *
1657  * @p->scx.holding_cpu is set to this CPU before @dsq is unlocked. If @p gets
1658  * dequeued after we unlock @dsq but before locking @src_rq, the holding_cpu
1659  * would be cleared to -1. While other cpus may have updated it to different
1660  * values afterwards, as this operation can't be preempted or recurse, the
1661  * holding_cpu can never become this CPU again before we're done. Thus, we can
1662  * tell whether we lost to dequeue by testing whether the holding_cpu still
1663  * points to this CPU. See dispatch_dequeue() for the counterpart.
1664  *
1665  * On return, @dsq is unlocked and @src_rq is locked. Returns %true if @p is
1666  * still valid. %false if lost to dequeue.
1667  */
1668 static bool unlink_dsq_and_lock_src_rq(struct task_struct *p,
1669 				       struct scx_dispatch_q *dsq,
1670 				       struct rq *src_rq)
1671 {
1672 	s32 cpu = raw_smp_processor_id();
1673 
1674 	lockdep_assert_held(&dsq->lock);
1675 
1676 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
1677 	task_unlink_from_dsq(p, dsq);
1678 	p->scx.holding_cpu = cpu;
1679 
1680 	raw_spin_unlock(&dsq->lock);
1681 	raw_spin_rq_lock(src_rq);
1682 
1683 	/* task_rq couldn't have changed if we're still the holding cpu */
1684 	return likely(p->scx.holding_cpu == cpu) &&
1685 		!WARN_ON_ONCE(src_rq != task_rq(p));
1686 }
1687 
1688 static bool consume_remote_task(struct rq *this_rq, struct task_struct *p,
1689 				struct scx_dispatch_q *dsq, struct rq *src_rq)
1690 {
1691 	raw_spin_rq_unlock(this_rq);
1692 
1693 	if (unlink_dsq_and_lock_src_rq(p, dsq, src_rq)) {
1694 		move_remote_task_to_local_dsq(p, 0, src_rq, this_rq);
1695 		return true;
1696 	} else {
1697 		raw_spin_rq_unlock(src_rq);
1698 		raw_spin_rq_lock(this_rq);
1699 		return false;
1700 	}
1701 }
1702 
1703 /**
1704  * move_task_between_dsqs() - Move a task from one DSQ to another
1705  * @sch: scx_sched being operated on
1706  * @p: target task
1707  * @enq_flags: %SCX_ENQ_*
1708  * @src_dsq: DSQ @p is currently on, must not be a local DSQ
1709  * @dst_dsq: DSQ @p is being moved to, can be any DSQ
1710  *
1711  * Must be called with @p's task_rq and @src_dsq locked. If @dst_dsq is a local
1712  * DSQ and @p is on a different CPU, @p will be migrated and thus its task_rq
1713  * will change. As @p's task_rq is locked, this function doesn't need to use the
1714  * holding_cpu mechanism.
1715  *
1716  * On return, @src_dsq is unlocked and only @p's new task_rq, which is the
1717  * return value, is locked.
1718  */
1719 static struct rq *move_task_between_dsqs(struct scx_sched *sch,
1720 					 struct task_struct *p, u64 enq_flags,
1721 					 struct scx_dispatch_q *src_dsq,
1722 					 struct scx_dispatch_q *dst_dsq)
1723 {
1724 	struct rq *src_rq = task_rq(p), *dst_rq;
1725 
1726 	BUG_ON(src_dsq->id == SCX_DSQ_LOCAL);
1727 	lockdep_assert_held(&src_dsq->lock);
1728 	lockdep_assert_rq_held(src_rq);
1729 
1730 	if (dst_dsq->id == SCX_DSQ_LOCAL) {
1731 		dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
1732 		if (src_rq != dst_rq &&
1733 		    unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) {
1734 			dst_dsq = find_global_dsq(sch, p);
1735 			dst_rq = src_rq;
1736 		}
1737 	} else {
1738 		/* no need to migrate if destination is a non-local DSQ */
1739 		dst_rq = src_rq;
1740 	}
1741 
1742 	/*
1743 	 * Move @p into $dst_dsq. If $dst_dsq is the local DSQ of a different
1744 	 * CPU, @p will be migrated.
1745 	 */
1746 	if (dst_dsq->id == SCX_DSQ_LOCAL) {
1747 		/* @p is going from a non-local DSQ to a local DSQ */
1748 		if (src_rq == dst_rq) {
1749 			task_unlink_from_dsq(p, src_dsq);
1750 			move_local_task_to_local_dsq(p, enq_flags,
1751 						     src_dsq, dst_rq);
1752 			raw_spin_unlock(&src_dsq->lock);
1753 		} else {
1754 			raw_spin_unlock(&src_dsq->lock);
1755 			move_remote_task_to_local_dsq(p, enq_flags,
1756 						      src_rq, dst_rq);
1757 		}
1758 	} else {
1759 		/*
1760 		 * @p is going from a non-local DSQ to a non-local DSQ. As
1761 		 * $src_dsq is already locked, do an abbreviated dequeue.
1762 		 */
1763 		task_unlink_from_dsq(p, src_dsq);
1764 		p->scx.dsq = NULL;
1765 		raw_spin_unlock(&src_dsq->lock);
1766 
1767 		dispatch_enqueue(sch, dst_dsq, p, enq_flags);
1768 	}
1769 
1770 	return dst_rq;
1771 }
1772 
1773 /*
1774  * A poorly behaving BPF scheduler can live-lock the system by e.g. incessantly
1775  * banging on the same DSQ on a large NUMA system to the point where switching
1776  * to the bypass mode can take a long time. Inject artificial delays while the
1777  * bypass mode is switching to guarantee timely completion.
1778  */
1779 static void scx_breather(struct rq *rq)
1780 {
1781 	u64 until;
1782 
1783 	lockdep_assert_rq_held(rq);
1784 
1785 	if (likely(!atomic_read(&scx_breather_depth)))
1786 		return;
1787 
1788 	raw_spin_rq_unlock(rq);
1789 
1790 	until = ktime_get_ns() + NSEC_PER_MSEC;
1791 
1792 	do {
1793 		int cnt = 1024;
1794 		while (atomic_read(&scx_breather_depth) && --cnt)
1795 			cpu_relax();
1796 	} while (atomic_read(&scx_breather_depth) &&
1797 		 time_before64(ktime_get_ns(), until));
1798 
1799 	raw_spin_rq_lock(rq);
1800 }
1801 
1802 static bool consume_dispatch_q(struct scx_sched *sch, struct rq *rq,
1803 			       struct scx_dispatch_q *dsq)
1804 {
1805 	struct task_struct *p;
1806 retry:
1807 	/*
1808 	 * This retry loop can repeatedly race against scx_bypass() dequeueing
1809 	 * tasks from @dsq trying to put the system into the bypass mode. On
1810 	 * some multi-socket machines (e.g. 2x Intel 8480c), this can live-lock
1811 	 * the machine into soft lockups. Give a breather.
1812 	 */
1813 	scx_breather(rq);
1814 
1815 	/*
1816 	 * The caller can't expect to successfully consume a task if the task's
1817 	 * addition to @dsq isn't guaranteed to be visible somehow. Test
1818 	 * @dsq->list without locking and skip if it seems empty.
1819 	 */
1820 	if (list_empty(&dsq->list))
1821 		return false;
1822 
1823 	raw_spin_lock(&dsq->lock);
1824 
1825 	nldsq_for_each_task(p, dsq) {
1826 		struct rq *task_rq = task_rq(p);
1827 
1828 		if (rq == task_rq) {
1829 			task_unlink_from_dsq(p, dsq);
1830 			move_local_task_to_local_dsq(p, 0, dsq, rq);
1831 			raw_spin_unlock(&dsq->lock);
1832 			return true;
1833 		}
1834 
1835 		if (task_can_run_on_remote_rq(sch, p, rq, false)) {
1836 			if (likely(consume_remote_task(rq, p, dsq, task_rq)))
1837 				return true;
1838 			goto retry;
1839 		}
1840 	}
1841 
1842 	raw_spin_unlock(&dsq->lock);
1843 	return false;
1844 }
1845 
1846 static bool consume_global_dsq(struct scx_sched *sch, struct rq *rq)
1847 {
1848 	int node = cpu_to_node(cpu_of(rq));
1849 
1850 	return consume_dispatch_q(sch, rq, sch->global_dsqs[node]);
1851 }
1852 
1853 /**
1854  * dispatch_to_local_dsq - Dispatch a task to a local dsq
1855  * @sch: scx_sched being operated on
1856  * @rq: current rq which is locked
1857  * @dst_dsq: destination DSQ
1858  * @p: task to dispatch
1859  * @enq_flags: %SCX_ENQ_*
1860  *
1861  * We're holding @rq lock and want to dispatch @p to @dst_dsq which is a local
1862  * DSQ. This function performs all the synchronization dancing needed because
1863  * local DSQs are protected with rq locks.
1864  *
1865  * The caller must have exclusive ownership of @p (e.g. through
1866  * %SCX_OPSS_DISPATCHING).
1867  */
1868 static void dispatch_to_local_dsq(struct scx_sched *sch, struct rq *rq,
1869 				  struct scx_dispatch_q *dst_dsq,
1870 				  struct task_struct *p, u64 enq_flags)
1871 {
1872 	struct rq *src_rq = task_rq(p);
1873 	struct rq *dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
1874 	struct rq *locked_rq = rq;
1875 
1876 	/*
1877 	 * We're synchronized against dequeue through DISPATCHING. As @p can't
1878 	 * be dequeued, its task_rq and cpus_allowed are stable too.
1879 	 *
1880 	 * If dispatching to @rq that @p is already on, no lock dancing needed.
1881 	 */
1882 	if (rq == src_rq && rq == dst_rq) {
1883 		dispatch_enqueue(sch, dst_dsq, p,
1884 				 enq_flags | SCX_ENQ_CLEAR_OPSS);
1885 		return;
1886 	}
1887 
1888 	if (src_rq != dst_rq &&
1889 	    unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) {
1890 		dispatch_enqueue(sch, find_global_dsq(sch, p), p,
1891 				 enq_flags | SCX_ENQ_CLEAR_OPSS);
1892 		return;
1893 	}
1894 
1895 	/*
1896 	 * @p is on a possibly remote @src_rq which we need to lock to move the
1897 	 * task. If dequeue is in progress, it'd be locking @src_rq and waiting
1898 	 * on DISPATCHING, so we can't grab @src_rq lock while holding
1899 	 * DISPATCHING.
1900 	 *
1901 	 * As DISPATCHING guarantees that @p is wholly ours, we can pretend that
1902 	 * we're moving from a DSQ and use the same mechanism - mark the task
1903 	 * under transfer with holding_cpu, release DISPATCHING and then follow
1904 	 * the same protocol. See unlink_dsq_and_lock_src_rq().
1905 	 */
1906 	p->scx.holding_cpu = raw_smp_processor_id();
1907 
1908 	/* store_release ensures that dequeue sees the above */
1909 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1910 
1911 	/* switch to @src_rq lock */
1912 	if (locked_rq != src_rq) {
1913 		raw_spin_rq_unlock(locked_rq);
1914 		locked_rq = src_rq;
1915 		raw_spin_rq_lock(src_rq);
1916 	}
1917 
1918 	/* task_rq couldn't have changed if we're still the holding cpu */
1919 	if (likely(p->scx.holding_cpu == raw_smp_processor_id()) &&
1920 	    !WARN_ON_ONCE(src_rq != task_rq(p))) {
1921 		/*
1922 		 * If @p is staying on the same rq, there's no need to go
1923 		 * through the full deactivate/activate cycle. Optimize by
1924 		 * abbreviating move_remote_task_to_local_dsq().
1925 		 */
1926 		if (src_rq == dst_rq) {
1927 			p->scx.holding_cpu = -1;
1928 			dispatch_enqueue(sch, &dst_rq->scx.local_dsq, p,
1929 					 enq_flags);
1930 		} else {
1931 			move_remote_task_to_local_dsq(p, enq_flags,
1932 						      src_rq, dst_rq);
1933 			/* task has been moved to dst_rq, which is now locked */
1934 			locked_rq = dst_rq;
1935 		}
1936 
1937 		/* if the destination CPU is idle, wake it up */
1938 		if (sched_class_above(p->sched_class, dst_rq->curr->sched_class))
1939 			resched_curr(dst_rq);
1940 	}
1941 
1942 	/* switch back to @rq lock */
1943 	if (locked_rq != rq) {
1944 		raw_spin_rq_unlock(locked_rq);
1945 		raw_spin_rq_lock(rq);
1946 	}
1947 }
1948 
1949 /**
1950  * finish_dispatch - Asynchronously finish dispatching a task
1951  * @rq: current rq which is locked
1952  * @p: task to finish dispatching
1953  * @qseq_at_dispatch: qseq when @p started getting dispatched
1954  * @dsq_id: destination DSQ ID
1955  * @enq_flags: %SCX_ENQ_*
1956  *
1957  * Dispatching to local DSQs may need to wait for queueing to complete or
1958  * require rq lock dancing. As we don't wanna do either while inside
1959  * ops.dispatch() to avoid locking order inversion, we split dispatching into
1960  * two parts. scx_bpf_dsq_insert() which is called by ops.dispatch() records the
1961  * task and its qseq. Once ops.dispatch() returns, this function is called to
1962  * finish up.
1963  *
1964  * There is no guarantee that @p is still valid for dispatching or even that it
1965  * was valid in the first place. Make sure that the task is still owned by the
1966  * BPF scheduler and claim the ownership before dispatching.
1967  */
1968 static void finish_dispatch(struct scx_sched *sch, struct rq *rq,
1969 			    struct task_struct *p,
1970 			    unsigned long qseq_at_dispatch,
1971 			    u64 dsq_id, u64 enq_flags)
1972 {
1973 	struct scx_dispatch_q *dsq;
1974 	unsigned long opss;
1975 
1976 	touch_core_sched_dispatch(rq, p);
1977 retry:
1978 	/*
1979 	 * No need for _acquire here. @p is accessed only after a successful
1980 	 * try_cmpxchg to DISPATCHING.
1981 	 */
1982 	opss = atomic_long_read(&p->scx.ops_state);
1983 
1984 	switch (opss & SCX_OPSS_STATE_MASK) {
1985 	case SCX_OPSS_DISPATCHING:
1986 	case SCX_OPSS_NONE:
1987 		/* someone else already got to it */
1988 		return;
1989 	case SCX_OPSS_QUEUED:
1990 		/*
1991 		 * If qseq doesn't match, @p has gone through at least one
1992 		 * dispatch/dequeue and re-enqueue cycle between
1993 		 * scx_bpf_dsq_insert() and here and we have no claim on it.
1994 		 */
1995 		if ((opss & SCX_OPSS_QSEQ_MASK) != qseq_at_dispatch)
1996 			return;
1997 
1998 		/*
1999 		 * While we know @p is accessible, we don't yet have a claim on
2000 		 * it - the BPF scheduler is allowed to dispatch tasks
2001 		 * spuriously and there can be a racing dequeue attempt. Let's
2002 		 * claim @p by atomically transitioning it from QUEUED to
2003 		 * DISPATCHING.
2004 		 */
2005 		if (likely(atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
2006 						   SCX_OPSS_DISPATCHING)))
2007 			break;
2008 		goto retry;
2009 	case SCX_OPSS_QUEUEING:
2010 		/*
2011 		 * do_enqueue_task() is in the process of transferring the task
2012 		 * to the BPF scheduler while holding @p's rq lock. As we aren't
2013 		 * holding any kernel or BPF resource that the enqueue path may
2014 		 * depend upon, it's safe to wait.
2015 		 */
2016 		wait_ops_state(p, opss);
2017 		goto retry;
2018 	}
2019 
2020 	BUG_ON(!(p->scx.flags & SCX_TASK_QUEUED));
2021 
2022 	dsq = find_dsq_for_dispatch(sch, this_rq(), dsq_id, p);
2023 
2024 	if (dsq->id == SCX_DSQ_LOCAL)
2025 		dispatch_to_local_dsq(sch, rq, dsq, p, enq_flags);
2026 	else
2027 		dispatch_enqueue(sch, dsq, p, enq_flags | SCX_ENQ_CLEAR_OPSS);
2028 }
2029 
2030 static void flush_dispatch_buf(struct scx_sched *sch, struct rq *rq)
2031 {
2032 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
2033 	u32 u;
2034 
2035 	for (u = 0; u < dspc->cursor; u++) {
2036 		struct scx_dsp_buf_ent *ent = &dspc->buf[u];
2037 
2038 		finish_dispatch(sch, rq, ent->task, ent->qseq, ent->dsq_id,
2039 				ent->enq_flags);
2040 	}
2041 
2042 	dspc->nr_tasks += dspc->cursor;
2043 	dspc->cursor = 0;
2044 }
2045 
2046 static inline void maybe_queue_balance_callback(struct rq *rq)
2047 {
2048 	lockdep_assert_rq_held(rq);
2049 
2050 	if (!(rq->scx.flags & SCX_RQ_BAL_CB_PENDING))
2051 		return;
2052 
2053 	queue_balance_callback(rq, &rq->scx.deferred_bal_cb,
2054 				deferred_bal_cb_workfn);
2055 
2056 	rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING;
2057 }
2058 
2059 static int balance_one(struct rq *rq, struct task_struct *prev)
2060 {
2061 	struct scx_sched *sch = scx_root;
2062 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
2063 	bool prev_on_scx = prev->sched_class == &ext_sched_class;
2064 	bool prev_on_rq = prev->scx.flags & SCX_TASK_QUEUED;
2065 	int nr_loops = SCX_DSP_MAX_LOOPS;
2066 
2067 	lockdep_assert_rq_held(rq);
2068 	rq->scx.flags |= SCX_RQ_IN_BALANCE;
2069 	rq->scx.flags &= ~(SCX_RQ_BAL_PENDING | SCX_RQ_BAL_KEEP);
2070 
2071 	if ((sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) &&
2072 	    unlikely(rq->scx.cpu_released)) {
2073 		/*
2074 		 * If the previous sched_class for the current CPU was not SCX,
2075 		 * notify the BPF scheduler that it again has control of the
2076 		 * core. This callback complements ->cpu_release(), which is
2077 		 * emitted in switch_class().
2078 		 */
2079 		if (SCX_HAS_OP(sch, cpu_acquire))
2080 			SCX_CALL_OP(sch, SCX_KF_REST, cpu_acquire, rq,
2081 				    cpu_of(rq), NULL);
2082 		rq->scx.cpu_released = false;
2083 	}
2084 
2085 	if (prev_on_scx) {
2086 		update_curr_scx(rq);
2087 
2088 		/*
2089 		 * If @prev is runnable & has slice left, it has priority and
2090 		 * fetching more just increases latency for the fetched tasks.
2091 		 * Tell pick_task_scx() to keep running @prev. If the BPF
2092 		 * scheduler wants to handle this explicitly, it should
2093 		 * implement ->cpu_release().
2094 		 *
2095 		 * See scx_disable_workfn() for the explanation on the bypassing
2096 		 * test.
2097 		 */
2098 		if (prev_on_rq && prev->scx.slice && !scx_rq_bypassing(rq)) {
2099 			rq->scx.flags |= SCX_RQ_BAL_KEEP;
2100 			goto has_tasks;
2101 		}
2102 	}
2103 
2104 	/* if there already are tasks to run, nothing to do */
2105 	if (rq->scx.local_dsq.nr)
2106 		goto has_tasks;
2107 
2108 	if (consume_global_dsq(sch, rq))
2109 		goto has_tasks;
2110 
2111 	if (unlikely(!SCX_HAS_OP(sch, dispatch)) ||
2112 	    scx_rq_bypassing(rq) || !scx_rq_online(rq))
2113 		goto no_tasks;
2114 
2115 	dspc->rq = rq;
2116 
2117 	/*
2118 	 * The dispatch loop. Because flush_dispatch_buf() may drop the rq lock,
2119 	 * the local DSQ might still end up empty after a successful
2120 	 * ops.dispatch(). If the local DSQ is empty even after ops.dispatch()
2121 	 * produced some tasks, retry. The BPF scheduler may depend on this
2122 	 * looping behavior to simplify its implementation.
2123 	 */
2124 	do {
2125 		dspc->nr_tasks = 0;
2126 
2127 		SCX_CALL_OP(sch, SCX_KF_DISPATCH, dispatch, rq,
2128 			    cpu_of(rq), prev_on_scx ? prev : NULL);
2129 
2130 		flush_dispatch_buf(sch, rq);
2131 
2132 		if (prev_on_rq && prev->scx.slice) {
2133 			rq->scx.flags |= SCX_RQ_BAL_KEEP;
2134 			goto has_tasks;
2135 		}
2136 		if (rq->scx.local_dsq.nr)
2137 			goto has_tasks;
2138 		if (consume_global_dsq(sch, rq))
2139 			goto has_tasks;
2140 
2141 		/*
2142 		 * ops.dispatch() can trap us in this loop by repeatedly
2143 		 * dispatching ineligible tasks. Break out once in a while to
2144 		 * allow the watchdog to run. As IRQ can't be enabled in
2145 		 * balance(), we want to complete this scheduling cycle and then
2146 		 * start a new one. IOW, we want to call resched_curr() on the
2147 		 * next, most likely idle, task, not the current one. Use
2148 		 * scx_kick_cpu() for deferred kicking.
2149 		 */
2150 		if (unlikely(!--nr_loops)) {
2151 			scx_kick_cpu(sch, cpu_of(rq), 0);
2152 			break;
2153 		}
2154 	} while (dspc->nr_tasks);
2155 
2156 no_tasks:
2157 	/*
2158 	 * Didn't find another task to run. Keep running @prev unless
2159 	 * %SCX_OPS_ENQ_LAST is in effect.
2160 	 */
2161 	if (prev_on_rq &&
2162 	    (!(sch->ops.flags & SCX_OPS_ENQ_LAST) || scx_rq_bypassing(rq))) {
2163 		rq->scx.flags |= SCX_RQ_BAL_KEEP;
2164 		__scx_add_event(sch, SCX_EV_DISPATCH_KEEP_LAST, 1);
2165 		goto has_tasks;
2166 	}
2167 	rq->scx.flags &= ~SCX_RQ_IN_BALANCE;
2168 	return false;
2169 
2170 has_tasks:
2171 	rq->scx.flags &= ~SCX_RQ_IN_BALANCE;
2172 	return true;
2173 }
2174 
2175 static int balance_scx(struct rq *rq, struct task_struct *prev,
2176 		       struct rq_flags *rf)
2177 {
2178 	int ret;
2179 
2180 	rq_unpin_lock(rq, rf);
2181 
2182 	ret = balance_one(rq, prev);
2183 
2184 #ifdef CONFIG_SCHED_SMT
2185 	/*
2186 	 * When core-sched is enabled, this ops.balance() call will be followed
2187 	 * by pick_task_scx() on this CPU and the SMT siblings. Balance the
2188 	 * siblings too.
2189 	 */
2190 	if (sched_core_enabled(rq)) {
2191 		const struct cpumask *smt_mask = cpu_smt_mask(cpu_of(rq));
2192 		int scpu;
2193 
2194 		for_each_cpu_andnot(scpu, smt_mask, cpumask_of(cpu_of(rq))) {
2195 			struct rq *srq = cpu_rq(scpu);
2196 			struct task_struct *sprev = srq->curr;
2197 
2198 			WARN_ON_ONCE(__rq_lockp(rq) != __rq_lockp(srq));
2199 			update_rq_clock(srq);
2200 			balance_one(srq, sprev);
2201 		}
2202 	}
2203 #endif
2204 	rq_repin_lock(rq, rf);
2205 
2206 	maybe_queue_balance_callback(rq);
2207 
2208 	return ret;
2209 }
2210 
2211 static void process_ddsp_deferred_locals(struct rq *rq)
2212 {
2213 	struct task_struct *p;
2214 
2215 	lockdep_assert_rq_held(rq);
2216 
2217 	/*
2218 	 * Now that @rq can be unlocked, execute the deferred enqueueing of
2219 	 * tasks directly dispatched to the local DSQs of other CPUs. See
2220 	 * direct_dispatch(). Keep popping from the head instead of using
2221 	 * list_for_each_entry_safe() as dispatch_local_dsq() may unlock @rq
2222 	 * temporarily.
2223 	 */
2224 	while ((p = list_first_entry_or_null(&rq->scx.ddsp_deferred_locals,
2225 				struct task_struct, scx.dsq_list.node))) {
2226 		struct scx_sched *sch = scx_root;
2227 		struct scx_dispatch_q *dsq;
2228 
2229 		list_del_init(&p->scx.dsq_list.node);
2230 
2231 		dsq = find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, p);
2232 		if (!WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL))
2233 			dispatch_to_local_dsq(sch, rq, dsq, p,
2234 					      p->scx.ddsp_enq_flags);
2235 	}
2236 }
2237 
2238 static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first)
2239 {
2240 	struct scx_sched *sch = scx_root;
2241 
2242 	if (p->scx.flags & SCX_TASK_QUEUED) {
2243 		/*
2244 		 * Core-sched might decide to execute @p before it is
2245 		 * dispatched. Call ops_dequeue() to notify the BPF scheduler.
2246 		 */
2247 		ops_dequeue(rq, p, SCX_DEQ_CORE_SCHED_EXEC);
2248 		dispatch_dequeue(rq, p);
2249 	}
2250 
2251 	p->se.exec_start = rq_clock_task(rq);
2252 
2253 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2254 	if (SCX_HAS_OP(sch, running) && (p->scx.flags & SCX_TASK_QUEUED))
2255 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, running, rq, p);
2256 
2257 	clr_task_runnable(p, true);
2258 
2259 	/*
2260 	 * @p is getting newly scheduled or got kicked after someone updated its
2261 	 * slice. Refresh whether tick can be stopped. See scx_can_stop_tick().
2262 	 */
2263 	if ((p->scx.slice == SCX_SLICE_INF) !=
2264 	    (bool)(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) {
2265 		if (p->scx.slice == SCX_SLICE_INF)
2266 			rq->scx.flags |= SCX_RQ_CAN_STOP_TICK;
2267 		else
2268 			rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK;
2269 
2270 		sched_update_tick_dependency(rq);
2271 
2272 		/*
2273 		 * For now, let's refresh the load_avgs just when transitioning
2274 		 * in and out of nohz. In the future, we might want to add a
2275 		 * mechanism which calls the following periodically on
2276 		 * tick-stopped CPUs.
2277 		 */
2278 		update_other_load_avgs(rq);
2279 	}
2280 }
2281 
2282 static enum scx_cpu_preempt_reason
2283 preempt_reason_from_class(const struct sched_class *class)
2284 {
2285 	if (class == &stop_sched_class)
2286 		return SCX_CPU_PREEMPT_STOP;
2287 	if (class == &dl_sched_class)
2288 		return SCX_CPU_PREEMPT_DL;
2289 	if (class == &rt_sched_class)
2290 		return SCX_CPU_PREEMPT_RT;
2291 	return SCX_CPU_PREEMPT_UNKNOWN;
2292 }
2293 
2294 static void switch_class(struct rq *rq, struct task_struct *next)
2295 {
2296 	struct scx_sched *sch = scx_root;
2297 	const struct sched_class *next_class = next->sched_class;
2298 
2299 	/*
2300 	 * Pairs with the smp_load_acquire() issued by a CPU in
2301 	 * kick_cpus_irq_workfn() who is waiting for this CPU to perform a
2302 	 * resched.
2303 	 */
2304 	smp_store_release(&rq->scx.pnt_seq, rq->scx.pnt_seq + 1);
2305 	if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT))
2306 		return;
2307 
2308 	/*
2309 	 * The callback is conceptually meant to convey that the CPU is no
2310 	 * longer under the control of SCX. Therefore, don't invoke the callback
2311 	 * if the next class is below SCX (in which case the BPF scheduler has
2312 	 * actively decided not to schedule any tasks on the CPU).
2313 	 */
2314 	if (sched_class_above(&ext_sched_class, next_class))
2315 		return;
2316 
2317 	/*
2318 	 * At this point we know that SCX was preempted by a higher priority
2319 	 * sched_class, so invoke the ->cpu_release() callback if we have not
2320 	 * done so already. We only send the callback once between SCX being
2321 	 * preempted, and it regaining control of the CPU.
2322 	 *
2323 	 * ->cpu_release() complements ->cpu_acquire(), which is emitted the
2324 	 *  next time that balance_scx() is invoked.
2325 	 */
2326 	if (!rq->scx.cpu_released) {
2327 		if (SCX_HAS_OP(sch, cpu_release)) {
2328 			struct scx_cpu_release_args args = {
2329 				.reason = preempt_reason_from_class(next_class),
2330 				.task = next,
2331 			};
2332 
2333 			SCX_CALL_OP(sch, SCX_KF_CPU_RELEASE, cpu_release, rq,
2334 				    cpu_of(rq), &args);
2335 		}
2336 		rq->scx.cpu_released = true;
2337 	}
2338 }
2339 
2340 static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
2341 			      struct task_struct *next)
2342 {
2343 	struct scx_sched *sch = scx_root;
2344 	update_curr_scx(rq);
2345 
2346 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2347 	if (SCX_HAS_OP(sch, stopping) && (p->scx.flags & SCX_TASK_QUEUED))
2348 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, stopping, rq, p, true);
2349 
2350 	if (p->scx.flags & SCX_TASK_QUEUED) {
2351 		set_task_runnable(rq, p);
2352 
2353 		/*
2354 		 * If @p has slice left and is being put, @p is getting
2355 		 * preempted by a higher priority scheduler class or core-sched
2356 		 * forcing a different task. Leave it at the head of the local
2357 		 * DSQ.
2358 		 */
2359 		if (p->scx.slice && !scx_rq_bypassing(rq)) {
2360 			dispatch_enqueue(sch, &rq->scx.local_dsq, p,
2361 					 SCX_ENQ_HEAD);
2362 			goto switch_class;
2363 		}
2364 
2365 		/*
2366 		 * If @p is runnable but we're about to enter a lower
2367 		 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell
2368 		 * ops.enqueue() that @p is the only one available for this cpu,
2369 		 * which should trigger an explicit follow-up scheduling event.
2370 		 */
2371 		if (sched_class_above(&ext_sched_class, next->sched_class)) {
2372 			WARN_ON_ONCE(!(sch->ops.flags & SCX_OPS_ENQ_LAST));
2373 			do_enqueue_task(rq, p, SCX_ENQ_LAST, -1);
2374 		} else {
2375 			do_enqueue_task(rq, p, 0, -1);
2376 		}
2377 	}
2378 
2379 switch_class:
2380 	if (next && next->sched_class != &ext_sched_class)
2381 		switch_class(rq, next);
2382 }
2383 
2384 static struct task_struct *first_local_task(struct rq *rq)
2385 {
2386 	return list_first_entry_or_null(&rq->scx.local_dsq.list,
2387 					struct task_struct, scx.dsq_list.node);
2388 }
2389 
2390 static struct task_struct *pick_task_scx(struct rq *rq)
2391 {
2392 	struct task_struct *prev = rq->curr;
2393 	struct task_struct *p;
2394 	bool keep_prev = rq->scx.flags & SCX_RQ_BAL_KEEP;
2395 	bool kick_idle = false;
2396 
2397 	/*
2398 	 * WORKAROUND:
2399 	 *
2400 	 * %SCX_RQ_BAL_KEEP should be set iff $prev is on SCX as it must just
2401 	 * have gone through balance_scx(). Unfortunately, there currently is a
2402 	 * bug where fair could say yes on balance() but no on pick_task(),
2403 	 * which then ends up calling pick_task_scx() without preceding
2404 	 * balance_scx().
2405 	 *
2406 	 * Keep running @prev if possible and avoid stalling from entering idle
2407 	 * without balancing.
2408 	 *
2409 	 * Once fair is fixed, remove the workaround and trigger WARN_ON_ONCE()
2410 	 * if pick_task_scx() is called without preceding balance_scx().
2411 	 */
2412 	if (unlikely(rq->scx.flags & SCX_RQ_BAL_PENDING)) {
2413 		if (prev->scx.flags & SCX_TASK_QUEUED) {
2414 			keep_prev = true;
2415 		} else {
2416 			keep_prev = false;
2417 			kick_idle = true;
2418 		}
2419 	} else if (unlikely(keep_prev &&
2420 			    prev->sched_class != &ext_sched_class)) {
2421 		/*
2422 		 * Can happen while enabling as SCX_RQ_BAL_PENDING assertion is
2423 		 * conditional on scx_enabled() and may have been skipped.
2424 		 */
2425 		WARN_ON_ONCE(scx_enable_state() == SCX_ENABLED);
2426 		keep_prev = false;
2427 	}
2428 
2429 	/*
2430 	 * If balance_scx() is telling us to keep running @prev, replenish slice
2431 	 * if necessary and keep running @prev. Otherwise, pop the first one
2432 	 * from the local DSQ.
2433 	 */
2434 	if (keep_prev) {
2435 		p = prev;
2436 		if (!p->scx.slice)
2437 			refill_task_slice_dfl(rcu_dereference_sched(scx_root), p);
2438 	} else {
2439 		p = first_local_task(rq);
2440 		if (!p) {
2441 			if (kick_idle)
2442 				scx_kick_cpu(rcu_dereference_sched(scx_root),
2443 					     cpu_of(rq), SCX_KICK_IDLE);
2444 			return NULL;
2445 		}
2446 
2447 		if (unlikely(!p->scx.slice)) {
2448 			struct scx_sched *sch = rcu_dereference_sched(scx_root);
2449 
2450 			if (!scx_rq_bypassing(rq) && !sch->warned_zero_slice) {
2451 				printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in %s()\n",
2452 						p->comm, p->pid, __func__);
2453 				sch->warned_zero_slice = true;
2454 			}
2455 			refill_task_slice_dfl(sch, p);
2456 		}
2457 	}
2458 
2459 	return p;
2460 }
2461 
2462 #ifdef CONFIG_SCHED_CORE
2463 /**
2464  * scx_prio_less - Task ordering for core-sched
2465  * @a: task A
2466  * @b: task B
2467  * @in_fi: in forced idle state
2468  *
2469  * Core-sched is implemented as an additional scheduling layer on top of the
2470  * usual sched_class'es and needs to find out the expected task ordering. For
2471  * SCX, core-sched calls this function to interrogate the task ordering.
2472  *
2473  * Unless overridden by ops.core_sched_before(), @p->scx.core_sched_at is used
2474  * to implement the default task ordering. The older the timestamp, the higher
2475  * priority the task - the global FIFO ordering matching the default scheduling
2476  * behavior.
2477  *
2478  * When ops.core_sched_before() is enabled, @p->scx.core_sched_at is used to
2479  * implement FIFO ordering within each local DSQ. See pick_task_scx().
2480  */
2481 bool scx_prio_less(const struct task_struct *a, const struct task_struct *b,
2482 		   bool in_fi)
2483 {
2484 	struct scx_sched *sch = scx_root;
2485 
2486 	/*
2487 	 * The const qualifiers are dropped from task_struct pointers when
2488 	 * calling ops.core_sched_before(). Accesses are controlled by the
2489 	 * verifier.
2490 	 */
2491 	if (SCX_HAS_OP(sch, core_sched_before) &&
2492 	    !scx_rq_bypassing(task_rq(a)))
2493 		return SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, core_sched_before,
2494 					      NULL,
2495 					      (struct task_struct *)a,
2496 					      (struct task_struct *)b);
2497 	else
2498 		return time_after64(a->scx.core_sched_at, b->scx.core_sched_at);
2499 }
2500 #endif	/* CONFIG_SCHED_CORE */
2501 
2502 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags)
2503 {
2504 	struct scx_sched *sch = scx_root;
2505 	bool rq_bypass;
2506 
2507 	/*
2508 	 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it
2509 	 * can be a good migration opportunity with low cache and memory
2510 	 * footprint. Returning a CPU different than @prev_cpu triggers
2511 	 * immediate rq migration. However, for SCX, as the current rq
2512 	 * association doesn't dictate where the task is going to run, this
2513 	 * doesn't fit well. If necessary, we can later add a dedicated method
2514 	 * which can decide to preempt self to force it through the regular
2515 	 * scheduling path.
2516 	 */
2517 	if (unlikely(wake_flags & WF_EXEC))
2518 		return prev_cpu;
2519 
2520 	rq_bypass = scx_rq_bypassing(task_rq(p));
2521 	if (likely(SCX_HAS_OP(sch, select_cpu)) && !rq_bypass) {
2522 		s32 cpu;
2523 		struct task_struct **ddsp_taskp;
2524 
2525 		ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
2526 		WARN_ON_ONCE(*ddsp_taskp);
2527 		*ddsp_taskp = p;
2528 
2529 		cpu = SCX_CALL_OP_TASK_RET(sch,
2530 					   SCX_KF_ENQUEUE | SCX_KF_SELECT_CPU,
2531 					   select_cpu, NULL, p, prev_cpu,
2532 					   wake_flags);
2533 		p->scx.selected_cpu = cpu;
2534 		*ddsp_taskp = NULL;
2535 		if (ops_cpu_valid(sch, cpu, "from ops.select_cpu()"))
2536 			return cpu;
2537 		else
2538 			return prev_cpu;
2539 	} else {
2540 		s32 cpu;
2541 
2542 		cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, NULL, 0);
2543 		if (cpu >= 0) {
2544 			refill_task_slice_dfl(sch, p);
2545 			p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL;
2546 		} else {
2547 			cpu = prev_cpu;
2548 		}
2549 		p->scx.selected_cpu = cpu;
2550 
2551 		if (rq_bypass)
2552 			__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
2553 		return cpu;
2554 	}
2555 }
2556 
2557 static void task_woken_scx(struct rq *rq, struct task_struct *p)
2558 {
2559 	run_deferred(rq);
2560 }
2561 
2562 static void set_cpus_allowed_scx(struct task_struct *p,
2563 				 struct affinity_context *ac)
2564 {
2565 	struct scx_sched *sch = scx_root;
2566 
2567 	set_cpus_allowed_common(p, ac);
2568 
2569 	/*
2570 	 * The effective cpumask is stored in @p->cpus_ptr which may temporarily
2571 	 * differ from the configured one in @p->cpus_mask. Always tell the bpf
2572 	 * scheduler the effective one.
2573 	 *
2574 	 * Fine-grained memory write control is enforced by BPF making the const
2575 	 * designation pointless. Cast it away when calling the operation.
2576 	 */
2577 	if (SCX_HAS_OP(sch, set_cpumask))
2578 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, NULL,
2579 				 p, (struct cpumask *)p->cpus_ptr);
2580 }
2581 
2582 static void handle_hotplug(struct rq *rq, bool online)
2583 {
2584 	struct scx_sched *sch = scx_root;
2585 	int cpu = cpu_of(rq);
2586 
2587 	atomic_long_inc(&scx_hotplug_seq);
2588 
2589 	/*
2590 	 * scx_root updates are protected by cpus_read_lock() and will stay
2591 	 * stable here. Note that we can't depend on scx_enabled() test as the
2592 	 * hotplug ops need to be enabled before __scx_enabled is set.
2593 	 */
2594 	if (unlikely(!sch))
2595 		return;
2596 
2597 	if (scx_enabled())
2598 		scx_idle_update_selcpu_topology(&sch->ops);
2599 
2600 	if (online && SCX_HAS_OP(sch, cpu_online))
2601 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_online, NULL, cpu);
2602 	else if (!online && SCX_HAS_OP(sch, cpu_offline))
2603 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_offline, NULL, cpu);
2604 	else
2605 		scx_exit(sch, SCX_EXIT_UNREG_KERN,
2606 			 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
2607 			 "cpu %d going %s, exiting scheduler", cpu,
2608 			 online ? "online" : "offline");
2609 }
2610 
2611 void scx_rq_activate(struct rq *rq)
2612 {
2613 	handle_hotplug(rq, true);
2614 }
2615 
2616 void scx_rq_deactivate(struct rq *rq)
2617 {
2618 	handle_hotplug(rq, false);
2619 }
2620 
2621 static void rq_online_scx(struct rq *rq)
2622 {
2623 	rq->scx.flags |= SCX_RQ_ONLINE;
2624 }
2625 
2626 static void rq_offline_scx(struct rq *rq)
2627 {
2628 	rq->scx.flags &= ~SCX_RQ_ONLINE;
2629 }
2630 
2631 
2632 static bool check_rq_for_timeouts(struct rq *rq)
2633 {
2634 	struct scx_sched *sch;
2635 	struct task_struct *p;
2636 	struct rq_flags rf;
2637 	bool timed_out = false;
2638 
2639 	rq_lock_irqsave(rq, &rf);
2640 	sch = rcu_dereference_bh(scx_root);
2641 	if (unlikely(!sch))
2642 		goto out_unlock;
2643 
2644 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) {
2645 		unsigned long last_runnable = p->scx.runnable_at;
2646 
2647 		if (unlikely(time_after(jiffies,
2648 					last_runnable + scx_watchdog_timeout))) {
2649 			u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable);
2650 
2651 			scx_exit(sch, SCX_EXIT_ERROR_STALL, 0,
2652 				 "%s[%d] failed to run for %u.%03us",
2653 				 p->comm, p->pid, dur_ms / 1000, dur_ms % 1000);
2654 			timed_out = true;
2655 			break;
2656 		}
2657 	}
2658 out_unlock:
2659 	rq_unlock_irqrestore(rq, &rf);
2660 	return timed_out;
2661 }
2662 
2663 static void scx_watchdog_workfn(struct work_struct *work)
2664 {
2665 	int cpu;
2666 
2667 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
2668 
2669 	for_each_online_cpu(cpu) {
2670 		if (unlikely(check_rq_for_timeouts(cpu_rq(cpu))))
2671 			break;
2672 
2673 		cond_resched();
2674 	}
2675 	queue_delayed_work(system_unbound_wq, to_delayed_work(work),
2676 			   scx_watchdog_timeout / 2);
2677 }
2678 
2679 void scx_tick(struct rq *rq)
2680 {
2681 	struct scx_sched *sch;
2682 	unsigned long last_check;
2683 
2684 	if (!scx_enabled())
2685 		return;
2686 
2687 	sch = rcu_dereference_bh(scx_root);
2688 	if (unlikely(!sch))
2689 		return;
2690 
2691 	last_check = READ_ONCE(scx_watchdog_timestamp);
2692 	if (unlikely(time_after(jiffies,
2693 				last_check + READ_ONCE(scx_watchdog_timeout)))) {
2694 		u32 dur_ms = jiffies_to_msecs(jiffies - last_check);
2695 
2696 		scx_exit(sch, SCX_EXIT_ERROR_STALL, 0,
2697 			 "watchdog failed to check in for %u.%03us",
2698 			 dur_ms / 1000, dur_ms % 1000);
2699 	}
2700 
2701 	update_other_load_avgs(rq);
2702 }
2703 
2704 static void task_tick_scx(struct rq *rq, struct task_struct *curr, int queued)
2705 {
2706 	struct scx_sched *sch = scx_root;
2707 
2708 	update_curr_scx(rq);
2709 
2710 	/*
2711 	 * While disabling, always resched and refresh core-sched timestamp as
2712 	 * we can't trust the slice management or ops.core_sched_before().
2713 	 */
2714 	if (scx_rq_bypassing(rq)) {
2715 		curr->scx.slice = 0;
2716 		touch_core_sched(rq, curr);
2717 	} else if (SCX_HAS_OP(sch, tick)) {
2718 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, tick, rq, curr);
2719 	}
2720 
2721 	if (!curr->scx.slice)
2722 		resched_curr(rq);
2723 }
2724 
2725 #ifdef CONFIG_EXT_GROUP_SCHED
2726 static struct cgroup *tg_cgrp(struct task_group *tg)
2727 {
2728 	/*
2729 	 * If CGROUP_SCHED is disabled, @tg is NULL. If @tg is an autogroup,
2730 	 * @tg->css.cgroup is NULL. In both cases, @tg can be treated as the
2731 	 * root cgroup.
2732 	 */
2733 	if (tg && tg->css.cgroup)
2734 		return tg->css.cgroup;
2735 	else
2736 		return &cgrp_dfl_root.cgrp;
2737 }
2738 
2739 #define SCX_INIT_TASK_ARGS_CGROUP(tg)		.cgroup = tg_cgrp(tg),
2740 
2741 #else	/* CONFIG_EXT_GROUP_SCHED */
2742 
2743 #define SCX_INIT_TASK_ARGS_CGROUP(tg)
2744 
2745 #endif	/* CONFIG_EXT_GROUP_SCHED */
2746 
2747 static enum scx_task_state scx_get_task_state(const struct task_struct *p)
2748 {
2749 	return (p->scx.flags & SCX_TASK_STATE_MASK) >> SCX_TASK_STATE_SHIFT;
2750 }
2751 
2752 static void scx_set_task_state(struct task_struct *p, enum scx_task_state state)
2753 {
2754 	enum scx_task_state prev_state = scx_get_task_state(p);
2755 	bool warn = false;
2756 
2757 	BUILD_BUG_ON(SCX_TASK_NR_STATES > (1 << SCX_TASK_STATE_BITS));
2758 
2759 	switch (state) {
2760 	case SCX_TASK_NONE:
2761 		break;
2762 	case SCX_TASK_INIT:
2763 		warn = prev_state != SCX_TASK_NONE;
2764 		break;
2765 	case SCX_TASK_READY:
2766 		warn = prev_state == SCX_TASK_NONE;
2767 		break;
2768 	case SCX_TASK_ENABLED:
2769 		warn = prev_state != SCX_TASK_READY;
2770 		break;
2771 	default:
2772 		warn = true;
2773 		return;
2774 	}
2775 
2776 	WARN_ONCE(warn, "sched_ext: Invalid task state transition %d -> %d for %s[%d]",
2777 		  prev_state, state, p->comm, p->pid);
2778 
2779 	p->scx.flags &= ~SCX_TASK_STATE_MASK;
2780 	p->scx.flags |= state << SCX_TASK_STATE_SHIFT;
2781 }
2782 
2783 static int scx_init_task(struct task_struct *p, struct task_group *tg, bool fork)
2784 {
2785 	struct scx_sched *sch = scx_root;
2786 	int ret;
2787 
2788 	p->scx.disallow = false;
2789 
2790 	if (SCX_HAS_OP(sch, init_task)) {
2791 		struct scx_init_task_args args = {
2792 			SCX_INIT_TASK_ARGS_CGROUP(tg)
2793 			.fork = fork,
2794 		};
2795 
2796 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init_task, NULL,
2797 				      p, &args);
2798 		if (unlikely(ret)) {
2799 			ret = ops_sanitize_err(sch, "init_task", ret);
2800 			return ret;
2801 		}
2802 	}
2803 
2804 	scx_set_task_state(p, SCX_TASK_INIT);
2805 
2806 	if (p->scx.disallow) {
2807 		if (!fork) {
2808 			struct rq *rq;
2809 			struct rq_flags rf;
2810 
2811 			rq = task_rq_lock(p, &rf);
2812 
2813 			/*
2814 			 * We're in the load path and @p->policy will be applied
2815 			 * right after. Reverting @p->policy here and rejecting
2816 			 * %SCHED_EXT transitions from scx_check_setscheduler()
2817 			 * guarantees that if ops.init_task() sets @p->disallow,
2818 			 * @p can never be in SCX.
2819 			 */
2820 			if (p->policy == SCHED_EXT) {
2821 				p->policy = SCHED_NORMAL;
2822 				atomic_long_inc(&scx_nr_rejected);
2823 			}
2824 
2825 			task_rq_unlock(rq, p, &rf);
2826 		} else if (p->policy == SCHED_EXT) {
2827 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] during fork",
2828 				  p->comm, p->pid);
2829 		}
2830 	}
2831 
2832 	p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
2833 	return 0;
2834 }
2835 
2836 static void scx_enable_task(struct task_struct *p)
2837 {
2838 	struct scx_sched *sch = scx_root;
2839 	struct rq *rq = task_rq(p);
2840 	u32 weight;
2841 
2842 	lockdep_assert_rq_held(rq);
2843 
2844 	/*
2845 	 * Set the weight before calling ops.enable() so that the scheduler
2846 	 * doesn't see a stale value if they inspect the task struct.
2847 	 */
2848 	if (task_has_idle_policy(p))
2849 		weight = WEIGHT_IDLEPRIO;
2850 	else
2851 		weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO];
2852 
2853 	p->scx.weight = sched_weight_to_cgroup(weight);
2854 
2855 	if (SCX_HAS_OP(sch, enable))
2856 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, enable, rq, p);
2857 	scx_set_task_state(p, SCX_TASK_ENABLED);
2858 
2859 	if (SCX_HAS_OP(sch, set_weight))
2860 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq,
2861 				 p, p->scx.weight);
2862 }
2863 
2864 static void scx_disable_task(struct task_struct *p)
2865 {
2866 	struct scx_sched *sch = scx_root;
2867 	struct rq *rq = task_rq(p);
2868 
2869 	lockdep_assert_rq_held(rq);
2870 	WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED);
2871 
2872 	if (SCX_HAS_OP(sch, disable))
2873 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, disable, rq, p);
2874 	scx_set_task_state(p, SCX_TASK_READY);
2875 }
2876 
2877 static void scx_exit_task(struct task_struct *p)
2878 {
2879 	struct scx_sched *sch = scx_root;
2880 	struct scx_exit_task_args args = {
2881 		.cancelled = false,
2882 	};
2883 
2884 	lockdep_assert_rq_held(task_rq(p));
2885 
2886 	switch (scx_get_task_state(p)) {
2887 	case SCX_TASK_NONE:
2888 		return;
2889 	case SCX_TASK_INIT:
2890 		args.cancelled = true;
2891 		break;
2892 	case SCX_TASK_READY:
2893 		break;
2894 	case SCX_TASK_ENABLED:
2895 		scx_disable_task(p);
2896 		break;
2897 	default:
2898 		WARN_ON_ONCE(true);
2899 		return;
2900 	}
2901 
2902 	if (SCX_HAS_OP(sch, exit_task))
2903 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, exit_task, task_rq(p),
2904 				 p, &args);
2905 	scx_set_task_state(p, SCX_TASK_NONE);
2906 }
2907 
2908 void init_scx_entity(struct sched_ext_entity *scx)
2909 {
2910 	memset(scx, 0, sizeof(*scx));
2911 	INIT_LIST_HEAD(&scx->dsq_list.node);
2912 	RB_CLEAR_NODE(&scx->dsq_priq);
2913 	scx->sticky_cpu = -1;
2914 	scx->holding_cpu = -1;
2915 	INIT_LIST_HEAD(&scx->runnable_node);
2916 	scx->runnable_at = jiffies;
2917 	scx->ddsp_dsq_id = SCX_DSQ_INVALID;
2918 	scx->slice = SCX_SLICE_DFL;
2919 }
2920 
2921 void scx_pre_fork(struct task_struct *p)
2922 {
2923 	/*
2924 	 * BPF scheduler enable/disable paths want to be able to iterate and
2925 	 * update all tasks which can become complex when racing forks. As
2926 	 * enable/disable are very cold paths, let's use a percpu_rwsem to
2927 	 * exclude forks.
2928 	 */
2929 	percpu_down_read(&scx_fork_rwsem);
2930 }
2931 
2932 int scx_fork(struct task_struct *p)
2933 {
2934 	percpu_rwsem_assert_held(&scx_fork_rwsem);
2935 
2936 	if (scx_init_task_enabled)
2937 		return scx_init_task(p, task_group(p), true);
2938 	else
2939 		return 0;
2940 }
2941 
2942 void scx_post_fork(struct task_struct *p)
2943 {
2944 	if (scx_init_task_enabled) {
2945 		scx_set_task_state(p, SCX_TASK_READY);
2946 
2947 		/*
2948 		 * Enable the task immediately if it's running on sched_ext.
2949 		 * Otherwise, it'll be enabled in switching_to_scx() if and
2950 		 * when it's ever configured to run with a SCHED_EXT policy.
2951 		 */
2952 		if (p->sched_class == &ext_sched_class) {
2953 			struct rq_flags rf;
2954 			struct rq *rq;
2955 
2956 			rq = task_rq_lock(p, &rf);
2957 			scx_enable_task(p);
2958 			task_rq_unlock(rq, p, &rf);
2959 		}
2960 	}
2961 
2962 	spin_lock_irq(&scx_tasks_lock);
2963 	list_add_tail(&p->scx.tasks_node, &scx_tasks);
2964 	spin_unlock_irq(&scx_tasks_lock);
2965 
2966 	percpu_up_read(&scx_fork_rwsem);
2967 }
2968 
2969 void scx_cancel_fork(struct task_struct *p)
2970 {
2971 	if (scx_enabled()) {
2972 		struct rq *rq;
2973 		struct rq_flags rf;
2974 
2975 		rq = task_rq_lock(p, &rf);
2976 		WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY);
2977 		scx_exit_task(p);
2978 		task_rq_unlock(rq, p, &rf);
2979 	}
2980 
2981 	percpu_up_read(&scx_fork_rwsem);
2982 }
2983 
2984 void sched_ext_free(struct task_struct *p)
2985 {
2986 	unsigned long flags;
2987 
2988 	spin_lock_irqsave(&scx_tasks_lock, flags);
2989 	list_del_init(&p->scx.tasks_node);
2990 	spin_unlock_irqrestore(&scx_tasks_lock, flags);
2991 
2992 	/*
2993 	 * @p is off scx_tasks and wholly ours. scx_enable()'s READY -> ENABLED
2994 	 * transitions can't race us. Disable ops for @p.
2995 	 */
2996 	if (scx_get_task_state(p) != SCX_TASK_NONE) {
2997 		struct rq_flags rf;
2998 		struct rq *rq;
2999 
3000 		rq = task_rq_lock(p, &rf);
3001 		scx_exit_task(p);
3002 		task_rq_unlock(rq, p, &rf);
3003 	}
3004 }
3005 
3006 static void reweight_task_scx(struct rq *rq, struct task_struct *p,
3007 			      const struct load_weight *lw)
3008 {
3009 	struct scx_sched *sch = scx_root;
3010 
3011 	lockdep_assert_rq_held(task_rq(p));
3012 
3013 	p->scx.weight = sched_weight_to_cgroup(scale_load_down(lw->weight));
3014 	if (SCX_HAS_OP(sch, set_weight))
3015 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq,
3016 				 p, p->scx.weight);
3017 }
3018 
3019 static void prio_changed_scx(struct rq *rq, struct task_struct *p, int oldprio)
3020 {
3021 }
3022 
3023 static void switching_to_scx(struct rq *rq, struct task_struct *p)
3024 {
3025 	struct scx_sched *sch = scx_root;
3026 
3027 	scx_enable_task(p);
3028 
3029 	/*
3030 	 * set_cpus_allowed_scx() is not called while @p is associated with a
3031 	 * different scheduler class. Keep the BPF scheduler up-to-date.
3032 	 */
3033 	if (SCX_HAS_OP(sch, set_cpumask))
3034 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, rq,
3035 				 p, (struct cpumask *)p->cpus_ptr);
3036 }
3037 
3038 static void switched_from_scx(struct rq *rq, struct task_struct *p)
3039 {
3040 	scx_disable_task(p);
3041 }
3042 
3043 static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p,int wake_flags) {}
3044 static void switched_to_scx(struct rq *rq, struct task_struct *p) {}
3045 
3046 int scx_check_setscheduler(struct task_struct *p, int policy)
3047 {
3048 	lockdep_assert_rq_held(task_rq(p));
3049 
3050 	/* if disallow, reject transitioning into SCX */
3051 	if (scx_enabled() && READ_ONCE(p->scx.disallow) &&
3052 	    p->policy != policy && policy == SCHED_EXT)
3053 		return -EACCES;
3054 
3055 	return 0;
3056 }
3057 
3058 #ifdef CONFIG_NO_HZ_FULL
3059 bool scx_can_stop_tick(struct rq *rq)
3060 {
3061 	struct task_struct *p = rq->curr;
3062 
3063 	if (scx_rq_bypassing(rq))
3064 		return false;
3065 
3066 	if (p->sched_class != &ext_sched_class)
3067 		return true;
3068 
3069 	/*
3070 	 * @rq can dispatch from different DSQs, so we can't tell whether it
3071 	 * needs the tick or not by looking at nr_running. Allow stopping ticks
3072 	 * iff the BPF scheduler indicated so. See set_next_task_scx().
3073 	 */
3074 	return rq->scx.flags & SCX_RQ_CAN_STOP_TICK;
3075 }
3076 #endif
3077 
3078 #ifdef CONFIG_EXT_GROUP_SCHED
3079 
3080 DEFINE_STATIC_PERCPU_RWSEM(scx_cgroup_ops_rwsem);
3081 static bool scx_cgroup_enabled;
3082 
3083 void scx_tg_init(struct task_group *tg)
3084 {
3085 	tg->scx.weight = CGROUP_WEIGHT_DFL;
3086 	tg->scx.bw_period_us = default_bw_period_us();
3087 	tg->scx.bw_quota_us = RUNTIME_INF;
3088 	tg->scx.idle = false;
3089 }
3090 
3091 int scx_tg_online(struct task_group *tg)
3092 {
3093 	struct scx_sched *sch = scx_root;
3094 	int ret = 0;
3095 
3096 	WARN_ON_ONCE(tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED));
3097 
3098 	if (scx_cgroup_enabled) {
3099 		if (SCX_HAS_OP(sch, cgroup_init)) {
3100 			struct scx_cgroup_init_args args =
3101 				{ .weight = tg->scx.weight,
3102 				  .bw_period_us = tg->scx.bw_period_us,
3103 				  .bw_quota_us = tg->scx.bw_quota_us,
3104 				  .bw_burst_us = tg->scx.bw_burst_us };
3105 
3106 			ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init,
3107 					      NULL, tg->css.cgroup, &args);
3108 			if (ret)
3109 				ret = ops_sanitize_err(sch, "cgroup_init", ret);
3110 		}
3111 		if (ret == 0)
3112 			tg->scx.flags |= SCX_TG_ONLINE | SCX_TG_INITED;
3113 	} else {
3114 		tg->scx.flags |= SCX_TG_ONLINE;
3115 	}
3116 
3117 	return ret;
3118 }
3119 
3120 void scx_tg_offline(struct task_group *tg)
3121 {
3122 	struct scx_sched *sch = scx_root;
3123 
3124 	WARN_ON_ONCE(!(tg->scx.flags & SCX_TG_ONLINE));
3125 
3126 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_exit) &&
3127 	    (tg->scx.flags & SCX_TG_INITED))
3128 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL,
3129 			    tg->css.cgroup);
3130 	tg->scx.flags &= ~(SCX_TG_ONLINE | SCX_TG_INITED);
3131 }
3132 
3133 int scx_cgroup_can_attach(struct cgroup_taskset *tset)
3134 {
3135 	struct scx_sched *sch = scx_root;
3136 	struct cgroup_subsys_state *css;
3137 	struct task_struct *p;
3138 	int ret;
3139 
3140 	if (!scx_cgroup_enabled)
3141 		return 0;
3142 
3143 	cgroup_taskset_for_each(p, css, tset) {
3144 		struct cgroup *from = tg_cgrp(task_group(p));
3145 		struct cgroup *to = tg_cgrp(css_tg(css));
3146 
3147 		WARN_ON_ONCE(p->scx.cgrp_moving_from);
3148 
3149 		/*
3150 		 * sched_move_task() omits identity migrations. Let's match the
3151 		 * behavior so that ops.cgroup_prep_move() and ops.cgroup_move()
3152 		 * always match one-to-one.
3153 		 */
3154 		if (from == to)
3155 			continue;
3156 
3157 		if (SCX_HAS_OP(sch, cgroup_prep_move)) {
3158 			ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED,
3159 					      cgroup_prep_move, NULL,
3160 					      p, from, css->cgroup);
3161 			if (ret)
3162 				goto err;
3163 		}
3164 
3165 		p->scx.cgrp_moving_from = from;
3166 	}
3167 
3168 	return 0;
3169 
3170 err:
3171 	cgroup_taskset_for_each(p, css, tset) {
3172 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
3173 		    p->scx.cgrp_moving_from)
3174 			SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL,
3175 				    p, p->scx.cgrp_moving_from, css->cgroup);
3176 		p->scx.cgrp_moving_from = NULL;
3177 	}
3178 
3179 	return ops_sanitize_err(sch, "cgroup_prep_move", ret);
3180 }
3181 
3182 void scx_cgroup_move_task(struct task_struct *p)
3183 {
3184 	struct scx_sched *sch = scx_root;
3185 
3186 	if (!scx_cgroup_enabled)
3187 		return;
3188 
3189 	/*
3190 	 * @p must have ops.cgroup_prep_move() called on it and thus
3191 	 * cgrp_moving_from set.
3192 	 */
3193 	if (SCX_HAS_OP(sch, cgroup_move) &&
3194 	    !WARN_ON_ONCE(!p->scx.cgrp_moving_from))
3195 		SCX_CALL_OP_TASK(sch, SCX_KF_UNLOCKED, cgroup_move, NULL,
3196 				 p, p->scx.cgrp_moving_from,
3197 				 tg_cgrp(task_group(p)));
3198 	p->scx.cgrp_moving_from = NULL;
3199 }
3200 
3201 void scx_cgroup_cancel_attach(struct cgroup_taskset *tset)
3202 {
3203 	struct scx_sched *sch = scx_root;
3204 	struct cgroup_subsys_state *css;
3205 	struct task_struct *p;
3206 
3207 	if (!scx_cgroup_enabled)
3208 		return;
3209 
3210 	cgroup_taskset_for_each(p, css, tset) {
3211 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
3212 		    p->scx.cgrp_moving_from)
3213 			SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL,
3214 				    p, p->scx.cgrp_moving_from, css->cgroup);
3215 		p->scx.cgrp_moving_from = NULL;
3216 	}
3217 }
3218 
3219 void scx_group_set_weight(struct task_group *tg, unsigned long weight)
3220 {
3221 	struct scx_sched *sch = scx_root;
3222 
3223 	percpu_down_read(&scx_cgroup_ops_rwsem);
3224 
3225 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_weight) &&
3226 	    tg->scx.weight != weight)
3227 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_weight, NULL,
3228 			    tg_cgrp(tg), weight);
3229 
3230 	tg->scx.weight = weight;
3231 
3232 	percpu_up_read(&scx_cgroup_ops_rwsem);
3233 }
3234 
3235 void scx_group_set_idle(struct task_group *tg, bool idle)
3236 {
3237 	struct scx_sched *sch = scx_root;
3238 
3239 	percpu_down_read(&scx_cgroup_ops_rwsem);
3240 
3241 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_idle))
3242 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_idle, NULL,
3243 			    tg_cgrp(tg), idle);
3244 
3245 	/* Update the task group's idle state */
3246 	tg->scx.idle = idle;
3247 
3248 	percpu_up_read(&scx_cgroup_ops_rwsem);
3249 }
3250 
3251 void scx_group_set_bandwidth(struct task_group *tg,
3252 			     u64 period_us, u64 quota_us, u64 burst_us)
3253 {
3254 	struct scx_sched *sch = scx_root;
3255 
3256 	percpu_down_read(&scx_cgroup_ops_rwsem);
3257 
3258 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_bandwidth) &&
3259 	    (tg->scx.bw_period_us != period_us ||
3260 	     tg->scx.bw_quota_us != quota_us ||
3261 	     tg->scx.bw_burst_us != burst_us))
3262 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_bandwidth, NULL,
3263 			    tg_cgrp(tg), period_us, quota_us, burst_us);
3264 
3265 	tg->scx.bw_period_us = period_us;
3266 	tg->scx.bw_quota_us = quota_us;
3267 	tg->scx.bw_burst_us = burst_us;
3268 
3269 	percpu_up_read(&scx_cgroup_ops_rwsem);
3270 }
3271 
3272 static void scx_cgroup_lock(void)
3273 {
3274 	percpu_down_write(&scx_cgroup_ops_rwsem);
3275 	cgroup_lock();
3276 }
3277 
3278 static void scx_cgroup_unlock(void)
3279 {
3280 	cgroup_unlock();
3281 	percpu_up_write(&scx_cgroup_ops_rwsem);
3282 }
3283 
3284 #else	/* CONFIG_EXT_GROUP_SCHED */
3285 
3286 static void scx_cgroup_lock(void) {}
3287 static void scx_cgroup_unlock(void) {}
3288 
3289 #endif	/* CONFIG_EXT_GROUP_SCHED */
3290 
3291 /*
3292  * Omitted operations:
3293  *
3294  * - wakeup_preempt: NOOP as it isn't useful in the wakeup path because the task
3295  *   isn't tied to the CPU at that point. Preemption is implemented by resetting
3296  *   the victim task's slice to 0 and triggering reschedule on the target CPU.
3297  *
3298  * - migrate_task_rq: Unnecessary as task to cpu mapping is transient.
3299  *
3300  * - task_fork/dead: We need fork/dead notifications for all tasks regardless of
3301  *   their current sched_class. Call them directly from sched core instead.
3302  */
3303 DEFINE_SCHED_CLASS(ext) = {
3304 	.enqueue_task		= enqueue_task_scx,
3305 	.dequeue_task		= dequeue_task_scx,
3306 	.yield_task		= yield_task_scx,
3307 	.yield_to_task		= yield_to_task_scx,
3308 
3309 	.wakeup_preempt		= wakeup_preempt_scx,
3310 
3311 	.balance		= balance_scx,
3312 	.pick_task		= pick_task_scx,
3313 
3314 	.put_prev_task		= put_prev_task_scx,
3315 	.set_next_task		= set_next_task_scx,
3316 
3317 	.select_task_rq		= select_task_rq_scx,
3318 	.task_woken		= task_woken_scx,
3319 	.set_cpus_allowed	= set_cpus_allowed_scx,
3320 
3321 	.rq_online		= rq_online_scx,
3322 	.rq_offline		= rq_offline_scx,
3323 
3324 	.task_tick		= task_tick_scx,
3325 
3326 	.switching_to		= switching_to_scx,
3327 	.switched_from		= switched_from_scx,
3328 	.switched_to		= switched_to_scx,
3329 	.reweight_task		= reweight_task_scx,
3330 	.prio_changed		= prio_changed_scx,
3331 
3332 	.update_curr		= update_curr_scx,
3333 
3334 #ifdef CONFIG_UCLAMP_TASK
3335 	.uclamp_enabled		= 1,
3336 #endif
3337 };
3338 
3339 static void init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id)
3340 {
3341 	memset(dsq, 0, sizeof(*dsq));
3342 
3343 	raw_spin_lock_init(&dsq->lock);
3344 	INIT_LIST_HEAD(&dsq->list);
3345 	dsq->id = dsq_id;
3346 }
3347 
3348 static void free_dsq_irq_workfn(struct irq_work *irq_work)
3349 {
3350 	struct llist_node *to_free = llist_del_all(&dsqs_to_free);
3351 	struct scx_dispatch_q *dsq, *tmp_dsq;
3352 
3353 	llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node)
3354 		kfree_rcu(dsq, rcu);
3355 }
3356 
3357 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn);
3358 
3359 static void destroy_dsq(struct scx_sched *sch, u64 dsq_id)
3360 {
3361 	struct scx_dispatch_q *dsq;
3362 	unsigned long flags;
3363 
3364 	rcu_read_lock();
3365 
3366 	dsq = find_user_dsq(sch, dsq_id);
3367 	if (!dsq)
3368 		goto out_unlock_rcu;
3369 
3370 	raw_spin_lock_irqsave(&dsq->lock, flags);
3371 
3372 	if (dsq->nr) {
3373 		scx_error(sch, "attempting to destroy in-use dsq 0x%016llx (nr=%u)",
3374 			  dsq->id, dsq->nr);
3375 		goto out_unlock_dsq;
3376 	}
3377 
3378 	if (rhashtable_remove_fast(&sch->dsq_hash, &dsq->hash_node,
3379 				   dsq_hash_params))
3380 		goto out_unlock_dsq;
3381 
3382 	/*
3383 	 * Mark dead by invalidating ->id to prevent dispatch_enqueue() from
3384 	 * queueing more tasks. As this function can be called from anywhere,
3385 	 * freeing is bounced through an irq work to avoid nesting RCU
3386 	 * operations inside scheduler locks.
3387 	 */
3388 	dsq->id = SCX_DSQ_INVALID;
3389 	llist_add(&dsq->free_node, &dsqs_to_free);
3390 	irq_work_queue(&free_dsq_irq_work);
3391 
3392 out_unlock_dsq:
3393 	raw_spin_unlock_irqrestore(&dsq->lock, flags);
3394 out_unlock_rcu:
3395 	rcu_read_unlock();
3396 }
3397 
3398 #ifdef CONFIG_EXT_GROUP_SCHED
3399 static void scx_cgroup_exit(struct scx_sched *sch)
3400 {
3401 	struct cgroup_subsys_state *css;
3402 
3403 	scx_cgroup_enabled = false;
3404 
3405 	/*
3406 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
3407 	 * cgroups and exit all the inited ones, all online cgroups are exited.
3408 	 */
3409 	css_for_each_descendant_post(css, &root_task_group.css) {
3410 		struct task_group *tg = css_tg(css);
3411 
3412 		if (!(tg->scx.flags & SCX_TG_INITED))
3413 			continue;
3414 		tg->scx.flags &= ~SCX_TG_INITED;
3415 
3416 		if (!sch->ops.cgroup_exit)
3417 			continue;
3418 
3419 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL,
3420 			    css->cgroup);
3421 	}
3422 }
3423 
3424 static int scx_cgroup_init(struct scx_sched *sch)
3425 {
3426 	struct cgroup_subsys_state *css;
3427 	int ret;
3428 
3429 	/*
3430 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
3431 	 * cgroups and init, all online cgroups are initialized.
3432 	 */
3433 	css_for_each_descendant_pre(css, &root_task_group.css) {
3434 		struct task_group *tg = css_tg(css);
3435 		struct scx_cgroup_init_args args = {
3436 			.weight = tg->scx.weight,
3437 			.bw_period_us = tg->scx.bw_period_us,
3438 			.bw_quota_us = tg->scx.bw_quota_us,
3439 			.bw_burst_us = tg->scx.bw_burst_us,
3440 		};
3441 
3442 		if ((tg->scx.flags &
3443 		     (SCX_TG_ONLINE | SCX_TG_INITED)) != SCX_TG_ONLINE)
3444 			continue;
3445 
3446 		if (!sch->ops.cgroup_init) {
3447 			tg->scx.flags |= SCX_TG_INITED;
3448 			continue;
3449 		}
3450 
3451 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init, NULL,
3452 				      css->cgroup, &args);
3453 		if (ret) {
3454 			css_put(css);
3455 			scx_error(sch, "ops.cgroup_init() failed (%d)", ret);
3456 			return ret;
3457 		}
3458 		tg->scx.flags |= SCX_TG_INITED;
3459 	}
3460 
3461 	WARN_ON_ONCE(scx_cgroup_enabled);
3462 	scx_cgroup_enabled = true;
3463 
3464 	return 0;
3465 }
3466 
3467 #else
3468 static void scx_cgroup_exit(struct scx_sched *sch) {}
3469 static int scx_cgroup_init(struct scx_sched *sch) { return 0; }
3470 #endif
3471 
3472 
3473 /********************************************************************************
3474  * Sysfs interface and ops enable/disable.
3475  */
3476 
3477 #define SCX_ATTR(_name)								\
3478 	static struct kobj_attribute scx_attr_##_name = {			\
3479 		.attr = { .name = __stringify(_name), .mode = 0444 },		\
3480 		.show = scx_attr_##_name##_show,				\
3481 	}
3482 
3483 static ssize_t scx_attr_state_show(struct kobject *kobj,
3484 				   struct kobj_attribute *ka, char *buf)
3485 {
3486 	return sysfs_emit(buf, "%s\n", scx_enable_state_str[scx_enable_state()]);
3487 }
3488 SCX_ATTR(state);
3489 
3490 static ssize_t scx_attr_switch_all_show(struct kobject *kobj,
3491 					struct kobj_attribute *ka, char *buf)
3492 {
3493 	return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all));
3494 }
3495 SCX_ATTR(switch_all);
3496 
3497 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj,
3498 					 struct kobj_attribute *ka, char *buf)
3499 {
3500 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected));
3501 }
3502 SCX_ATTR(nr_rejected);
3503 
3504 static ssize_t scx_attr_hotplug_seq_show(struct kobject *kobj,
3505 					 struct kobj_attribute *ka, char *buf)
3506 {
3507 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_hotplug_seq));
3508 }
3509 SCX_ATTR(hotplug_seq);
3510 
3511 static ssize_t scx_attr_enable_seq_show(struct kobject *kobj,
3512 					struct kobj_attribute *ka, char *buf)
3513 {
3514 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_enable_seq));
3515 }
3516 SCX_ATTR(enable_seq);
3517 
3518 static struct attribute *scx_global_attrs[] = {
3519 	&scx_attr_state.attr,
3520 	&scx_attr_switch_all.attr,
3521 	&scx_attr_nr_rejected.attr,
3522 	&scx_attr_hotplug_seq.attr,
3523 	&scx_attr_enable_seq.attr,
3524 	NULL,
3525 };
3526 
3527 static const struct attribute_group scx_global_attr_group = {
3528 	.attrs = scx_global_attrs,
3529 };
3530 
3531 static void free_exit_info(struct scx_exit_info *ei);
3532 
3533 static void scx_sched_free_rcu_work(struct work_struct *work)
3534 {
3535 	struct rcu_work *rcu_work = to_rcu_work(work);
3536 	struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work);
3537 	struct rhashtable_iter rht_iter;
3538 	struct scx_dispatch_q *dsq;
3539 	int node;
3540 
3541 	irq_work_sync(&sch->error_irq_work);
3542 	kthread_stop(sch->helper->task);
3543 
3544 	free_percpu(sch->pcpu);
3545 
3546 	for_each_node_state(node, N_POSSIBLE)
3547 		kfree(sch->global_dsqs[node]);
3548 	kfree(sch->global_dsqs);
3549 
3550 	rhashtable_walk_enter(&sch->dsq_hash, &rht_iter);
3551 	do {
3552 		rhashtable_walk_start(&rht_iter);
3553 
3554 		while ((dsq = rhashtable_walk_next(&rht_iter)) && !IS_ERR(dsq))
3555 			destroy_dsq(sch, dsq->id);
3556 
3557 		rhashtable_walk_stop(&rht_iter);
3558 	} while (dsq == ERR_PTR(-EAGAIN));
3559 	rhashtable_walk_exit(&rht_iter);
3560 
3561 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
3562 	free_exit_info(sch->exit_info);
3563 	kfree(sch);
3564 }
3565 
3566 static void scx_kobj_release(struct kobject *kobj)
3567 {
3568 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
3569 
3570 	INIT_RCU_WORK(&sch->rcu_work, scx_sched_free_rcu_work);
3571 	queue_rcu_work(system_unbound_wq, &sch->rcu_work);
3572 }
3573 
3574 static ssize_t scx_attr_ops_show(struct kobject *kobj,
3575 				 struct kobj_attribute *ka, char *buf)
3576 {
3577 	return sysfs_emit(buf, "%s\n", scx_root->ops.name);
3578 }
3579 SCX_ATTR(ops);
3580 
3581 #define scx_attr_event_show(buf, at, events, kind) ({				\
3582 	sysfs_emit_at(buf, at, "%s %llu\n", #kind, (events)->kind);		\
3583 })
3584 
3585 static ssize_t scx_attr_events_show(struct kobject *kobj,
3586 				    struct kobj_attribute *ka, char *buf)
3587 {
3588 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
3589 	struct scx_event_stats events;
3590 	int at = 0;
3591 
3592 	scx_read_events(sch, &events);
3593 	at += scx_attr_event_show(buf, at, &events, SCX_EV_SELECT_CPU_FALLBACK);
3594 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
3595 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_KEEP_LAST);
3596 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_EXITING);
3597 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
3598 	at += scx_attr_event_show(buf, at, &events, SCX_EV_REFILL_SLICE_DFL);
3599 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DURATION);
3600 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DISPATCH);
3601 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_ACTIVATE);
3602 	return at;
3603 }
3604 SCX_ATTR(events);
3605 
3606 static struct attribute *scx_sched_attrs[] = {
3607 	&scx_attr_ops.attr,
3608 	&scx_attr_events.attr,
3609 	NULL,
3610 };
3611 ATTRIBUTE_GROUPS(scx_sched);
3612 
3613 static const struct kobj_type scx_ktype = {
3614 	.release = scx_kobj_release,
3615 	.sysfs_ops = &kobj_sysfs_ops,
3616 	.default_groups = scx_sched_groups,
3617 };
3618 
3619 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
3620 {
3621 	return add_uevent_var(env, "SCXOPS=%s", scx_root->ops.name);
3622 }
3623 
3624 static const struct kset_uevent_ops scx_uevent_ops = {
3625 	.uevent = scx_uevent,
3626 };
3627 
3628 /*
3629  * Used by sched_fork() and __setscheduler_prio() to pick the matching
3630  * sched_class. dl/rt are already handled.
3631  */
3632 bool task_should_scx(int policy)
3633 {
3634 	if (!scx_enabled() || unlikely(scx_enable_state() == SCX_DISABLING))
3635 		return false;
3636 	if (READ_ONCE(scx_switching_all))
3637 		return true;
3638 	return policy == SCHED_EXT;
3639 }
3640 
3641 bool scx_allow_ttwu_queue(const struct task_struct *p)
3642 {
3643 	struct scx_sched *sch;
3644 
3645 	if (!scx_enabled())
3646 		return true;
3647 
3648 	sch = rcu_dereference_sched(scx_root);
3649 	if (unlikely(!sch))
3650 		return true;
3651 
3652 	if (sch->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP)
3653 		return true;
3654 
3655 	if (unlikely(p->sched_class != &ext_sched_class))
3656 		return true;
3657 
3658 	return false;
3659 }
3660 
3661 /**
3662  * scx_rcu_cpu_stall - sched_ext RCU CPU stall handler
3663  *
3664  * While there are various reasons why RCU CPU stalls can occur on a system
3665  * that may not be caused by the current BPF scheduler, try kicking out the
3666  * current scheduler in an attempt to recover the system to a good state before
3667  * issuing panics.
3668  */
3669 bool scx_rcu_cpu_stall(void)
3670 {
3671 	struct scx_sched *sch;
3672 
3673 	rcu_read_lock();
3674 
3675 	sch = rcu_dereference(scx_root);
3676 	if (unlikely(!sch)) {
3677 		rcu_read_unlock();
3678 		return false;
3679 	}
3680 
3681 	switch (scx_enable_state()) {
3682 	case SCX_ENABLING:
3683 	case SCX_ENABLED:
3684 		break;
3685 	default:
3686 		rcu_read_unlock();
3687 		return false;
3688 	}
3689 
3690 	scx_error(sch, "RCU CPU stall detected!");
3691 	rcu_read_unlock();
3692 
3693 	return true;
3694 }
3695 
3696 /**
3697  * scx_softlockup - sched_ext softlockup handler
3698  * @dur_s: number of seconds of CPU stuck due to soft lockup
3699  *
3700  * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can
3701  * live-lock the system by making many CPUs target the same DSQ to the point
3702  * where soft-lockup detection triggers. This function is called from
3703  * soft-lockup watchdog when the triggering point is close and tries to unjam
3704  * the system by enabling the breather and aborting the BPF scheduler.
3705  */
3706 void scx_softlockup(u32 dur_s)
3707 {
3708 	struct scx_sched *sch;
3709 
3710 	rcu_read_lock();
3711 
3712 	sch = rcu_dereference(scx_root);
3713 	if (unlikely(!sch))
3714 		goto out_unlock;
3715 
3716 	switch (scx_enable_state()) {
3717 	case SCX_ENABLING:
3718 	case SCX_ENABLED:
3719 		break;
3720 	default:
3721 		goto out_unlock;
3722 	}
3723 
3724 	/* allow only one instance, cleared at the end of scx_bypass() */
3725 	if (test_and_set_bit(0, &scx_in_softlockup))
3726 		goto out_unlock;
3727 
3728 	printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU%d stuck for %us, disabling \"%s\"\n",
3729 			smp_processor_id(), dur_s, scx_root->ops.name);
3730 
3731 	/*
3732 	 * Some CPUs may be trapped in the dispatch paths. Enable breather
3733 	 * immediately; otherwise, we might even be able to get to scx_bypass().
3734 	 */
3735 	atomic_inc(&scx_breather_depth);
3736 
3737 	scx_error(sch, "soft lockup - CPU#%d stuck for %us", smp_processor_id(), dur_s);
3738 out_unlock:
3739 	rcu_read_unlock();
3740 }
3741 
3742 static void scx_clear_softlockup(void)
3743 {
3744 	if (test_and_clear_bit(0, &scx_in_softlockup))
3745 		atomic_dec(&scx_breather_depth);
3746 }
3747 
3748 /**
3749  * scx_bypass - [Un]bypass scx_ops and guarantee forward progress
3750  * @bypass: true for bypass, false for unbypass
3751  *
3752  * Bypassing guarantees that all runnable tasks make forward progress without
3753  * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might
3754  * be held by tasks that the BPF scheduler is forgetting to run, which
3755  * unfortunately also excludes toggling the static branches.
3756  *
3757  * Let's work around by overriding a couple ops and modifying behaviors based on
3758  * the DISABLING state and then cycling the queued tasks through dequeue/enqueue
3759  * to force global FIFO scheduling.
3760  *
3761  * - ops.select_cpu() is ignored and the default select_cpu() is used.
3762  *
3763  * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order.
3764  *   %SCX_OPS_ENQ_LAST is also ignored.
3765  *
3766  * - ops.dispatch() is ignored.
3767  *
3768  * - balance_scx() does not set %SCX_RQ_BAL_KEEP on non-zero slice as slice
3769  *   can't be trusted. Whenever a tick triggers, the running task is rotated to
3770  *   the tail of the queue with core_sched_at touched.
3771  *
3772  * - pick_next_task() suppresses zero slice warning.
3773  *
3774  * - scx_kick_cpu() is disabled to avoid irq_work malfunction during PM
3775  *   operations.
3776  *
3777  * - scx_prio_less() reverts to the default core_sched_at order.
3778  */
3779 static void scx_bypass(bool bypass)
3780 {
3781 	static DEFINE_RAW_SPINLOCK(bypass_lock);
3782 	static unsigned long bypass_timestamp;
3783 	struct scx_sched *sch;
3784 	unsigned long flags;
3785 	int cpu;
3786 
3787 	raw_spin_lock_irqsave(&bypass_lock, flags);
3788 	sch = rcu_dereference_bh(scx_root);
3789 
3790 	if (bypass) {
3791 		scx_bypass_depth++;
3792 		WARN_ON_ONCE(scx_bypass_depth <= 0);
3793 		if (scx_bypass_depth != 1)
3794 			goto unlock;
3795 		bypass_timestamp = ktime_get_ns();
3796 		if (sch)
3797 			scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1);
3798 	} else {
3799 		scx_bypass_depth--;
3800 		WARN_ON_ONCE(scx_bypass_depth < 0);
3801 		if (scx_bypass_depth != 0)
3802 			goto unlock;
3803 		if (sch)
3804 			scx_add_event(sch, SCX_EV_BYPASS_DURATION,
3805 				      ktime_get_ns() - bypass_timestamp);
3806 	}
3807 
3808 	atomic_inc(&scx_breather_depth);
3809 
3810 	/*
3811 	 * No task property is changing. We just need to make sure all currently
3812 	 * queued tasks are re-queued according to the new scx_rq_bypassing()
3813 	 * state. As an optimization, walk each rq's runnable_list instead of
3814 	 * the scx_tasks list.
3815 	 *
3816 	 * This function can't trust the scheduler and thus can't use
3817 	 * cpus_read_lock(). Walk all possible CPUs instead of online.
3818 	 */
3819 	for_each_possible_cpu(cpu) {
3820 		struct rq *rq = cpu_rq(cpu);
3821 		struct task_struct *p, *n;
3822 
3823 		raw_spin_rq_lock(rq);
3824 
3825 		if (bypass) {
3826 			WARN_ON_ONCE(rq->scx.flags & SCX_RQ_BYPASSING);
3827 			rq->scx.flags |= SCX_RQ_BYPASSING;
3828 		} else {
3829 			WARN_ON_ONCE(!(rq->scx.flags & SCX_RQ_BYPASSING));
3830 			rq->scx.flags &= ~SCX_RQ_BYPASSING;
3831 		}
3832 
3833 		/*
3834 		 * We need to guarantee that no tasks are on the BPF scheduler
3835 		 * while bypassing. Either we see enabled or the enable path
3836 		 * sees scx_rq_bypassing() before moving tasks to SCX.
3837 		 */
3838 		if (!scx_enabled()) {
3839 			raw_spin_rq_unlock(rq);
3840 			continue;
3841 		}
3842 
3843 		/*
3844 		 * The use of list_for_each_entry_safe_reverse() is required
3845 		 * because each task is going to be removed from and added back
3846 		 * to the runnable_list during iteration. Because they're added
3847 		 * to the tail of the list, safe reverse iteration can still
3848 		 * visit all nodes.
3849 		 */
3850 		list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list,
3851 						 scx.runnable_node) {
3852 			struct sched_enq_and_set_ctx ctx;
3853 
3854 			/* cycling deq/enq is enough, see the function comment */
3855 			sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
3856 			sched_enq_and_set_task(&ctx);
3857 		}
3858 
3859 		/* resched to restore ticks and idle state */
3860 		if (cpu_online(cpu) || cpu == smp_processor_id())
3861 			resched_curr(rq);
3862 
3863 		raw_spin_rq_unlock(rq);
3864 	}
3865 
3866 	atomic_dec(&scx_breather_depth);
3867 unlock:
3868 	raw_spin_unlock_irqrestore(&bypass_lock, flags);
3869 	scx_clear_softlockup();
3870 }
3871 
3872 static void free_exit_info(struct scx_exit_info *ei)
3873 {
3874 	kvfree(ei->dump);
3875 	kfree(ei->msg);
3876 	kfree(ei->bt);
3877 	kfree(ei);
3878 }
3879 
3880 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
3881 {
3882 	struct scx_exit_info *ei;
3883 
3884 	ei = kzalloc(sizeof(*ei), GFP_KERNEL);
3885 	if (!ei)
3886 		return NULL;
3887 
3888 	ei->bt = kcalloc(SCX_EXIT_BT_LEN, sizeof(ei->bt[0]), GFP_KERNEL);
3889 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
3890 	ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL);
3891 
3892 	if (!ei->bt || !ei->msg || !ei->dump) {
3893 		free_exit_info(ei);
3894 		return NULL;
3895 	}
3896 
3897 	return ei;
3898 }
3899 
3900 static const char *scx_exit_reason(enum scx_exit_kind kind)
3901 {
3902 	switch (kind) {
3903 	case SCX_EXIT_UNREG:
3904 		return "unregistered from user space";
3905 	case SCX_EXIT_UNREG_BPF:
3906 		return "unregistered from BPF";
3907 	case SCX_EXIT_UNREG_KERN:
3908 		return "unregistered from the main kernel";
3909 	case SCX_EXIT_SYSRQ:
3910 		return "disabled by sysrq-S";
3911 	case SCX_EXIT_ERROR:
3912 		return "runtime error";
3913 	case SCX_EXIT_ERROR_BPF:
3914 		return "scx_bpf_error";
3915 	case SCX_EXIT_ERROR_STALL:
3916 		return "runnable task stall";
3917 	default:
3918 		return "<UNKNOWN>";
3919 	}
3920 }
3921 
3922 static void free_kick_pseqs_rcu(struct rcu_head *rcu)
3923 {
3924 	struct scx_kick_pseqs *pseqs = container_of(rcu, struct scx_kick_pseqs, rcu);
3925 
3926 	kvfree(pseqs);
3927 }
3928 
3929 static void free_kick_pseqs(void)
3930 {
3931 	int cpu;
3932 
3933 	for_each_possible_cpu(cpu) {
3934 		struct scx_kick_pseqs **pseqs = per_cpu_ptr(&scx_kick_pseqs, cpu);
3935 		struct scx_kick_pseqs *to_free;
3936 
3937 		to_free = rcu_replace_pointer(*pseqs, NULL, true);
3938 		if (to_free)
3939 			call_rcu(&to_free->rcu, free_kick_pseqs_rcu);
3940 	}
3941 }
3942 
3943 static void scx_disable_workfn(struct kthread_work *work)
3944 {
3945 	struct scx_sched *sch = container_of(work, struct scx_sched, disable_work);
3946 	struct scx_exit_info *ei = sch->exit_info;
3947 	struct scx_task_iter sti;
3948 	struct task_struct *p;
3949 	int kind, cpu;
3950 
3951 	kind = atomic_read(&sch->exit_kind);
3952 	while (true) {
3953 		if (kind == SCX_EXIT_DONE)	/* already disabled? */
3954 			return;
3955 		WARN_ON_ONCE(kind == SCX_EXIT_NONE);
3956 		if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE))
3957 			break;
3958 	}
3959 	ei->kind = kind;
3960 	ei->reason = scx_exit_reason(ei->kind);
3961 
3962 	/* guarantee forward progress by bypassing scx_ops */
3963 	scx_bypass(true);
3964 
3965 	switch (scx_set_enable_state(SCX_DISABLING)) {
3966 	case SCX_DISABLING:
3967 		WARN_ONCE(true, "sched_ext: duplicate disabling instance?");
3968 		break;
3969 	case SCX_DISABLED:
3970 		pr_warn("sched_ext: ops error detected without ops (%s)\n",
3971 			sch->exit_info->msg);
3972 		WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
3973 		goto done;
3974 	default:
3975 		break;
3976 	}
3977 
3978 	/*
3979 	 * Here, every runnable task is guaranteed to make forward progress and
3980 	 * we can safely use blocking synchronization constructs. Actually
3981 	 * disable ops.
3982 	 */
3983 	mutex_lock(&scx_enable_mutex);
3984 
3985 	static_branch_disable(&__scx_switched_all);
3986 	WRITE_ONCE(scx_switching_all, false);
3987 
3988 	/*
3989 	 * Shut down cgroup support before tasks so that the cgroup attach path
3990 	 * doesn't race against scx_exit_task().
3991 	 */
3992 	scx_cgroup_lock();
3993 	scx_cgroup_exit(sch);
3994 	scx_cgroup_unlock();
3995 
3996 	/*
3997 	 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones
3998 	 * must be switched out and exited synchronously.
3999 	 */
4000 	percpu_down_write(&scx_fork_rwsem);
4001 
4002 	scx_init_task_enabled = false;
4003 
4004 	scx_task_iter_start(&sti);
4005 	while ((p = scx_task_iter_next_locked(&sti))) {
4006 		const struct sched_class *old_class = p->sched_class;
4007 		const struct sched_class *new_class =
4008 			__setscheduler_class(p->policy, p->prio);
4009 		struct sched_enq_and_set_ctx ctx;
4010 
4011 		if (old_class != new_class && p->se.sched_delayed)
4012 			dequeue_task(task_rq(p), p, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
4013 
4014 		sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
4015 
4016 		p->sched_class = new_class;
4017 		check_class_changing(task_rq(p), p, old_class);
4018 
4019 		sched_enq_and_set_task(&ctx);
4020 
4021 		check_class_changed(task_rq(p), p, old_class, p->prio);
4022 		scx_exit_task(p);
4023 	}
4024 	scx_task_iter_stop(&sti);
4025 	percpu_up_write(&scx_fork_rwsem);
4026 
4027 	/*
4028 	 * Invalidate all the rq clocks to prevent getting outdated
4029 	 * rq clocks from a previous scx scheduler.
4030 	 */
4031 	for_each_possible_cpu(cpu) {
4032 		struct rq *rq = cpu_rq(cpu);
4033 		scx_rq_clock_invalidate(rq);
4034 	}
4035 
4036 	/* no task is on scx, turn off all the switches and flush in-progress calls */
4037 	static_branch_disable(&__scx_enabled);
4038 	bitmap_zero(sch->has_op, SCX_OPI_END);
4039 	scx_idle_disable();
4040 	synchronize_rcu();
4041 
4042 	if (ei->kind >= SCX_EXIT_ERROR) {
4043 		pr_err("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
4044 		       sch->ops.name, ei->reason);
4045 
4046 		if (ei->msg[0] != '\0')
4047 			pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg);
4048 #ifdef CONFIG_STACKTRACE
4049 		stack_trace_print(ei->bt, ei->bt_len, 2);
4050 #endif
4051 	} else {
4052 		pr_info("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
4053 			sch->ops.name, ei->reason);
4054 	}
4055 
4056 	if (sch->ops.exit)
4057 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, exit, NULL, ei);
4058 
4059 	cancel_delayed_work_sync(&scx_watchdog_work);
4060 
4061 	/*
4062 	 * scx_root clearing must be inside cpus_read_lock(). See
4063 	 * handle_hotplug().
4064 	 */
4065 	cpus_read_lock();
4066 	RCU_INIT_POINTER(scx_root, NULL);
4067 	cpus_read_unlock();
4068 
4069 	/*
4070 	 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs
4071 	 * could observe an object of the same name still in the hierarchy when
4072 	 * the next scheduler is loaded.
4073 	 */
4074 	kobject_del(&sch->kobj);
4075 
4076 	free_percpu(scx_dsp_ctx);
4077 	scx_dsp_ctx = NULL;
4078 	scx_dsp_max_batch = 0;
4079 	free_kick_pseqs();
4080 
4081 	mutex_unlock(&scx_enable_mutex);
4082 
4083 	WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
4084 done:
4085 	scx_bypass(false);
4086 }
4087 
4088 static void scx_disable(enum scx_exit_kind kind)
4089 {
4090 	int none = SCX_EXIT_NONE;
4091 	struct scx_sched *sch;
4092 
4093 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
4094 		kind = SCX_EXIT_ERROR;
4095 
4096 	rcu_read_lock();
4097 	sch = rcu_dereference(scx_root);
4098 	if (sch) {
4099 		atomic_try_cmpxchg(&sch->exit_kind, &none, kind);
4100 		kthread_queue_work(sch->helper, &sch->disable_work);
4101 	}
4102 	rcu_read_unlock();
4103 }
4104 
4105 static void dump_newline(struct seq_buf *s)
4106 {
4107 	trace_sched_ext_dump("");
4108 
4109 	/* @s may be zero sized and seq_buf triggers WARN if so */
4110 	if (s->size)
4111 		seq_buf_putc(s, '\n');
4112 }
4113 
4114 static __printf(2, 3) void dump_line(struct seq_buf *s, const char *fmt, ...)
4115 {
4116 	va_list args;
4117 
4118 #ifdef CONFIG_TRACEPOINTS
4119 	if (trace_sched_ext_dump_enabled()) {
4120 		/* protected by scx_dump_state()::dump_lock */
4121 		static char line_buf[SCX_EXIT_MSG_LEN];
4122 
4123 		va_start(args, fmt);
4124 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
4125 		va_end(args);
4126 
4127 		trace_sched_ext_dump(line_buf);
4128 	}
4129 #endif
4130 	/* @s may be zero sized and seq_buf triggers WARN if so */
4131 	if (s->size) {
4132 		va_start(args, fmt);
4133 		seq_buf_vprintf(s, fmt, args);
4134 		va_end(args);
4135 
4136 		seq_buf_putc(s, '\n');
4137 	}
4138 }
4139 
4140 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
4141 			     const unsigned long *bt, unsigned int len)
4142 {
4143 	unsigned int i;
4144 
4145 	for (i = 0; i < len; i++)
4146 		dump_line(s, "%s%pS", prefix, (void *)bt[i]);
4147 }
4148 
4149 static void ops_dump_init(struct seq_buf *s, const char *prefix)
4150 {
4151 	struct scx_dump_data *dd = &scx_dump_data;
4152 
4153 	lockdep_assert_irqs_disabled();
4154 
4155 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
4156 	dd->first = true;
4157 	dd->cursor = 0;
4158 	dd->s = s;
4159 	dd->prefix = prefix;
4160 }
4161 
4162 static void ops_dump_flush(void)
4163 {
4164 	struct scx_dump_data *dd = &scx_dump_data;
4165 	char *line = dd->buf.line;
4166 
4167 	if (!dd->cursor)
4168 		return;
4169 
4170 	/*
4171 	 * There's something to flush and this is the first line. Insert a blank
4172 	 * line to distinguish ops dump.
4173 	 */
4174 	if (dd->first) {
4175 		dump_newline(dd->s);
4176 		dd->first = false;
4177 	}
4178 
4179 	/*
4180 	 * There may be multiple lines in $line. Scan and emit each line
4181 	 * separately.
4182 	 */
4183 	while (true) {
4184 		char *end = line;
4185 		char c;
4186 
4187 		while (*end != '\n' && *end != '\0')
4188 			end++;
4189 
4190 		/*
4191 		 * If $line overflowed, it may not have newline at the end.
4192 		 * Always emit with a newline.
4193 		 */
4194 		c = *end;
4195 		*end = '\0';
4196 		dump_line(dd->s, "%s%s", dd->prefix, line);
4197 		if (c == '\0')
4198 			break;
4199 
4200 		/* move to the next line */
4201 		end++;
4202 		if (*end == '\0')
4203 			break;
4204 		line = end;
4205 	}
4206 
4207 	dd->cursor = 0;
4208 }
4209 
4210 static void ops_dump_exit(void)
4211 {
4212 	ops_dump_flush();
4213 	scx_dump_data.cpu = -1;
4214 }
4215 
4216 static void scx_dump_task(struct seq_buf *s, struct scx_dump_ctx *dctx,
4217 			  struct task_struct *p, char marker)
4218 {
4219 	static unsigned long bt[SCX_EXIT_BT_LEN];
4220 	struct scx_sched *sch = scx_root;
4221 	char dsq_id_buf[19] = "(n/a)";
4222 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
4223 	unsigned int bt_len = 0;
4224 
4225 	if (p->scx.dsq)
4226 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
4227 			  (unsigned long long)p->scx.dsq->id);
4228 
4229 	dump_newline(s);
4230 	dump_line(s, " %c%c %s[%d] %+ldms",
4231 		  marker, task_state_to_char(p), p->comm, p->pid,
4232 		  jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
4233 	dump_line(s, "      scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu",
4234 		  scx_get_task_state(p), p->scx.flags & ~SCX_TASK_STATE_MASK,
4235 		  p->scx.dsq_flags, ops_state & SCX_OPSS_STATE_MASK,
4236 		  ops_state >> SCX_OPSS_QSEQ_SHIFT);
4237 	dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
4238 		  p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
4239 	dump_line(s, "      dsq_vtime=%llu slice=%llu weight=%u",
4240 		  p->scx.dsq_vtime, p->scx.slice, p->scx.weight);
4241 	dump_line(s, "      cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr),
4242 		  p->migration_disabled);
4243 
4244 	if (SCX_HAS_OP(sch, dump_task)) {
4245 		ops_dump_init(s, "    ");
4246 		SCX_CALL_OP(sch, SCX_KF_REST, dump_task, NULL, dctx, p);
4247 		ops_dump_exit();
4248 	}
4249 
4250 #ifdef CONFIG_STACKTRACE
4251 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
4252 #endif
4253 	if (bt_len) {
4254 		dump_newline(s);
4255 		dump_stack_trace(s, "    ", bt, bt_len);
4256 	}
4257 }
4258 
4259 static void scx_dump_state(struct scx_exit_info *ei, size_t dump_len)
4260 {
4261 	static DEFINE_SPINLOCK(dump_lock);
4262 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
4263 	struct scx_sched *sch = scx_root;
4264 	struct scx_dump_ctx dctx = {
4265 		.kind = ei->kind,
4266 		.exit_code = ei->exit_code,
4267 		.reason = ei->reason,
4268 		.at_ns = ktime_get_ns(),
4269 		.at_jiffies = jiffies,
4270 	};
4271 	struct seq_buf s;
4272 	struct scx_event_stats events;
4273 	unsigned long flags;
4274 	char *buf;
4275 	int cpu;
4276 
4277 	spin_lock_irqsave(&dump_lock, flags);
4278 
4279 	seq_buf_init(&s, ei->dump, dump_len);
4280 
4281 	if (ei->kind == SCX_EXIT_NONE) {
4282 		dump_line(&s, "Debug dump triggered by %s", ei->reason);
4283 	} else {
4284 		dump_line(&s, "%s[%d] triggered exit kind %d:",
4285 			  current->comm, current->pid, ei->kind);
4286 		dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
4287 		dump_newline(&s);
4288 		dump_line(&s, "Backtrace:");
4289 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
4290 	}
4291 
4292 	if (SCX_HAS_OP(sch, dump)) {
4293 		ops_dump_init(&s, "");
4294 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, dump, NULL, &dctx);
4295 		ops_dump_exit();
4296 	}
4297 
4298 	dump_newline(&s);
4299 	dump_line(&s, "CPU states");
4300 	dump_line(&s, "----------");
4301 
4302 	for_each_possible_cpu(cpu) {
4303 		struct rq *rq = cpu_rq(cpu);
4304 		struct rq_flags rf;
4305 		struct task_struct *p;
4306 		struct seq_buf ns;
4307 		size_t avail, used;
4308 		bool idle;
4309 
4310 		rq_lock(rq, &rf);
4311 
4312 		idle = list_empty(&rq->scx.runnable_list) &&
4313 			rq->curr->sched_class == &idle_sched_class;
4314 
4315 		if (idle && !SCX_HAS_OP(sch, dump_cpu))
4316 			goto next;
4317 
4318 		/*
4319 		 * We don't yet know whether ops.dump_cpu() will produce output
4320 		 * and we may want to skip the default CPU dump if it doesn't.
4321 		 * Use a nested seq_buf to generate the standard dump so that we
4322 		 * can decide whether to commit later.
4323 		 */
4324 		avail = seq_buf_get_buf(&s, &buf);
4325 		seq_buf_init(&ns, buf, avail);
4326 
4327 		dump_newline(&ns);
4328 		dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu pnt_seq=%lu",
4329 			  cpu, rq->scx.nr_running, rq->scx.flags,
4330 			  rq->scx.cpu_released, rq->scx.ops_qseq,
4331 			  rq->scx.pnt_seq);
4332 		dump_line(&ns, "          curr=%s[%d] class=%ps",
4333 			  rq->curr->comm, rq->curr->pid,
4334 			  rq->curr->sched_class);
4335 		if (!cpumask_empty(rq->scx.cpus_to_kick))
4336 			dump_line(&ns, "  cpus_to_kick   : %*pb",
4337 				  cpumask_pr_args(rq->scx.cpus_to_kick));
4338 		if (!cpumask_empty(rq->scx.cpus_to_kick_if_idle))
4339 			dump_line(&ns, "  idle_to_kick   : %*pb",
4340 				  cpumask_pr_args(rq->scx.cpus_to_kick_if_idle));
4341 		if (!cpumask_empty(rq->scx.cpus_to_preempt))
4342 			dump_line(&ns, "  cpus_to_preempt: %*pb",
4343 				  cpumask_pr_args(rq->scx.cpus_to_preempt));
4344 		if (!cpumask_empty(rq->scx.cpus_to_wait))
4345 			dump_line(&ns, "  cpus_to_wait   : %*pb",
4346 				  cpumask_pr_args(rq->scx.cpus_to_wait));
4347 
4348 		used = seq_buf_used(&ns);
4349 		if (SCX_HAS_OP(sch, dump_cpu)) {
4350 			ops_dump_init(&ns, "  ");
4351 			SCX_CALL_OP(sch, SCX_KF_REST, dump_cpu, NULL,
4352 				    &dctx, cpu, idle);
4353 			ops_dump_exit();
4354 		}
4355 
4356 		/*
4357 		 * If idle && nothing generated by ops.dump_cpu(), there's
4358 		 * nothing interesting. Skip.
4359 		 */
4360 		if (idle && used == seq_buf_used(&ns))
4361 			goto next;
4362 
4363 		/*
4364 		 * $s may already have overflowed when $ns was created. If so,
4365 		 * calling commit on it will trigger BUG.
4366 		 */
4367 		if (avail) {
4368 			seq_buf_commit(&s, seq_buf_used(&ns));
4369 			if (seq_buf_has_overflowed(&ns))
4370 				seq_buf_set_overflow(&s);
4371 		}
4372 
4373 		if (rq->curr->sched_class == &ext_sched_class)
4374 			scx_dump_task(&s, &dctx, rq->curr, '*');
4375 
4376 		list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
4377 			scx_dump_task(&s, &dctx, p, ' ');
4378 	next:
4379 		rq_unlock(rq, &rf);
4380 	}
4381 
4382 	dump_newline(&s);
4383 	dump_line(&s, "Event counters");
4384 	dump_line(&s, "--------------");
4385 
4386 	scx_read_events(sch, &events);
4387 	scx_dump_event(s, &events, SCX_EV_SELECT_CPU_FALLBACK);
4388 	scx_dump_event(s, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
4389 	scx_dump_event(s, &events, SCX_EV_DISPATCH_KEEP_LAST);
4390 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_EXITING);
4391 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
4392 	scx_dump_event(s, &events, SCX_EV_REFILL_SLICE_DFL);
4393 	scx_dump_event(s, &events, SCX_EV_BYPASS_DURATION);
4394 	scx_dump_event(s, &events, SCX_EV_BYPASS_DISPATCH);
4395 	scx_dump_event(s, &events, SCX_EV_BYPASS_ACTIVATE);
4396 
4397 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
4398 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
4399 		       trunc_marker, sizeof(trunc_marker));
4400 
4401 	spin_unlock_irqrestore(&dump_lock, flags);
4402 }
4403 
4404 static void scx_error_irq_workfn(struct irq_work *irq_work)
4405 {
4406 	struct scx_sched *sch = container_of(irq_work, struct scx_sched, error_irq_work);
4407 	struct scx_exit_info *ei = sch->exit_info;
4408 
4409 	if (ei->kind >= SCX_EXIT_ERROR)
4410 		scx_dump_state(ei, sch->ops.exit_dump_len);
4411 
4412 	kthread_queue_work(sch->helper, &sch->disable_work);
4413 }
4414 
4415 static void scx_vexit(struct scx_sched *sch,
4416 		      enum scx_exit_kind kind, s64 exit_code,
4417 		      const char *fmt, va_list args)
4418 {
4419 	struct scx_exit_info *ei = sch->exit_info;
4420 	int none = SCX_EXIT_NONE;
4421 
4422 	if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind))
4423 		return;
4424 
4425 	ei->exit_code = exit_code;
4426 #ifdef CONFIG_STACKTRACE
4427 	if (kind >= SCX_EXIT_ERROR)
4428 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
4429 #endif
4430 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
4431 
4432 	/*
4433 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
4434 	 * in scx_disable_workfn().
4435 	 */
4436 	ei->kind = kind;
4437 	ei->reason = scx_exit_reason(ei->kind);
4438 
4439 	irq_work_queue(&sch->error_irq_work);
4440 }
4441 
4442 static int alloc_kick_pseqs(void)
4443 {
4444 	int cpu;
4445 
4446 	/*
4447 	 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size
4448 	 * can exceed percpu allocator limits on large machines.
4449 	 */
4450 	for_each_possible_cpu(cpu) {
4451 		struct scx_kick_pseqs **pseqs = per_cpu_ptr(&scx_kick_pseqs, cpu);
4452 		struct scx_kick_pseqs *new_pseqs;
4453 
4454 		WARN_ON_ONCE(rcu_access_pointer(*pseqs));
4455 
4456 		new_pseqs = kvzalloc_node(struct_size(new_pseqs, seqs, nr_cpu_ids),
4457 					  GFP_KERNEL, cpu_to_node(cpu));
4458 		if (!new_pseqs) {
4459 			free_kick_pseqs();
4460 			return -ENOMEM;
4461 		}
4462 
4463 		rcu_assign_pointer(*pseqs, new_pseqs);
4464 	}
4465 
4466 	return 0;
4467 }
4468 
4469 static struct scx_sched *scx_alloc_and_add_sched(struct sched_ext_ops *ops)
4470 {
4471 	struct scx_sched *sch;
4472 	int node, ret;
4473 
4474 	sch = kzalloc(sizeof(*sch), GFP_KERNEL);
4475 	if (!sch)
4476 		return ERR_PTR(-ENOMEM);
4477 
4478 	sch->exit_info = alloc_exit_info(ops->exit_dump_len);
4479 	if (!sch->exit_info) {
4480 		ret = -ENOMEM;
4481 		goto err_free_sch;
4482 	}
4483 
4484 	ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params);
4485 	if (ret < 0)
4486 		goto err_free_ei;
4487 
4488 	sch->global_dsqs = kcalloc(nr_node_ids, sizeof(sch->global_dsqs[0]),
4489 				   GFP_KERNEL);
4490 	if (!sch->global_dsqs) {
4491 		ret = -ENOMEM;
4492 		goto err_free_hash;
4493 	}
4494 
4495 	for_each_node_state(node, N_POSSIBLE) {
4496 		struct scx_dispatch_q *dsq;
4497 
4498 		dsq = kzalloc_node(sizeof(*dsq), GFP_KERNEL, node);
4499 		if (!dsq) {
4500 			ret = -ENOMEM;
4501 			goto err_free_gdsqs;
4502 		}
4503 
4504 		init_dsq(dsq, SCX_DSQ_GLOBAL);
4505 		sch->global_dsqs[node] = dsq;
4506 	}
4507 
4508 	sch->pcpu = alloc_percpu(struct scx_sched_pcpu);
4509 	if (!sch->pcpu)
4510 		goto err_free_gdsqs;
4511 
4512 	sch->helper = kthread_run_worker(0, "sched_ext_helper");
4513 	if (!sch->helper)
4514 		goto err_free_pcpu;
4515 	sched_set_fifo(sch->helper->task);
4516 
4517 	atomic_set(&sch->exit_kind, SCX_EXIT_NONE);
4518 	init_irq_work(&sch->error_irq_work, scx_error_irq_workfn);
4519 	kthread_init_work(&sch->disable_work, scx_disable_workfn);
4520 	sch->ops = *ops;
4521 	ops->priv = sch;
4522 
4523 	sch->kobj.kset = scx_kset;
4524 	ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root");
4525 	if (ret < 0)
4526 		goto err_stop_helper;
4527 
4528 	return sch;
4529 
4530 err_stop_helper:
4531 	kthread_stop(sch->helper->task);
4532 err_free_pcpu:
4533 	free_percpu(sch->pcpu);
4534 err_free_gdsqs:
4535 	for_each_node_state(node, N_POSSIBLE)
4536 		kfree(sch->global_dsqs[node]);
4537 	kfree(sch->global_dsqs);
4538 err_free_hash:
4539 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
4540 err_free_ei:
4541 	free_exit_info(sch->exit_info);
4542 err_free_sch:
4543 	kfree(sch);
4544 	return ERR_PTR(ret);
4545 }
4546 
4547 static int check_hotplug_seq(struct scx_sched *sch,
4548 			      const struct sched_ext_ops *ops)
4549 {
4550 	unsigned long long global_hotplug_seq;
4551 
4552 	/*
4553 	 * If a hotplug event has occurred between when a scheduler was
4554 	 * initialized, and when we were able to attach, exit and notify user
4555 	 * space about it.
4556 	 */
4557 	if (ops->hotplug_seq) {
4558 		global_hotplug_seq = atomic_long_read(&scx_hotplug_seq);
4559 		if (ops->hotplug_seq != global_hotplug_seq) {
4560 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
4561 				 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
4562 				 "expected hotplug seq %llu did not match actual %llu",
4563 				 ops->hotplug_seq, global_hotplug_seq);
4564 			return -EBUSY;
4565 		}
4566 	}
4567 
4568 	return 0;
4569 }
4570 
4571 static int validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
4572 {
4573 	/*
4574 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
4575 	 * ops.enqueue() callback isn't implemented.
4576 	 */
4577 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
4578 		scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
4579 		return -EINVAL;
4580 	}
4581 
4582 	/*
4583 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle
4584 	 * selection policy to be enabled.
4585 	 */
4586 	if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) &&
4587 	    (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) {
4588 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled");
4589 		return -EINVAL;
4590 	}
4591 
4592 	if (ops->flags & SCX_OPS_HAS_CGROUP_WEIGHT)
4593 		pr_warn("SCX_OPS_HAS_CGROUP_WEIGHT is deprecated and a noop\n");
4594 
4595 	return 0;
4596 }
4597 
4598 static int scx_enable(struct sched_ext_ops *ops, struct bpf_link *link)
4599 {
4600 	struct scx_sched *sch;
4601 	struct scx_task_iter sti;
4602 	struct task_struct *p;
4603 	unsigned long timeout;
4604 	int i, cpu, ret;
4605 
4606 	if (!cpumask_equal(housekeeping_cpumask(HK_TYPE_DOMAIN),
4607 			   cpu_possible_mask)) {
4608 		pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n");
4609 		return -EINVAL;
4610 	}
4611 
4612 	mutex_lock(&scx_enable_mutex);
4613 
4614 	ret = alloc_kick_pseqs();
4615 	if (ret)
4616 		goto err_unlock;
4617 
4618 	if (scx_enable_state() != SCX_DISABLED) {
4619 		ret = -EBUSY;
4620 		goto err_free_pseqs;
4621 	}
4622 
4623 	sch = scx_alloc_and_add_sched(ops);
4624 	if (IS_ERR(sch)) {
4625 		ret = PTR_ERR(sch);
4626 		goto err_free_pseqs;
4627 	}
4628 
4629 	/*
4630 	 * Transition to ENABLING and clear exit info to arm the disable path.
4631 	 * Failure triggers full disabling from here on.
4632 	 */
4633 	WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED);
4634 	WARN_ON_ONCE(scx_root);
4635 
4636 	atomic_long_set(&scx_nr_rejected, 0);
4637 
4638 	for_each_possible_cpu(cpu)
4639 		cpu_rq(cpu)->scx.cpuperf_target = SCX_CPUPERF_ONE;
4640 
4641 	/*
4642 	 * Keep CPUs stable during enable so that the BPF scheduler can track
4643 	 * online CPUs by watching ->on/offline_cpu() after ->init().
4644 	 */
4645 	cpus_read_lock();
4646 
4647 	/*
4648 	 * Make the scheduler instance visible. Must be inside cpus_read_lock().
4649 	 * See handle_hotplug().
4650 	 */
4651 	rcu_assign_pointer(scx_root, sch);
4652 
4653 	scx_idle_enable(ops);
4654 
4655 	if (sch->ops.init) {
4656 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init, NULL);
4657 		if (ret) {
4658 			ret = ops_sanitize_err(sch, "init", ret);
4659 			cpus_read_unlock();
4660 			scx_error(sch, "ops.init() failed (%d)", ret);
4661 			goto err_disable;
4662 		}
4663 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
4664 	}
4665 
4666 	for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++)
4667 		if (((void (**)(void))ops)[i])
4668 			set_bit(i, sch->has_op);
4669 
4670 	ret = check_hotplug_seq(sch, ops);
4671 	if (ret) {
4672 		cpus_read_unlock();
4673 		goto err_disable;
4674 	}
4675 	scx_idle_update_selcpu_topology(ops);
4676 
4677 	cpus_read_unlock();
4678 
4679 	ret = validate_ops(sch, ops);
4680 	if (ret)
4681 		goto err_disable;
4682 
4683 	WARN_ON_ONCE(scx_dsp_ctx);
4684 	scx_dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
4685 	scx_dsp_ctx = __alloc_percpu(struct_size_t(struct scx_dsp_ctx, buf,
4686 						   scx_dsp_max_batch),
4687 				     __alignof__(struct scx_dsp_ctx));
4688 	if (!scx_dsp_ctx) {
4689 		ret = -ENOMEM;
4690 		goto err_disable;
4691 	}
4692 
4693 	if (ops->timeout_ms)
4694 		timeout = msecs_to_jiffies(ops->timeout_ms);
4695 	else
4696 		timeout = SCX_WATCHDOG_MAX_TIMEOUT;
4697 
4698 	WRITE_ONCE(scx_watchdog_timeout, timeout);
4699 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
4700 	queue_delayed_work(system_unbound_wq, &scx_watchdog_work,
4701 			   scx_watchdog_timeout / 2);
4702 
4703 	/*
4704 	 * Once __scx_enabled is set, %current can be switched to SCX anytime.
4705 	 * This can lead to stalls as some BPF schedulers (e.g. userspace
4706 	 * scheduling) may not function correctly before all tasks are switched.
4707 	 * Init in bypass mode to guarantee forward progress.
4708 	 */
4709 	scx_bypass(true);
4710 
4711 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
4712 		if (((void (**)(void))ops)[i])
4713 			set_bit(i, sch->has_op);
4714 
4715 	if (sch->ops.cpu_acquire || sch->ops.cpu_release)
4716 		sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT;
4717 
4718 	/*
4719 	 * Lock out forks, cgroup on/offlining and moves before opening the
4720 	 * floodgate so that they don't wander into the operations prematurely.
4721 	 */
4722 	percpu_down_write(&scx_fork_rwsem);
4723 
4724 	WARN_ON_ONCE(scx_init_task_enabled);
4725 	scx_init_task_enabled = true;
4726 
4727 	/*
4728 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
4729 	 * preventing new tasks from being added. No need to exclude tasks
4730 	 * leaving as sched_ext_free() can handle both prepped and enabled
4731 	 * tasks. Prep all tasks first and then enable them with preemption
4732 	 * disabled.
4733 	 *
4734 	 * All cgroups should be initialized before scx_init_task() so that the
4735 	 * BPF scheduler can reliably track each task's cgroup membership from
4736 	 * scx_init_task(). Lock out cgroup on/offlining and task migrations
4737 	 * while tasks are being initialized so that scx_cgroup_can_attach()
4738 	 * never sees uninitialized tasks.
4739 	 */
4740 	scx_cgroup_lock();
4741 	ret = scx_cgroup_init(sch);
4742 	if (ret)
4743 		goto err_disable_unlock_all;
4744 
4745 	scx_task_iter_start(&sti);
4746 	while ((p = scx_task_iter_next_locked(&sti))) {
4747 		/*
4748 		 * @p may already be dead, have lost all its usages counts and
4749 		 * be waiting for RCU grace period before being freed. @p can't
4750 		 * be initialized for SCX in such cases and should be ignored.
4751 		 */
4752 		if (!tryget_task_struct(p))
4753 			continue;
4754 
4755 		scx_task_iter_unlock(&sti);
4756 
4757 		ret = scx_init_task(p, task_group(p), false);
4758 		if (ret) {
4759 			put_task_struct(p);
4760 			scx_task_iter_stop(&sti);
4761 			scx_error(sch, "ops.init_task() failed (%d) for %s[%d]",
4762 				  ret, p->comm, p->pid);
4763 			goto err_disable_unlock_all;
4764 		}
4765 
4766 		scx_set_task_state(p, SCX_TASK_READY);
4767 
4768 		put_task_struct(p);
4769 	}
4770 	scx_task_iter_stop(&sti);
4771 	scx_cgroup_unlock();
4772 	percpu_up_write(&scx_fork_rwsem);
4773 
4774 	/*
4775 	 * All tasks are READY. It's safe to turn on scx_enabled() and switch
4776 	 * all eligible tasks.
4777 	 */
4778 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
4779 	static_branch_enable(&__scx_enabled);
4780 
4781 	/*
4782 	 * We're fully committed and can't fail. The task READY -> ENABLED
4783 	 * transitions here are synchronized against sched_ext_free() through
4784 	 * scx_tasks_lock.
4785 	 */
4786 	percpu_down_write(&scx_fork_rwsem);
4787 	scx_task_iter_start(&sti);
4788 	while ((p = scx_task_iter_next_locked(&sti))) {
4789 		const struct sched_class *old_class = p->sched_class;
4790 		const struct sched_class *new_class =
4791 			__setscheduler_class(p->policy, p->prio);
4792 		struct sched_enq_and_set_ctx ctx;
4793 
4794 		if (!tryget_task_struct(p))
4795 			continue;
4796 
4797 		if (old_class != new_class && p->se.sched_delayed)
4798 			dequeue_task(task_rq(p), p, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
4799 
4800 		sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
4801 
4802 		p->scx.slice = SCX_SLICE_DFL;
4803 		p->sched_class = new_class;
4804 		check_class_changing(task_rq(p), p, old_class);
4805 
4806 		sched_enq_and_set_task(&ctx);
4807 
4808 		check_class_changed(task_rq(p), p, old_class, p->prio);
4809 		put_task_struct(p);
4810 	}
4811 	scx_task_iter_stop(&sti);
4812 	percpu_up_write(&scx_fork_rwsem);
4813 
4814 	scx_bypass(false);
4815 
4816 	if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) {
4817 		WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE);
4818 		goto err_disable;
4819 	}
4820 
4821 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
4822 		static_branch_enable(&__scx_switched_all);
4823 
4824 	pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n",
4825 		sch->ops.name, scx_switched_all() ? "" : " (partial)");
4826 	kobject_uevent(&sch->kobj, KOBJ_ADD);
4827 	mutex_unlock(&scx_enable_mutex);
4828 
4829 	atomic_long_inc(&scx_enable_seq);
4830 
4831 	return 0;
4832 
4833 err_free_pseqs:
4834 	free_kick_pseqs();
4835 err_unlock:
4836 	mutex_unlock(&scx_enable_mutex);
4837 	return ret;
4838 
4839 err_disable_unlock_all:
4840 	scx_cgroup_unlock();
4841 	percpu_up_write(&scx_fork_rwsem);
4842 	/* we'll soon enter disable path, keep bypass on */
4843 err_disable:
4844 	mutex_unlock(&scx_enable_mutex);
4845 	/*
4846 	 * Returning an error code here would not pass all the error information
4847 	 * to userspace. Record errno using scx_error() for cases scx_error()
4848 	 * wasn't already invoked and exit indicating success so that the error
4849 	 * is notified through ops.exit() with all the details.
4850 	 *
4851 	 * Flush scx_disable_work to ensure that error is reported before init
4852 	 * completion. sch's base reference will be put by bpf_scx_unreg().
4853 	 */
4854 	scx_error(sch, "scx_enable() failed (%d)", ret);
4855 	kthread_flush_work(&sch->disable_work);
4856 	return 0;
4857 }
4858 
4859 
4860 /********************************************************************************
4861  * bpf_struct_ops plumbing.
4862  */
4863 #include <linux/bpf_verifier.h>
4864 #include <linux/bpf.h>
4865 #include <linux/btf.h>
4866 
4867 static const struct btf_type *task_struct_type;
4868 
4869 static bool bpf_scx_is_valid_access(int off, int size,
4870 				    enum bpf_access_type type,
4871 				    const struct bpf_prog *prog,
4872 				    struct bpf_insn_access_aux *info)
4873 {
4874 	if (type != BPF_READ)
4875 		return false;
4876 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
4877 		return false;
4878 	if (off % size != 0)
4879 		return false;
4880 
4881 	return btf_ctx_access(off, size, type, prog, info);
4882 }
4883 
4884 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
4885 				     const struct bpf_reg_state *reg, int off,
4886 				     int size)
4887 {
4888 	const struct btf_type *t;
4889 
4890 	t = btf_type_by_id(reg->btf, reg->btf_id);
4891 	if (t == task_struct_type) {
4892 		if (off >= offsetof(struct task_struct, scx.slice) &&
4893 		    off + size <= offsetofend(struct task_struct, scx.slice))
4894 			return SCALAR_VALUE;
4895 		if (off >= offsetof(struct task_struct, scx.dsq_vtime) &&
4896 		    off + size <= offsetofend(struct task_struct, scx.dsq_vtime))
4897 			return SCALAR_VALUE;
4898 		if (off >= offsetof(struct task_struct, scx.disallow) &&
4899 		    off + size <= offsetofend(struct task_struct, scx.disallow))
4900 			return SCALAR_VALUE;
4901 	}
4902 
4903 	return -EACCES;
4904 }
4905 
4906 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
4907 	.get_func_proto = bpf_base_func_proto,
4908 	.is_valid_access = bpf_scx_is_valid_access,
4909 	.btf_struct_access = bpf_scx_btf_struct_access,
4910 };
4911 
4912 static int bpf_scx_init_member(const struct btf_type *t,
4913 			       const struct btf_member *member,
4914 			       void *kdata, const void *udata)
4915 {
4916 	const struct sched_ext_ops *uops = udata;
4917 	struct sched_ext_ops *ops = kdata;
4918 	u32 moff = __btf_member_bit_offset(t, member) / 8;
4919 	int ret;
4920 
4921 	switch (moff) {
4922 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
4923 		if (*(u32 *)(udata + moff) > INT_MAX)
4924 			return -E2BIG;
4925 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
4926 		return 1;
4927 	case offsetof(struct sched_ext_ops, flags):
4928 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
4929 			return -EINVAL;
4930 		ops->flags = *(u64 *)(udata + moff);
4931 		return 1;
4932 	case offsetof(struct sched_ext_ops, name):
4933 		ret = bpf_obj_name_cpy(ops->name, uops->name,
4934 				       sizeof(ops->name));
4935 		if (ret < 0)
4936 			return ret;
4937 		if (ret == 0)
4938 			return -EINVAL;
4939 		return 1;
4940 	case offsetof(struct sched_ext_ops, timeout_ms):
4941 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
4942 		    SCX_WATCHDOG_MAX_TIMEOUT)
4943 			return -E2BIG;
4944 		ops->timeout_ms = *(u32 *)(udata + moff);
4945 		return 1;
4946 	case offsetof(struct sched_ext_ops, exit_dump_len):
4947 		ops->exit_dump_len =
4948 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
4949 		return 1;
4950 	case offsetof(struct sched_ext_ops, hotplug_seq):
4951 		ops->hotplug_seq = *(u64 *)(udata + moff);
4952 		return 1;
4953 	}
4954 
4955 	return 0;
4956 }
4957 
4958 static int bpf_scx_check_member(const struct btf_type *t,
4959 				const struct btf_member *member,
4960 				const struct bpf_prog *prog)
4961 {
4962 	u32 moff = __btf_member_bit_offset(t, member) / 8;
4963 
4964 	switch (moff) {
4965 	case offsetof(struct sched_ext_ops, init_task):
4966 #ifdef CONFIG_EXT_GROUP_SCHED
4967 	case offsetof(struct sched_ext_ops, cgroup_init):
4968 	case offsetof(struct sched_ext_ops, cgroup_exit):
4969 	case offsetof(struct sched_ext_ops, cgroup_prep_move):
4970 #endif
4971 	case offsetof(struct sched_ext_ops, cpu_online):
4972 	case offsetof(struct sched_ext_ops, cpu_offline):
4973 	case offsetof(struct sched_ext_ops, init):
4974 	case offsetof(struct sched_ext_ops, exit):
4975 		break;
4976 	default:
4977 		if (prog->sleepable)
4978 			return -EINVAL;
4979 	}
4980 
4981 	return 0;
4982 }
4983 
4984 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
4985 {
4986 	return scx_enable(kdata, link);
4987 }
4988 
4989 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
4990 {
4991 	struct sched_ext_ops *ops = kdata;
4992 	struct scx_sched *sch = ops->priv;
4993 
4994 	scx_disable(SCX_EXIT_UNREG);
4995 	kthread_flush_work(&sch->disable_work);
4996 	kobject_put(&sch->kobj);
4997 }
4998 
4999 static int bpf_scx_init(struct btf *btf)
5000 {
5001 	task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]);
5002 
5003 	return 0;
5004 }
5005 
5006 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
5007 {
5008 	/*
5009 	 * sched_ext does not support updating the actively-loaded BPF
5010 	 * scheduler, as registering a BPF scheduler can always fail if the
5011 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
5012 	 * etc. Similarly, we can always race with unregistration happening
5013 	 * elsewhere, such as with sysrq.
5014 	 */
5015 	return -EOPNOTSUPP;
5016 }
5017 
5018 static int bpf_scx_validate(void *kdata)
5019 {
5020 	return 0;
5021 }
5022 
5023 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
5024 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
5025 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
5026 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {}
5027 static void sched_ext_ops__tick(struct task_struct *p) {}
5028 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {}
5029 static void sched_ext_ops__running(struct task_struct *p) {}
5030 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {}
5031 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {}
5032 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; }
5033 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; }
5034 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {}
5035 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {}
5036 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {}
5037 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {}
5038 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {}
5039 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
5040 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {}
5041 static void sched_ext_ops__enable(struct task_struct *p) {}
5042 static void sched_ext_ops__disable(struct task_struct *p) {}
5043 #ifdef CONFIG_EXT_GROUP_SCHED
5044 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; }
5045 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {}
5046 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; }
5047 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
5048 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
5049 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
5050 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
5051 static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}
5052 #endif
5053 static void sched_ext_ops__cpu_online(s32 cpu) {}
5054 static void sched_ext_ops__cpu_offline(s32 cpu) {}
5055 static s32 sched_ext_ops__init(void) { return -EINVAL; }
5056 static void sched_ext_ops__exit(struct scx_exit_info *info) {}
5057 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {}
5058 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {}
5059 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {}
5060 
5061 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
5062 	.select_cpu		= sched_ext_ops__select_cpu,
5063 	.enqueue		= sched_ext_ops__enqueue,
5064 	.dequeue		= sched_ext_ops__dequeue,
5065 	.dispatch		= sched_ext_ops__dispatch,
5066 	.tick			= sched_ext_ops__tick,
5067 	.runnable		= sched_ext_ops__runnable,
5068 	.running		= sched_ext_ops__running,
5069 	.stopping		= sched_ext_ops__stopping,
5070 	.quiescent		= sched_ext_ops__quiescent,
5071 	.yield			= sched_ext_ops__yield,
5072 	.core_sched_before	= sched_ext_ops__core_sched_before,
5073 	.set_weight		= sched_ext_ops__set_weight,
5074 	.set_cpumask		= sched_ext_ops__set_cpumask,
5075 	.update_idle		= sched_ext_ops__update_idle,
5076 	.cpu_acquire		= sched_ext_ops__cpu_acquire,
5077 	.cpu_release		= sched_ext_ops__cpu_release,
5078 	.init_task		= sched_ext_ops__init_task,
5079 	.exit_task		= sched_ext_ops__exit_task,
5080 	.enable			= sched_ext_ops__enable,
5081 	.disable		= sched_ext_ops__disable,
5082 #ifdef CONFIG_EXT_GROUP_SCHED
5083 	.cgroup_init		= sched_ext_ops__cgroup_init,
5084 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
5085 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
5086 	.cgroup_move		= sched_ext_ops__cgroup_move,
5087 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
5088 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
5089 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
5090 	.cgroup_set_idle	= sched_ext_ops__cgroup_set_idle,
5091 #endif
5092 	.cpu_online		= sched_ext_ops__cpu_online,
5093 	.cpu_offline		= sched_ext_ops__cpu_offline,
5094 	.init			= sched_ext_ops__init,
5095 	.exit			= sched_ext_ops__exit,
5096 	.dump			= sched_ext_ops__dump,
5097 	.dump_cpu		= sched_ext_ops__dump_cpu,
5098 	.dump_task		= sched_ext_ops__dump_task,
5099 };
5100 
5101 static struct bpf_struct_ops bpf_sched_ext_ops = {
5102 	.verifier_ops = &bpf_scx_verifier_ops,
5103 	.reg = bpf_scx_reg,
5104 	.unreg = bpf_scx_unreg,
5105 	.check_member = bpf_scx_check_member,
5106 	.init_member = bpf_scx_init_member,
5107 	.init = bpf_scx_init,
5108 	.update = bpf_scx_update,
5109 	.validate = bpf_scx_validate,
5110 	.name = "sched_ext_ops",
5111 	.owner = THIS_MODULE,
5112 	.cfi_stubs = &__bpf_ops_sched_ext_ops
5113 };
5114 
5115 
5116 /********************************************************************************
5117  * System integration and init.
5118  */
5119 
5120 static void sysrq_handle_sched_ext_reset(u8 key)
5121 {
5122 	scx_disable(SCX_EXIT_SYSRQ);
5123 }
5124 
5125 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
5126 	.handler	= sysrq_handle_sched_ext_reset,
5127 	.help_msg	= "reset-sched-ext(S)",
5128 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
5129 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
5130 };
5131 
5132 static void sysrq_handle_sched_ext_dump(u8 key)
5133 {
5134 	struct scx_exit_info ei = { .kind = SCX_EXIT_NONE, .reason = "SysRq-D" };
5135 
5136 	if (scx_enabled())
5137 		scx_dump_state(&ei, 0);
5138 }
5139 
5140 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
5141 	.handler	= sysrq_handle_sched_ext_dump,
5142 	.help_msg	= "dump-sched-ext(D)",
5143 	.action_msg	= "Trigger sched_ext debug dump",
5144 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
5145 };
5146 
5147 static bool can_skip_idle_kick(struct rq *rq)
5148 {
5149 	lockdep_assert_rq_held(rq);
5150 
5151 	/*
5152 	 * We can skip idle kicking if @rq is going to go through at least one
5153 	 * full SCX scheduling cycle before going idle. Just checking whether
5154 	 * curr is not idle is insufficient because we could be racing
5155 	 * balance_one() trying to pull the next task from a remote rq, which
5156 	 * may fail, and @rq may become idle afterwards.
5157 	 *
5158 	 * The race window is small and we don't and can't guarantee that @rq is
5159 	 * only kicked while idle anyway. Skip only when sure.
5160 	 */
5161 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_BALANCE);
5162 }
5163 
5164 static bool kick_one_cpu(s32 cpu, struct rq *this_rq, unsigned long *pseqs)
5165 {
5166 	struct rq *rq = cpu_rq(cpu);
5167 	struct scx_rq *this_scx = &this_rq->scx;
5168 	bool should_wait = false;
5169 	unsigned long flags;
5170 
5171 	raw_spin_rq_lock_irqsave(rq, flags);
5172 
5173 	/*
5174 	 * During CPU hotplug, a CPU may depend on kicking itself to make
5175 	 * forward progress. Allow kicking self regardless of online state.
5176 	 */
5177 	if (cpu_online(cpu) || cpu == cpu_of(this_rq)) {
5178 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_preempt)) {
5179 			if (rq->curr->sched_class == &ext_sched_class)
5180 				rq->curr->scx.slice = 0;
5181 			cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
5182 		}
5183 
5184 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_wait)) {
5185 			pseqs[cpu] = rq->scx.pnt_seq;
5186 			should_wait = true;
5187 		}
5188 
5189 		resched_curr(rq);
5190 	} else {
5191 		cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
5192 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
5193 	}
5194 
5195 	raw_spin_rq_unlock_irqrestore(rq, flags);
5196 
5197 	return should_wait;
5198 }
5199 
5200 static void kick_one_cpu_if_idle(s32 cpu, struct rq *this_rq)
5201 {
5202 	struct rq *rq = cpu_rq(cpu);
5203 	unsigned long flags;
5204 
5205 	raw_spin_rq_lock_irqsave(rq, flags);
5206 
5207 	if (!can_skip_idle_kick(rq) &&
5208 	    (cpu_online(cpu) || cpu == cpu_of(this_rq)))
5209 		resched_curr(rq);
5210 
5211 	raw_spin_rq_unlock_irqrestore(rq, flags);
5212 }
5213 
5214 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
5215 {
5216 	struct rq *this_rq = this_rq();
5217 	struct scx_rq *this_scx = &this_rq->scx;
5218 	struct scx_kick_pseqs __rcu *pseqs_pcpu = __this_cpu_read(scx_kick_pseqs);
5219 	bool should_wait = false;
5220 	unsigned long *pseqs;
5221 	s32 cpu;
5222 
5223 	if (unlikely(!pseqs_pcpu)) {
5224 		pr_warn_once("kick_cpus_irq_workfn() called with NULL scx_kick_pseqs");
5225 		return;
5226 	}
5227 
5228 	pseqs = rcu_dereference_bh(pseqs_pcpu)->seqs;
5229 
5230 	for_each_cpu(cpu, this_scx->cpus_to_kick) {
5231 		should_wait |= kick_one_cpu(cpu, this_rq, pseqs);
5232 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick);
5233 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
5234 	}
5235 
5236 	for_each_cpu(cpu, this_scx->cpus_to_kick_if_idle) {
5237 		kick_one_cpu_if_idle(cpu, this_rq);
5238 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
5239 	}
5240 
5241 	if (!should_wait)
5242 		return;
5243 
5244 	for_each_cpu(cpu, this_scx->cpus_to_wait) {
5245 		unsigned long *wait_pnt_seq = &cpu_rq(cpu)->scx.pnt_seq;
5246 
5247 		if (cpu != cpu_of(this_rq)) {
5248 			/*
5249 			 * Pairs with smp_store_release() issued by this CPU in
5250 			 * switch_class() on the resched path.
5251 			 *
5252 			 * We busy-wait here to guarantee that no other task can
5253 			 * be scheduled on our core before the target CPU has
5254 			 * entered the resched path.
5255 			 */
5256 			while (smp_load_acquire(wait_pnt_seq) == pseqs[cpu])
5257 				cpu_relax();
5258 		}
5259 
5260 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
5261 	}
5262 }
5263 
5264 /**
5265  * print_scx_info - print out sched_ext scheduler state
5266  * @log_lvl: the log level to use when printing
5267  * @p: target task
5268  *
5269  * If a sched_ext scheduler is enabled, print the name and state of the
5270  * scheduler. If @p is on sched_ext, print further information about the task.
5271  *
5272  * This function can be safely called on any task as long as the task_struct
5273  * itself is accessible. While safe, this function isn't synchronized and may
5274  * print out mixups or garbages of limited length.
5275  */
5276 void print_scx_info(const char *log_lvl, struct task_struct *p)
5277 {
5278 	struct scx_sched *sch = scx_root;
5279 	enum scx_enable_state state = scx_enable_state();
5280 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
5281 	char runnable_at_buf[22] = "?";
5282 	struct sched_class *class;
5283 	unsigned long runnable_at;
5284 
5285 	if (state == SCX_DISABLED)
5286 		return;
5287 
5288 	/*
5289 	 * Carefully check if the task was running on sched_ext, and then
5290 	 * carefully copy the time it's been runnable, and its state.
5291 	 */
5292 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
5293 	    class != &ext_sched_class) {
5294 		printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name,
5295 		       scx_enable_state_str[state], all);
5296 		return;
5297 	}
5298 
5299 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
5300 				      sizeof(runnable_at)))
5301 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
5302 			  jiffies_delta_msecs(runnable_at, jiffies));
5303 
5304 	/* print everything onto one line to conserve console space */
5305 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
5306 	       log_lvl, sch->ops.name, scx_enable_state_str[state], all,
5307 	       runnable_at_buf);
5308 }
5309 
5310 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr)
5311 {
5312 	/*
5313 	 * SCX schedulers often have userspace components which are sometimes
5314 	 * involved in critial scheduling paths. PM operations involve freezing
5315 	 * userspace which can lead to scheduling misbehaviors including stalls.
5316 	 * Let's bypass while PM operations are in progress.
5317 	 */
5318 	switch (event) {
5319 	case PM_HIBERNATION_PREPARE:
5320 	case PM_SUSPEND_PREPARE:
5321 	case PM_RESTORE_PREPARE:
5322 		scx_bypass(true);
5323 		break;
5324 	case PM_POST_HIBERNATION:
5325 	case PM_POST_SUSPEND:
5326 	case PM_POST_RESTORE:
5327 		scx_bypass(false);
5328 		break;
5329 	}
5330 
5331 	return NOTIFY_OK;
5332 }
5333 
5334 static struct notifier_block scx_pm_notifier = {
5335 	.notifier_call = scx_pm_handler,
5336 };
5337 
5338 void __init init_sched_ext_class(void)
5339 {
5340 	s32 cpu, v;
5341 
5342 	/*
5343 	 * The following is to prevent the compiler from optimizing out the enum
5344 	 * definitions so that BPF scheduler implementations can use them
5345 	 * through the generated vmlinux.h.
5346 	 */
5347 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT |
5348 		   SCX_TG_ONLINE);
5349 
5350 	scx_idle_init_masks();
5351 
5352 	for_each_possible_cpu(cpu) {
5353 		struct rq *rq = cpu_rq(cpu);
5354 		int  n = cpu_to_node(cpu);
5355 
5356 		init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL);
5357 		INIT_LIST_HEAD(&rq->scx.runnable_list);
5358 		INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals);
5359 
5360 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick, GFP_KERNEL, n));
5361 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick_if_idle, GFP_KERNEL, n));
5362 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_preempt, GFP_KERNEL, n));
5363 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_wait, GFP_KERNEL, n));
5364 		init_irq_work(&rq->scx.deferred_irq_work, deferred_irq_workfn);
5365 		init_irq_work(&rq->scx.kick_cpus_irq_work, kick_cpus_irq_workfn);
5366 
5367 		if (cpu_online(cpu))
5368 			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
5369 	}
5370 
5371 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
5372 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
5373 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
5374 }
5375 
5376 
5377 /********************************************************************************
5378  * Helpers that can be called from the BPF scheduler.
5379  */
5380 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p,
5381 				    u64 enq_flags)
5382 {
5383 	if (!scx_kf_allowed(sch, SCX_KF_ENQUEUE | SCX_KF_DISPATCH))
5384 		return false;
5385 
5386 	lockdep_assert_irqs_disabled();
5387 
5388 	if (unlikely(!p)) {
5389 		scx_error(sch, "called with NULL task");
5390 		return false;
5391 	}
5392 
5393 	if (unlikely(enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
5394 		scx_error(sch, "invalid enq_flags 0x%llx", enq_flags);
5395 		return false;
5396 	}
5397 
5398 	return true;
5399 }
5400 
5401 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p,
5402 				  u64 dsq_id, u64 enq_flags)
5403 {
5404 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
5405 	struct task_struct *ddsp_task;
5406 
5407 	ddsp_task = __this_cpu_read(direct_dispatch_task);
5408 	if (ddsp_task) {
5409 		mark_direct_dispatch(sch, ddsp_task, p, dsq_id, enq_flags);
5410 		return;
5411 	}
5412 
5413 	if (unlikely(dspc->cursor >= scx_dsp_max_batch)) {
5414 		scx_error(sch, "dispatch buffer overflow");
5415 		return;
5416 	}
5417 
5418 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
5419 		.task = p,
5420 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
5421 		.dsq_id = dsq_id,
5422 		.enq_flags = enq_flags,
5423 	};
5424 }
5425 
5426 __bpf_kfunc_start_defs();
5427 
5428 /**
5429  * scx_bpf_dsq_insert - Insert a task into the FIFO queue of a DSQ
5430  * @p: task_struct to insert
5431  * @dsq_id: DSQ to insert into
5432  * @slice: duration @p can run for in nsecs, 0 to keep the current value
5433  * @enq_flags: SCX_ENQ_*
5434  *
5435  * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to
5436  * call this function spuriously. Can be called from ops.enqueue(),
5437  * ops.select_cpu(), and ops.dispatch().
5438  *
5439  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
5440  * and @p must match the task being enqueued.
5441  *
5442  * When called from ops.select_cpu(), @enq_flags and @dsp_id are stored, and @p
5443  * will be directly inserted into the corresponding dispatch queue after
5444  * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be
5445  * inserted into the local DSQ of the CPU returned by ops.select_cpu().
5446  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
5447  * task is inserted.
5448  *
5449  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
5450  * and this function can be called upto ops.dispatch_max_batch times to insert
5451  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
5452  * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the
5453  * counter.
5454  *
5455  * This function doesn't have any locking restrictions and may be called under
5456  * BPF locks (in the future when BPF introduces more flexible locking).
5457  *
5458  * @p is allowed to run for @slice. The scheduling path is triggered on slice
5459  * exhaustion. If zero, the current residual slice is maintained. If
5460  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
5461  * scx_bpf_kick_cpu() to trigger scheduling.
5462  *
5463  * Returns %true on successful insertion, %false on failure. On the root
5464  * scheduler, %false return triggers scheduler abort and the caller doesn't need
5465  * to check the return value.
5466  */
5467 __bpf_kfunc bool scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id, u64 slice,
5468 				    u64 enq_flags)
5469 {
5470 	struct scx_sched *sch;
5471 
5472 	guard(rcu)();
5473 	sch = rcu_dereference(scx_root);
5474 	if (unlikely(!sch))
5475 		return false;
5476 
5477 	if (!scx_dsq_insert_preamble(sch, p, enq_flags))
5478 		return false;
5479 
5480 	if (slice)
5481 		p->scx.slice = slice;
5482 	else
5483 		p->scx.slice = p->scx.slice ?: 1;
5484 
5485 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags);
5486 
5487 	return true;
5488 }
5489 
5490 /*
5491  * COMPAT: Will be removed in v6.23.
5492  */
5493 __bpf_kfunc void scx_bpf_dsq_insert___compat(struct task_struct *p, u64 dsq_id,
5494 					     u64 slice, u64 enq_flags)
5495 {
5496 	scx_bpf_dsq_insert(p, dsq_id, slice, enq_flags);
5497 }
5498 
5499 static bool scx_dsq_insert_vtime(struct scx_sched *sch, struct task_struct *p,
5500 				 u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
5501 {
5502 	if (!scx_dsq_insert_preamble(sch, p, enq_flags))
5503 		return false;
5504 
5505 	if (slice)
5506 		p->scx.slice = slice;
5507 	else
5508 		p->scx.slice = p->scx.slice ?: 1;
5509 
5510 	p->scx.dsq_vtime = vtime;
5511 
5512 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
5513 
5514 	return true;
5515 }
5516 
5517 struct scx_bpf_dsq_insert_vtime_args {
5518 	/* @p can't be packed together as KF_RCU is not transitive */
5519 	u64			dsq_id;
5520 	u64			slice;
5521 	u64			vtime;
5522 	u64			enq_flags;
5523 };
5524 
5525 /**
5526  * __scx_bpf_dsq_insert_vtime - Arg-wrapped vtime DSQ insertion
5527  * @p: task_struct to insert
5528  * @args: struct containing the rest of the arguments
5529  *       @args->dsq_id: DSQ to insert into
5530  *       @args->slice: duration @p can run for in nsecs, 0 to keep the current value
5531  *       @args->vtime: @p's ordering inside the vtime-sorted queue of the target DSQ
5532  *       @args->enq_flags: SCX_ENQ_*
5533  *
5534  * Wrapper kfunc that takes arguments via struct to work around BPF's 5 argument
5535  * limit. BPF programs should use scx_bpf_dsq_insert_vtime() which is provided
5536  * as an inline wrapper in common.bpf.h.
5537  *
5538  * Insert @p into the vtime priority queue of the DSQ identified by
5539  * @args->dsq_id. Tasks queued into the priority queue are ordered by
5540  * @args->vtime. All other aspects are identical to scx_bpf_dsq_insert().
5541  *
5542  * @args->vtime ordering is according to time_before64() which considers
5543  * wrapping. A numerically larger vtime may indicate an earlier position in the
5544  * ordering and vice-versa.
5545  *
5546  * A DSQ can only be used as a FIFO or priority queue at any given time and this
5547  * function must not be called on a DSQ which already has one or more FIFO tasks
5548  * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and
5549  * SCX_DSQ_GLOBAL) cannot be used as priority queues.
5550  *
5551  * Returns %true on successful insertion, %false on failure. On the root
5552  * scheduler, %false return triggers scheduler abort and the caller doesn't need
5553  * to check the return value.
5554  */
5555 __bpf_kfunc bool
5556 __scx_bpf_dsq_insert_vtime(struct task_struct *p,
5557 			   struct scx_bpf_dsq_insert_vtime_args *args)
5558 {
5559 	struct scx_sched *sch;
5560 
5561 	guard(rcu)();
5562 
5563 	sch = rcu_dereference(scx_root);
5564 	if (unlikely(!sch))
5565 		return false;
5566 
5567 	return scx_dsq_insert_vtime(sch, p, args->dsq_id, args->slice,
5568 				    args->vtime, args->enq_flags);
5569 }
5570 
5571 /*
5572  * COMPAT: Will be removed in v6.23.
5573  */
5574 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id,
5575 					  u64 slice, u64 vtime, u64 enq_flags)
5576 {
5577 	struct scx_sched *sch;
5578 
5579 	guard(rcu)();
5580 
5581 	sch = rcu_dereference(scx_root);
5582 	if (unlikely(!sch))
5583 		return;
5584 
5585 	scx_dsq_insert_vtime(sch, p, dsq_id, slice, vtime, enq_flags);
5586 }
5587 
5588 __bpf_kfunc_end_defs();
5589 
5590 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
5591 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_RCU)
5592 BTF_ID_FLAGS(func, scx_bpf_dsq_insert___compat, KF_RCU)
5593 BTF_ID_FLAGS(func, __scx_bpf_dsq_insert_vtime, KF_RCU)
5594 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU)
5595 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
5596 
5597 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
5598 	.owner			= THIS_MODULE,
5599 	.set			= &scx_kfunc_ids_enqueue_dispatch,
5600 };
5601 
5602 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit,
5603 			 struct task_struct *p, u64 dsq_id, u64 enq_flags)
5604 {
5605 	struct scx_sched *sch = scx_root;
5606 	struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq;
5607 	struct rq *this_rq, *src_rq, *locked_rq;
5608 	bool dispatched = false;
5609 	bool in_balance;
5610 	unsigned long flags;
5611 
5612 	if (!scx_kf_allowed_if_unlocked() &&
5613 	    !scx_kf_allowed(sch, SCX_KF_DISPATCH))
5614 		return false;
5615 
5616 	/*
5617 	 * Can be called from either ops.dispatch() locking this_rq() or any
5618 	 * context where no rq lock is held. If latter, lock @p's task_rq which
5619 	 * we'll likely need anyway.
5620 	 */
5621 	src_rq = task_rq(p);
5622 
5623 	local_irq_save(flags);
5624 	this_rq = this_rq();
5625 	in_balance = this_rq->scx.flags & SCX_RQ_IN_BALANCE;
5626 
5627 	if (in_balance) {
5628 		if (this_rq != src_rq) {
5629 			raw_spin_rq_unlock(this_rq);
5630 			raw_spin_rq_lock(src_rq);
5631 		}
5632 	} else {
5633 		raw_spin_rq_lock(src_rq);
5634 	}
5635 
5636 	/*
5637 	 * If the BPF scheduler keeps calling this function repeatedly, it can
5638 	 * cause similar live-lock conditions as consume_dispatch_q(). Insert a
5639 	 * breather if necessary.
5640 	 */
5641 	scx_breather(src_rq);
5642 
5643 	locked_rq = src_rq;
5644 	raw_spin_lock(&src_dsq->lock);
5645 
5646 	/*
5647 	 * Did someone else get to it? @p could have already left $src_dsq, got
5648 	 * re-enqueud, or be in the process of being consumed by someone else.
5649 	 */
5650 	if (unlikely(p->scx.dsq != src_dsq ||
5651 		     u32_before(kit->cursor.priv, p->scx.dsq_seq) ||
5652 		     p->scx.holding_cpu >= 0) ||
5653 	    WARN_ON_ONCE(src_rq != task_rq(p))) {
5654 		raw_spin_unlock(&src_dsq->lock);
5655 		goto out;
5656 	}
5657 
5658 	/* @p is still on $src_dsq and stable, determine the destination */
5659 	dst_dsq = find_dsq_for_dispatch(sch, this_rq, dsq_id, p);
5660 
5661 	/*
5662 	 * Apply vtime and slice updates before moving so that the new time is
5663 	 * visible before inserting into $dst_dsq. @p is still on $src_dsq but
5664 	 * this is safe as we're locking it.
5665 	 */
5666 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME)
5667 		p->scx.dsq_vtime = kit->vtime;
5668 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE)
5669 		p->scx.slice = kit->slice;
5670 
5671 	/* execute move */
5672 	locked_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq);
5673 	dispatched = true;
5674 out:
5675 	if (in_balance) {
5676 		if (this_rq != locked_rq) {
5677 			raw_spin_rq_unlock(locked_rq);
5678 			raw_spin_rq_lock(this_rq);
5679 		}
5680 	} else {
5681 		raw_spin_rq_unlock_irqrestore(locked_rq, flags);
5682 	}
5683 
5684 	kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE |
5685 			       __SCX_DSQ_ITER_HAS_VTIME);
5686 	return dispatched;
5687 }
5688 
5689 __bpf_kfunc_start_defs();
5690 
5691 /**
5692  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
5693  *
5694  * Can only be called from ops.dispatch().
5695  */
5696 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(void)
5697 {
5698 	struct scx_sched *sch;
5699 
5700 	guard(rcu)();
5701 
5702 	sch = rcu_dereference(scx_root);
5703 	if (unlikely(!sch))
5704 		return 0;
5705 
5706 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
5707 		return 0;
5708 
5709 	return scx_dsp_max_batch - __this_cpu_read(scx_dsp_ctx->cursor);
5710 }
5711 
5712 /**
5713  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
5714  *
5715  * Cancel the latest dispatch. Can be called multiple times to cancel further
5716  * dispatches. Can only be called from ops.dispatch().
5717  */
5718 __bpf_kfunc void scx_bpf_dispatch_cancel(void)
5719 {
5720 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
5721 	struct scx_sched *sch;
5722 
5723 	guard(rcu)();
5724 
5725 	sch = rcu_dereference(scx_root);
5726 	if (unlikely(!sch))
5727 		return;
5728 
5729 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
5730 		return;
5731 
5732 	if (dspc->cursor > 0)
5733 		dspc->cursor--;
5734 	else
5735 		scx_error(sch, "dispatch buffer underflow");
5736 }
5737 
5738 /**
5739  * scx_bpf_dsq_move_to_local - move a task from a DSQ to the current CPU's local DSQ
5740  * @dsq_id: DSQ to move task from
5741  *
5742  * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's
5743  * local DSQ for execution. Can only be called from ops.dispatch().
5744  *
5745  * This function flushes the in-flight dispatches from scx_bpf_dsq_insert()
5746  * before trying to move from the specified DSQ. It may also grab rq locks and
5747  * thus can't be called under any BPF locks.
5748  *
5749  * Returns %true if a task has been moved, %false if there isn't any task to
5750  * move.
5751  */
5752 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id)
5753 {
5754 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
5755 	struct scx_dispatch_q *dsq;
5756 	struct scx_sched *sch;
5757 
5758 	guard(rcu)();
5759 
5760 	sch = rcu_dereference(scx_root);
5761 	if (unlikely(!sch))
5762 		return false;
5763 
5764 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
5765 		return false;
5766 
5767 	flush_dispatch_buf(sch, dspc->rq);
5768 
5769 	dsq = find_user_dsq(sch, dsq_id);
5770 	if (unlikely(!dsq)) {
5771 		scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id);
5772 		return false;
5773 	}
5774 
5775 	if (consume_dispatch_q(sch, dspc->rq, dsq)) {
5776 		/*
5777 		 * A successfully consumed task can be dequeued before it starts
5778 		 * running while the CPU is trying to migrate other dispatched
5779 		 * tasks. Bump nr_tasks to tell balance_scx() to retry on empty
5780 		 * local DSQ.
5781 		 */
5782 		dspc->nr_tasks++;
5783 		return true;
5784 	} else {
5785 		return false;
5786 	}
5787 }
5788 
5789 /**
5790  * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs
5791  * @it__iter: DSQ iterator in progress
5792  * @slice: duration the moved task can run for in nsecs
5793  *
5794  * Override the slice of the next task that will be moved from @it__iter using
5795  * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous
5796  * slice duration is kept.
5797  */
5798 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter,
5799 					    u64 slice)
5800 {
5801 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
5802 
5803 	kit->slice = slice;
5804 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE;
5805 }
5806 
5807 /**
5808  * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs
5809  * @it__iter: DSQ iterator in progress
5810  * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ
5811  *
5812  * Override the vtime of the next task that will be moved from @it__iter using
5813  * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice
5814  * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the
5815  * override is ignored and cleared.
5816  */
5817 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter,
5818 					    u64 vtime)
5819 {
5820 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
5821 
5822 	kit->vtime = vtime;
5823 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME;
5824 }
5825 
5826 /**
5827  * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ
5828  * @it__iter: DSQ iterator in progress
5829  * @p: task to transfer
5830  * @dsq_id: DSQ to move @p to
5831  * @enq_flags: SCX_ENQ_*
5832  *
5833  * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ
5834  * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can
5835  * be the destination.
5836  *
5837  * For the transfer to be successful, @p must still be on the DSQ and have been
5838  * queued before the DSQ iteration started. This function doesn't care whether
5839  * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have
5840  * been queued before the iteration started.
5841  *
5842  * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update.
5843  *
5844  * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq
5845  * lock (e.g. BPF timers or SYSCALL programs).
5846  *
5847  * Returns %true if @p has been consumed, %false if @p had already been
5848  * consumed, dequeued, or, for sub-scheds, @dsq_id points to a disallowed local
5849  * DSQ.
5850  */
5851 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter,
5852 				  struct task_struct *p, u64 dsq_id,
5853 				  u64 enq_flags)
5854 {
5855 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
5856 			    p, dsq_id, enq_flags);
5857 }
5858 
5859 /**
5860  * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ
5861  * @it__iter: DSQ iterator in progress
5862  * @p: task to transfer
5863  * @dsq_id: DSQ to move @p to
5864  * @enq_flags: SCX_ENQ_*
5865  *
5866  * Transfer @p which is on the DSQ currently iterated by @it__iter to the
5867  * priority queue of the DSQ specified by @dsq_id. The destination must be a
5868  * user DSQ as only user DSQs support priority queue.
5869  *
5870  * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice()
5871  * and scx_bpf_dsq_move_set_vtime() to update.
5872  *
5873  * All other aspects are identical to scx_bpf_dsq_move(). See
5874  * scx_bpf_dsq_insert_vtime() for more information on @vtime.
5875  */
5876 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter,
5877 					struct task_struct *p, u64 dsq_id,
5878 					u64 enq_flags)
5879 {
5880 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
5881 			    p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
5882 }
5883 
5884 __bpf_kfunc_end_defs();
5885 
5886 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
5887 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots)
5888 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel)
5889 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local)
5890 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
5891 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
5892 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
5893 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
5894 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
5895 
5896 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
5897 	.owner			= THIS_MODULE,
5898 	.set			= &scx_kfunc_ids_dispatch,
5899 };
5900 
5901 __bpf_kfunc_start_defs();
5902 
5903 /**
5904  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
5905  *
5906  * Iterate over all of the tasks currently enqueued on the local DSQ of the
5907  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
5908  * processed tasks. Can only be called from ops.cpu_release().
5909  */
5910 __bpf_kfunc u32 scx_bpf_reenqueue_local(void)
5911 {
5912 	struct scx_sched *sch;
5913 	LIST_HEAD(tasks);
5914 	u32 nr_enqueued = 0;
5915 	struct rq *rq;
5916 	struct task_struct *p, *n;
5917 
5918 	guard(rcu)();
5919 	sch = rcu_dereference(scx_root);
5920 	if (unlikely(!sch))
5921 		return 0;
5922 
5923 	if (!scx_kf_allowed(sch, SCX_KF_CPU_RELEASE))
5924 		return 0;
5925 
5926 	rq = cpu_rq(smp_processor_id());
5927 	lockdep_assert_rq_held(rq);
5928 
5929 	/*
5930 	 * The BPF scheduler may choose to dispatch tasks back to
5931 	 * @rq->scx.local_dsq. Move all candidate tasks off to a private list
5932 	 * first to avoid processing the same tasks repeatedly.
5933 	 */
5934 	list_for_each_entry_safe(p, n, &rq->scx.local_dsq.list,
5935 				 scx.dsq_list.node) {
5936 		/*
5937 		 * If @p is being migrated, @p's current CPU may not agree with
5938 		 * its allowed CPUs and the migration_cpu_stop is about to
5939 		 * deactivate and re-activate @p anyway. Skip re-enqueueing.
5940 		 *
5941 		 * While racing sched property changes may also dequeue and
5942 		 * re-enqueue a migrating task while its current CPU and allowed
5943 		 * CPUs disagree, they use %ENQUEUE_RESTORE which is bypassed to
5944 		 * the current local DSQ for running tasks and thus are not
5945 		 * visible to the BPF scheduler.
5946 		 */
5947 		if (p->migration_pending)
5948 			continue;
5949 
5950 		dispatch_dequeue(rq, p);
5951 		list_add_tail(&p->scx.dsq_list.node, &tasks);
5952 	}
5953 
5954 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
5955 		list_del_init(&p->scx.dsq_list.node);
5956 		do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
5957 		nr_enqueued++;
5958 	}
5959 
5960 	return nr_enqueued;
5961 }
5962 
5963 __bpf_kfunc_end_defs();
5964 
5965 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
5966 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local)
5967 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
5968 
5969 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
5970 	.owner			= THIS_MODULE,
5971 	.set			= &scx_kfunc_ids_cpu_release,
5972 };
5973 
5974 __bpf_kfunc_start_defs();
5975 
5976 /**
5977  * scx_bpf_create_dsq - Create a custom DSQ
5978  * @dsq_id: DSQ to create
5979  * @node: NUMA node to allocate from
5980  *
5981  * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable
5982  * scx callback, and any BPF_PROG_TYPE_SYSCALL prog.
5983  */
5984 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node)
5985 {
5986 	struct scx_dispatch_q *dsq;
5987 	struct scx_sched *sch;
5988 	s32 ret;
5989 
5990 	if (unlikely(node >= (int)nr_node_ids ||
5991 		     (node < 0 && node != NUMA_NO_NODE)))
5992 		return -EINVAL;
5993 
5994 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN))
5995 		return -EINVAL;
5996 
5997 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
5998 	if (!dsq)
5999 		return -ENOMEM;
6000 
6001 	init_dsq(dsq, dsq_id);
6002 
6003 	rcu_read_lock();
6004 
6005 	sch = rcu_dereference(scx_root);
6006 	if (sch)
6007 		ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node,
6008 						    dsq_hash_params);
6009 	else
6010 		ret = -ENODEV;
6011 
6012 	rcu_read_unlock();
6013 	if (ret)
6014 		kfree(dsq);
6015 	return ret;
6016 }
6017 
6018 __bpf_kfunc_end_defs();
6019 
6020 BTF_KFUNCS_START(scx_kfunc_ids_unlocked)
6021 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_SLEEPABLE)
6022 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
6023 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
6024 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
6025 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
6026 BTF_KFUNCS_END(scx_kfunc_ids_unlocked)
6027 
6028 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = {
6029 	.owner			= THIS_MODULE,
6030 	.set			= &scx_kfunc_ids_unlocked,
6031 };
6032 
6033 __bpf_kfunc_start_defs();
6034 
6035 /**
6036  * scx_bpf_task_set_slice - Set task's time slice
6037  * @p: task of interest
6038  * @slice: time slice to set in nsecs
6039  *
6040  * Set @p's time slice to @slice. Returns %true on success, %false if the
6041  * calling scheduler doesn't have authority over @p.
6042  */
6043 __bpf_kfunc bool scx_bpf_task_set_slice(struct task_struct *p, u64 slice)
6044 {
6045 	p->scx.slice = slice;
6046 	return true;
6047 }
6048 
6049 /**
6050  * scx_bpf_task_set_dsq_vtime - Set task's virtual time for DSQ ordering
6051  * @p: task of interest
6052  * @vtime: virtual time to set
6053  *
6054  * Set @p's virtual time to @vtime. Returns %true on success, %false if the
6055  * calling scheduler doesn't have authority over @p.
6056  */
6057 __bpf_kfunc bool scx_bpf_task_set_dsq_vtime(struct task_struct *p, u64 vtime)
6058 {
6059 	p->scx.dsq_vtime = vtime;
6060 	return true;
6061 }
6062 
6063 static void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags)
6064 {
6065 	struct rq *this_rq;
6066 	unsigned long irq_flags;
6067 
6068 	if (!ops_cpu_valid(sch, cpu, NULL))
6069 		return;
6070 
6071 	local_irq_save(irq_flags);
6072 
6073 	this_rq = this_rq();
6074 
6075 	/*
6076 	 * While bypassing for PM ops, IRQ handling may not be online which can
6077 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
6078 	 * IRQ status update. Suppress kicking.
6079 	 */
6080 	if (scx_rq_bypassing(this_rq))
6081 		goto out;
6082 
6083 	/*
6084 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
6085 	 * rq locks. We can probably be smarter and avoid bouncing if called
6086 	 * from ops which don't hold a rq lock.
6087 	 */
6088 	if (flags & SCX_KICK_IDLE) {
6089 		struct rq *target_rq = cpu_rq(cpu);
6090 
6091 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT)))
6092 			scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
6093 
6094 		if (raw_spin_rq_trylock(target_rq)) {
6095 			if (can_skip_idle_kick(target_rq)) {
6096 				raw_spin_rq_unlock(target_rq);
6097 				goto out;
6098 			}
6099 			raw_spin_rq_unlock(target_rq);
6100 		}
6101 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick_if_idle);
6102 	} else {
6103 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick);
6104 
6105 		if (flags & SCX_KICK_PREEMPT)
6106 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_preempt);
6107 		if (flags & SCX_KICK_WAIT)
6108 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_wait);
6109 	}
6110 
6111 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
6112 out:
6113 	local_irq_restore(irq_flags);
6114 }
6115 
6116 /**
6117  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
6118  * @cpu: cpu to kick
6119  * @flags: %SCX_KICK_* flags
6120  *
6121  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
6122  * trigger rescheduling on a busy CPU. This can be called from any online
6123  * scx_ops operation and the actual kicking is performed asynchronously through
6124  * an irq work.
6125  */
6126 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags)
6127 {
6128 	struct scx_sched *sch;
6129 
6130 	guard(rcu)();
6131 	sch = rcu_dereference(scx_root);
6132 	if (likely(sch))
6133 		scx_kick_cpu(sch, cpu, flags);
6134 }
6135 
6136 /**
6137  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
6138  * @dsq_id: id of the DSQ
6139  *
6140  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
6141  * -%ENOENT is returned.
6142  */
6143 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id)
6144 {
6145 	struct scx_sched *sch;
6146 	struct scx_dispatch_q *dsq;
6147 	s32 ret;
6148 
6149 	preempt_disable();
6150 
6151 	sch = rcu_dereference_sched(scx_root);
6152 	if (unlikely(!sch)) {
6153 		ret = -ENODEV;
6154 		goto out;
6155 	}
6156 
6157 	if (dsq_id == SCX_DSQ_LOCAL) {
6158 		ret = READ_ONCE(this_rq()->scx.local_dsq.nr);
6159 		goto out;
6160 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
6161 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
6162 
6163 		if (ops_cpu_valid(sch, cpu, NULL)) {
6164 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
6165 			goto out;
6166 		}
6167 	} else {
6168 		dsq = find_user_dsq(sch, dsq_id);
6169 		if (dsq) {
6170 			ret = READ_ONCE(dsq->nr);
6171 			goto out;
6172 		}
6173 	}
6174 	ret = -ENOENT;
6175 out:
6176 	preempt_enable();
6177 	return ret;
6178 }
6179 
6180 /**
6181  * scx_bpf_destroy_dsq - Destroy a custom DSQ
6182  * @dsq_id: DSQ to destroy
6183  *
6184  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
6185  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
6186  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
6187  * which doesn't exist. Can be called from any online scx_ops operations.
6188  */
6189 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id)
6190 {
6191 	struct scx_sched *sch;
6192 
6193 	rcu_read_lock();
6194 	sch = rcu_dereference(scx_root);
6195 	if (sch)
6196 		destroy_dsq(sch, dsq_id);
6197 	rcu_read_unlock();
6198 }
6199 
6200 /**
6201  * bpf_iter_scx_dsq_new - Create a DSQ iterator
6202  * @it: iterator to initialize
6203  * @dsq_id: DSQ to iterate
6204  * @flags: %SCX_DSQ_ITER_*
6205  *
6206  * Initialize BPF iterator @it which can be used with bpf_for_each() to walk
6207  * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes
6208  * tasks which are already queued when this function is invoked.
6209  */
6210 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id,
6211 				     u64 flags)
6212 {
6213 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
6214 	struct scx_sched *sch;
6215 
6216 	BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) >
6217 		     sizeof(struct bpf_iter_scx_dsq));
6218 	BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) !=
6219 		     __alignof__(struct bpf_iter_scx_dsq));
6220 
6221 	/*
6222 	 * next() and destroy() will be called regardless of the return value.
6223 	 * Always clear $kit->dsq.
6224 	 */
6225 	kit->dsq = NULL;
6226 
6227 	sch = rcu_dereference_check(scx_root, rcu_read_lock_bh_held());
6228 	if (unlikely(!sch))
6229 		return -ENODEV;
6230 
6231 	if (flags & ~__SCX_DSQ_ITER_USER_FLAGS)
6232 		return -EINVAL;
6233 
6234 	kit->dsq = find_user_dsq(sch, dsq_id);
6235 	if (!kit->dsq)
6236 		return -ENOENT;
6237 
6238 	INIT_LIST_HEAD(&kit->cursor.node);
6239 	kit->cursor.flags = SCX_DSQ_LNODE_ITER_CURSOR | flags;
6240 	kit->cursor.priv = READ_ONCE(kit->dsq->seq);
6241 
6242 	return 0;
6243 }
6244 
6245 /**
6246  * bpf_iter_scx_dsq_next - Progress a DSQ iterator
6247  * @it: iterator to progress
6248  *
6249  * Return the next task. See bpf_iter_scx_dsq_new().
6250  */
6251 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it)
6252 {
6253 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
6254 	bool rev = kit->cursor.flags & SCX_DSQ_ITER_REV;
6255 	struct task_struct *p;
6256 	unsigned long flags;
6257 
6258 	if (!kit->dsq)
6259 		return NULL;
6260 
6261 	raw_spin_lock_irqsave(&kit->dsq->lock, flags);
6262 
6263 	if (list_empty(&kit->cursor.node))
6264 		p = NULL;
6265 	else
6266 		p = container_of(&kit->cursor, struct task_struct, scx.dsq_list);
6267 
6268 	/*
6269 	 * Only tasks which were queued before the iteration started are
6270 	 * visible. This bounds BPF iterations and guarantees that vtime never
6271 	 * jumps in the other direction while iterating.
6272 	 */
6273 	do {
6274 		p = nldsq_next_task(kit->dsq, p, rev);
6275 	} while (p && unlikely(u32_before(kit->cursor.priv, p->scx.dsq_seq)));
6276 
6277 	if (p) {
6278 		if (rev)
6279 			list_move_tail(&kit->cursor.node, &p->scx.dsq_list.node);
6280 		else
6281 			list_move(&kit->cursor.node, &p->scx.dsq_list.node);
6282 	} else {
6283 		list_del_init(&kit->cursor.node);
6284 	}
6285 
6286 	raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
6287 
6288 	return p;
6289 }
6290 
6291 /**
6292  * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator
6293  * @it: iterator to destroy
6294  *
6295  * Undo scx_iter_scx_dsq_new().
6296  */
6297 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it)
6298 {
6299 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
6300 
6301 	if (!kit->dsq)
6302 		return;
6303 
6304 	if (!list_empty(&kit->cursor.node)) {
6305 		unsigned long flags;
6306 
6307 		raw_spin_lock_irqsave(&kit->dsq->lock, flags);
6308 		list_del_init(&kit->cursor.node);
6309 		raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
6310 	}
6311 	kit->dsq = NULL;
6312 }
6313 
6314 /**
6315  * scx_bpf_dsq_peek - Lockless peek at the first element.
6316  * @dsq_id: DSQ to examine.
6317  *
6318  * Read the first element in the DSQ. This is semantically equivalent to using
6319  * the DSQ iterator, but is lockfree. Of course, like any lockless operation,
6320  * this provides only a point-in-time snapshot, and the contents may change
6321  * by the time any subsequent locking operation reads the queue.
6322  *
6323  * Returns the pointer, or NULL indicates an empty queue OR internal error.
6324  */
6325 __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id)
6326 {
6327 	struct scx_sched *sch;
6328 	struct scx_dispatch_q *dsq;
6329 
6330 	sch = rcu_dereference(scx_root);
6331 	if (unlikely(!sch))
6332 		return NULL;
6333 
6334 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) {
6335 		scx_error(sch, "peek disallowed on builtin DSQ 0x%llx", dsq_id);
6336 		return NULL;
6337 	}
6338 
6339 	dsq = find_user_dsq(sch, dsq_id);
6340 	if (unlikely(!dsq)) {
6341 		scx_error(sch, "peek on non-existent DSQ 0x%llx", dsq_id);
6342 		return NULL;
6343 	}
6344 
6345 	return rcu_dereference(dsq->first_task);
6346 }
6347 
6348 __bpf_kfunc_end_defs();
6349 
6350 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
6351 			 size_t line_size, char *fmt, unsigned long long *data,
6352 			 u32 data__sz)
6353 {
6354 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
6355 	s32 ret;
6356 
6357 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
6358 	    (data__sz && !data)) {
6359 		scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz);
6360 		return -EINVAL;
6361 	}
6362 
6363 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
6364 	if (ret < 0) {
6365 		scx_error(sch, "failed to read data fields (%d)", ret);
6366 		return ret;
6367 	}
6368 
6369 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
6370 				  &bprintf_data);
6371 	if (ret < 0) {
6372 		scx_error(sch, "format preparation failed (%d)", ret);
6373 		return ret;
6374 	}
6375 
6376 	ret = bstr_printf(line_buf, line_size, fmt,
6377 			  bprintf_data.bin_args);
6378 	bpf_bprintf_cleanup(&bprintf_data);
6379 	if (ret < 0) {
6380 		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
6381 		return ret;
6382 	}
6383 
6384 	return ret;
6385 }
6386 
6387 static s32 bstr_format(struct scx_sched *sch, struct scx_bstr_buf *buf,
6388 		       char *fmt, unsigned long long *data, u32 data__sz)
6389 {
6390 	return __bstr_format(sch, buf->data, buf->line, sizeof(buf->line),
6391 			     fmt, data, data__sz);
6392 }
6393 
6394 __bpf_kfunc_start_defs();
6395 
6396 /**
6397  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
6398  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
6399  * @fmt: error message format string
6400  * @data: format string parameters packaged using ___bpf_fill() macro
6401  * @data__sz: @data len, must end in '__sz' for the verifier
6402  *
6403  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
6404  * disabling.
6405  */
6406 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
6407 				   unsigned long long *data, u32 data__sz)
6408 {
6409 	struct scx_sched *sch;
6410 	unsigned long flags;
6411 
6412 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
6413 	sch = rcu_dereference_bh(scx_root);
6414 	if (likely(sch) &&
6415 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
6416 		scx_exit(sch, SCX_EXIT_UNREG_BPF, exit_code, "%s", scx_exit_bstr_buf.line);
6417 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
6418 }
6419 
6420 /**
6421  * scx_bpf_error_bstr - Indicate fatal error
6422  * @fmt: error message format string
6423  * @data: format string parameters packaged using ___bpf_fill() macro
6424  * @data__sz: @data len, must end in '__sz' for the verifier
6425  *
6426  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
6427  * disabling.
6428  */
6429 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
6430 				    u32 data__sz)
6431 {
6432 	struct scx_sched *sch;
6433 	unsigned long flags;
6434 
6435 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
6436 	sch = rcu_dereference_bh(scx_root);
6437 	if (likely(sch) &&
6438 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
6439 		scx_exit(sch, SCX_EXIT_ERROR_BPF, 0, "%s", scx_exit_bstr_buf.line);
6440 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
6441 }
6442 
6443 /**
6444  * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler
6445  * @fmt: format string
6446  * @data: format string parameters packaged using ___bpf_fill() macro
6447  * @data__sz: @data len, must end in '__sz' for the verifier
6448  *
6449  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
6450  * dump_task() to generate extra debug dump specific to the BPF scheduler.
6451  *
6452  * The extra dump may be multiple lines. A single line may be split over
6453  * multiple calls. The last line is automatically terminated.
6454  */
6455 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
6456 				   u32 data__sz)
6457 {
6458 	struct scx_sched *sch;
6459 	struct scx_dump_data *dd = &scx_dump_data;
6460 	struct scx_bstr_buf *buf = &dd->buf;
6461 	s32 ret;
6462 
6463 	guard(rcu)();
6464 
6465 	sch = rcu_dereference(scx_root);
6466 	if (unlikely(!sch))
6467 		return;
6468 
6469 	if (raw_smp_processor_id() != dd->cpu) {
6470 		scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends");
6471 		return;
6472 	}
6473 
6474 	/* append the formatted string to the line buf */
6475 	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
6476 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
6477 	if (ret < 0) {
6478 		dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
6479 			  dd->prefix, fmt, data, data__sz, ret);
6480 		return;
6481 	}
6482 
6483 	dd->cursor += ret;
6484 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
6485 
6486 	if (!dd->cursor)
6487 		return;
6488 
6489 	/*
6490 	 * If the line buf overflowed or ends in a newline, flush it into the
6491 	 * dump. This is to allow the caller to generate a single line over
6492 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
6493 	 * the line buf, the only case which can lead to an unexpected
6494 	 * truncation is when the caller keeps generating newlines in the middle
6495 	 * instead of the end consecutively. Don't do that.
6496 	 */
6497 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
6498 		ops_dump_flush();
6499 }
6500 
6501 /**
6502  * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU
6503  * @cpu: CPU of interest
6504  *
6505  * Return the maximum relative capacity of @cpu in relation to the most
6506  * performant CPU in the system. The return value is in the range [1,
6507  * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur().
6508  */
6509 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu)
6510 {
6511 	struct scx_sched *sch;
6512 
6513 	guard(rcu)();
6514 
6515 	sch = rcu_dereference(scx_root);
6516 	if (likely(sch) && ops_cpu_valid(sch, cpu, NULL))
6517 		return arch_scale_cpu_capacity(cpu);
6518 	else
6519 		return SCX_CPUPERF_ONE;
6520 }
6521 
6522 /**
6523  * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU
6524  * @cpu: CPU of interest
6525  *
6526  * Return the current relative performance of @cpu in relation to its maximum.
6527  * The return value is in the range [1, %SCX_CPUPERF_ONE].
6528  *
6529  * The current performance level of a CPU in relation to the maximum performance
6530  * available in the system can be calculated as follows:
6531  *
6532  *   scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE
6533  *
6534  * The result is in the range [1, %SCX_CPUPERF_ONE].
6535  */
6536 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu)
6537 {
6538 	struct scx_sched *sch;
6539 
6540 	guard(rcu)();
6541 
6542 	sch = rcu_dereference(scx_root);
6543 	if (likely(sch) && ops_cpu_valid(sch, cpu, NULL))
6544 		return arch_scale_freq_capacity(cpu);
6545 	else
6546 		return SCX_CPUPERF_ONE;
6547 }
6548 
6549 /**
6550  * scx_bpf_cpuperf_set - Set the relative performance target of a CPU
6551  * @cpu: CPU of interest
6552  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
6553  *
6554  * Set the target performance level of @cpu to @perf. @perf is in linear
6555  * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the
6556  * schedutil cpufreq governor chooses the target frequency.
6557  *
6558  * The actual performance level chosen, CPU grouping, and the overhead and
6559  * latency of the operations are dependent on the hardware and cpufreq driver in
6560  * use. Consult hardware and cpufreq documentation for more information. The
6561  * current performance level can be monitored using scx_bpf_cpuperf_cur().
6562  */
6563 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf)
6564 {
6565 	struct scx_sched *sch;
6566 
6567 	guard(rcu)();
6568 
6569 	sch = rcu_dereference(sch);
6570 	if (unlikely(!sch))
6571 		return;
6572 
6573 	if (unlikely(perf > SCX_CPUPERF_ONE)) {
6574 		scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu);
6575 		return;
6576 	}
6577 
6578 	if (ops_cpu_valid(sch, cpu, NULL)) {
6579 		struct rq *rq = cpu_rq(cpu), *locked_rq = scx_locked_rq();
6580 		struct rq_flags rf;
6581 
6582 		/*
6583 		 * When called with an rq lock held, restrict the operation
6584 		 * to the corresponding CPU to prevent ABBA deadlocks.
6585 		 */
6586 		if (locked_rq && rq != locked_rq) {
6587 			scx_error(sch, "Invalid target CPU %d", cpu);
6588 			return;
6589 		}
6590 
6591 		/*
6592 		 * If no rq lock is held, allow to operate on any CPU by
6593 		 * acquiring the corresponding rq lock.
6594 		 */
6595 		if (!locked_rq) {
6596 			rq_lock_irqsave(rq, &rf);
6597 			update_rq_clock(rq);
6598 		}
6599 
6600 		rq->scx.cpuperf_target = perf;
6601 		cpufreq_update_util(rq, 0);
6602 
6603 		if (!locked_rq)
6604 			rq_unlock_irqrestore(rq, &rf);
6605 	}
6606 }
6607 
6608 /**
6609  * scx_bpf_nr_node_ids - Return the number of possible node IDs
6610  *
6611  * All valid node IDs in the system are smaller than the returned value.
6612  */
6613 __bpf_kfunc u32 scx_bpf_nr_node_ids(void)
6614 {
6615 	return nr_node_ids;
6616 }
6617 
6618 /**
6619  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
6620  *
6621  * All valid CPU IDs in the system are smaller than the returned value.
6622  */
6623 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
6624 {
6625 	return nr_cpu_ids;
6626 }
6627 
6628 /**
6629  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
6630  */
6631 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
6632 {
6633 	return cpu_possible_mask;
6634 }
6635 
6636 /**
6637  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
6638  */
6639 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
6640 {
6641 	return cpu_online_mask;
6642 }
6643 
6644 /**
6645  * scx_bpf_put_cpumask - Release a possible/online cpumask
6646  * @cpumask: cpumask to release
6647  */
6648 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
6649 {
6650 	/*
6651 	 * Empty function body because we aren't actually acquiring or releasing
6652 	 * a reference to a global cpumask, which is read-only in the caller and
6653 	 * is never released. The acquire / release semantics here are just used
6654 	 * to make the cpumask is a trusted pointer in the caller.
6655 	 */
6656 }
6657 
6658 /**
6659  * scx_bpf_task_running - Is task currently running?
6660  * @p: task of interest
6661  */
6662 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
6663 {
6664 	return task_rq(p)->curr == p;
6665 }
6666 
6667 /**
6668  * scx_bpf_task_cpu - CPU a task is currently associated with
6669  * @p: task of interest
6670  */
6671 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
6672 {
6673 	return task_cpu(p);
6674 }
6675 
6676 /**
6677  * scx_bpf_cpu_rq - Fetch the rq of a CPU
6678  * @cpu: CPU of the rq
6679  */
6680 __bpf_kfunc struct rq *scx_bpf_cpu_rq(s32 cpu)
6681 {
6682 	struct scx_sched *sch;
6683 
6684 	guard(rcu)();
6685 
6686 	sch = rcu_dereference(scx_root);
6687 	if (unlikely(!sch))
6688 		return NULL;
6689 
6690 	if (!ops_cpu_valid(sch, cpu, NULL))
6691 		return NULL;
6692 
6693 	if (!sch->warned_deprecated_rq) {
6694 		printk_deferred(KERN_WARNING "sched_ext: %s() is deprecated; "
6695 				"use scx_bpf_locked_rq() when holding rq lock "
6696 				"or scx_bpf_cpu_curr() to read remote curr safely.\n", __func__);
6697 		sch->warned_deprecated_rq = true;
6698 	}
6699 
6700 	return cpu_rq(cpu);
6701 }
6702 
6703 /**
6704  * scx_bpf_locked_rq - Return the rq currently locked by SCX
6705  *
6706  * Returns the rq if a rq lock is currently held by SCX.
6707  * Otherwise emits an error and returns NULL.
6708  */
6709 __bpf_kfunc struct rq *scx_bpf_locked_rq(void)
6710 {
6711 	struct scx_sched *sch;
6712 	struct rq *rq;
6713 
6714 	guard(preempt)();
6715 
6716 	sch = rcu_dereference_sched(scx_root);
6717 	if (unlikely(!sch))
6718 		return NULL;
6719 
6720 	rq = scx_locked_rq();
6721 	if (!rq) {
6722 		scx_error(sch, "accessing rq without holding rq lock");
6723 		return NULL;
6724 	}
6725 
6726 	return rq;
6727 }
6728 
6729 /**
6730  * scx_bpf_cpu_curr - Return remote CPU's curr task
6731  * @cpu: CPU of interest
6732  *
6733  * Callers must hold RCU read lock (KF_RCU).
6734  */
6735 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu)
6736 {
6737 	struct scx_sched *sch;
6738 
6739 	guard(rcu)();
6740 
6741 	sch = rcu_dereference(scx_root);
6742 	if (unlikely(!sch))
6743 		return NULL;
6744 
6745 	if (!ops_cpu_valid(sch, cpu, NULL))
6746 		return NULL;
6747 
6748 	return rcu_dereference(cpu_rq(cpu)->curr);
6749 }
6750 
6751 /**
6752  * scx_bpf_task_cgroup - Return the sched cgroup of a task
6753  * @p: task of interest
6754  *
6755  * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with
6756  * from the scheduler's POV. SCX operations should use this function to
6757  * determine @p's current cgroup as, unlike following @p->cgroups,
6758  * @p->sched_task_group is protected by @p's rq lock and thus atomic w.r.t. all
6759  * rq-locked operations. Can be called on the parameter tasks of rq-locked
6760  * operations. The restriction guarantees that @p's rq is locked by the caller.
6761  */
6762 #ifdef CONFIG_CGROUP_SCHED
6763 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p)
6764 {
6765 	struct task_group *tg = p->sched_task_group;
6766 	struct cgroup *cgrp = &cgrp_dfl_root.cgrp;
6767 	struct scx_sched *sch;
6768 
6769 	guard(rcu)();
6770 
6771 	sch = rcu_dereference(scx_root);
6772 	if (unlikely(!sch))
6773 		goto out;
6774 
6775 	if (!scx_kf_allowed_on_arg_tasks(sch, __SCX_KF_RQ_LOCKED, p))
6776 		goto out;
6777 
6778 	cgrp = tg_cgrp(tg);
6779 
6780 out:
6781 	cgroup_get(cgrp);
6782 	return cgrp;
6783 }
6784 #endif
6785 
6786 /**
6787  * scx_bpf_now - Returns a high-performance monotonically non-decreasing
6788  * clock for the current CPU. The clock returned is in nanoseconds.
6789  *
6790  * It provides the following properties:
6791  *
6792  * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently
6793  *  to account for execution time and track tasks' runtime properties.
6794  *  Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which
6795  *  eventually reads a hardware timestamp counter -- is neither performant nor
6796  *  scalable. scx_bpf_now() aims to provide a high-performance clock by
6797  *  using the rq clock in the scheduler core whenever possible.
6798  *
6799  * 2) High enough resolution for the BPF scheduler use cases: In most BPF
6800  *  scheduler use cases, the required clock resolution is lower than the most
6801  *  accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically
6802  *  uses the rq clock in the scheduler core whenever it is valid. It considers
6803  *  that the rq clock is valid from the time the rq clock is updated
6804  *  (update_rq_clock) until the rq is unlocked (rq_unpin_lock).
6805  *
6806  * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now()
6807  *  guarantees the clock never goes backward when comparing them in the same
6808  *  CPU. On the other hand, when comparing clocks in different CPUs, there
6809  *  is no such guarantee -- the clock can go backward. It provides a
6810  *  monotonically *non-decreasing* clock so that it would provide the same
6811  *  clock values in two different scx_bpf_now() calls in the same CPU
6812  *  during the same period of when the rq clock is valid.
6813  */
6814 __bpf_kfunc u64 scx_bpf_now(void)
6815 {
6816 	struct rq *rq;
6817 	u64 clock;
6818 
6819 	preempt_disable();
6820 
6821 	rq = this_rq();
6822 	if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) {
6823 		/*
6824 		 * If the rq clock is valid, use the cached rq clock.
6825 		 *
6826 		 * Note that scx_bpf_now() is re-entrant between a process
6827 		 * context and an interrupt context (e.g., timer interrupt).
6828 		 * However, we don't need to consider the race between them
6829 		 * because such race is not observable from a caller.
6830 		 */
6831 		clock = READ_ONCE(rq->scx.clock);
6832 	} else {
6833 		/*
6834 		 * Otherwise, return a fresh rq clock.
6835 		 *
6836 		 * The rq clock is updated outside of the rq lock.
6837 		 * In this case, keep the updated rq clock invalid so the next
6838 		 * kfunc call outside the rq lock gets a fresh rq clock.
6839 		 */
6840 		clock = sched_clock_cpu(cpu_of(rq));
6841 	}
6842 
6843 	preempt_enable();
6844 
6845 	return clock;
6846 }
6847 
6848 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events)
6849 {
6850 	struct scx_event_stats *e_cpu;
6851 	int cpu;
6852 
6853 	/* Aggregate per-CPU event counters into @events. */
6854 	memset(events, 0, sizeof(*events));
6855 	for_each_possible_cpu(cpu) {
6856 		e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats;
6857 		scx_agg_event(events, e_cpu, SCX_EV_SELECT_CPU_FALLBACK);
6858 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
6859 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_KEEP_LAST);
6860 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_EXITING);
6861 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
6862 		scx_agg_event(events, e_cpu, SCX_EV_REFILL_SLICE_DFL);
6863 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DURATION);
6864 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DISPATCH);
6865 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_ACTIVATE);
6866 	}
6867 }
6868 
6869 /*
6870  * scx_bpf_events - Get a system-wide event counter to
6871  * @events: output buffer from a BPF program
6872  * @events__sz: @events len, must end in '__sz'' for the verifier
6873  */
6874 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events,
6875 				size_t events__sz)
6876 {
6877 	struct scx_sched *sch;
6878 	struct scx_event_stats e_sys;
6879 
6880 	rcu_read_lock();
6881 	sch = rcu_dereference(scx_root);
6882 	if (sch)
6883 		scx_read_events(sch, &e_sys);
6884 	else
6885 		memset(&e_sys, 0, sizeof(e_sys));
6886 	rcu_read_unlock();
6887 
6888 	/*
6889 	 * We cannot entirely trust a BPF-provided size since a BPF program
6890 	 * might be compiled against a different vmlinux.h, of which
6891 	 * scx_event_stats would be larger (a newer vmlinux.h) or smaller
6892 	 * (an older vmlinux.h). Hence, we use the smaller size to avoid
6893 	 * memory corruption.
6894 	 */
6895 	events__sz = min(events__sz, sizeof(*events));
6896 	memcpy(events, &e_sys, events__sz);
6897 }
6898 
6899 __bpf_kfunc_end_defs();
6900 
6901 BTF_KFUNCS_START(scx_kfunc_ids_any)
6902 BTF_ID_FLAGS(func, scx_bpf_task_set_slice, KF_RCU);
6903 BTF_ID_FLAGS(func, scx_bpf_task_set_dsq_vtime, KF_RCU);
6904 BTF_ID_FLAGS(func, scx_bpf_kick_cpu)
6905 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued)
6906 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq)
6907 BTF_ID_FLAGS(func, scx_bpf_dsq_peek, KF_RCU_PROTECTED | KF_RET_NULL)
6908 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_ITER_NEW | KF_RCU_PROTECTED)
6909 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
6910 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
6911 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_TRUSTED_ARGS)
6912 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_TRUSTED_ARGS)
6913 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_TRUSTED_ARGS)
6914 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap)
6915 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur)
6916 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set)
6917 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
6918 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
6919 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
6920 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
6921 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
6922 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
6923 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
6924 BTF_ID_FLAGS(func, scx_bpf_cpu_rq)
6925 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_RET_NULL)
6926 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_RET_NULL | KF_RCU_PROTECTED)
6927 #ifdef CONFIG_CGROUP_SCHED
6928 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_RCU | KF_ACQUIRE)
6929 #endif
6930 BTF_ID_FLAGS(func, scx_bpf_now)
6931 BTF_ID_FLAGS(func, scx_bpf_events, KF_TRUSTED_ARGS)
6932 BTF_KFUNCS_END(scx_kfunc_ids_any)
6933 
6934 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
6935 	.owner			= THIS_MODULE,
6936 	.set			= &scx_kfunc_ids_any,
6937 };
6938 
6939 static int __init scx_init(void)
6940 {
6941 	int ret;
6942 
6943 	/*
6944 	 * kfunc registration can't be done from init_sched_ext_class() as
6945 	 * register_btf_kfunc_id_set() needs most of the system to be up.
6946 	 *
6947 	 * Some kfuncs are context-sensitive and can only be called from
6948 	 * specific SCX ops. They are grouped into BTF sets accordingly.
6949 	 * Unfortunately, BPF currently doesn't have a way of enforcing such
6950 	 * restrictions. Eventually, the verifier should be able to enforce
6951 	 * them. For now, register them the same and make each kfunc explicitly
6952 	 * check using scx_kf_allowed().
6953 	 */
6954 	if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6955 					     &scx_kfunc_set_enqueue_dispatch)) ||
6956 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6957 					     &scx_kfunc_set_dispatch)) ||
6958 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6959 					     &scx_kfunc_set_cpu_release)) ||
6960 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6961 					     &scx_kfunc_set_unlocked)) ||
6962 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
6963 					     &scx_kfunc_set_unlocked)) ||
6964 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6965 					     &scx_kfunc_set_any)) ||
6966 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
6967 					     &scx_kfunc_set_any)) ||
6968 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
6969 					     &scx_kfunc_set_any))) {
6970 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
6971 		return ret;
6972 	}
6973 
6974 	ret = scx_idle_init();
6975 	if (ret) {
6976 		pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret);
6977 		return ret;
6978 	}
6979 
6980 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops);
6981 	if (ret) {
6982 		pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret);
6983 		return ret;
6984 	}
6985 
6986 	ret = register_pm_notifier(&scx_pm_notifier);
6987 	if (ret) {
6988 		pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret);
6989 		return ret;
6990 	}
6991 
6992 	scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj);
6993 	if (!scx_kset) {
6994 		pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n");
6995 		return -ENOMEM;
6996 	}
6997 
6998 	ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group);
6999 	if (ret < 0) {
7000 		pr_err("sched_ext: Failed to add global attributes\n");
7001 		return ret;
7002 	}
7003 
7004 	return 0;
7005 }
7006 __initcall(scx_init);
7007