xref: /linux/kernel/sched/ext.c (revision 2dbbdeda77a61b39dc4a34dfce873907cfea2c4b)
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_CB_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_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 void process_ddsp_deferred_locals(struct rq *rq)
2176 {
2177 	struct task_struct *p;
2178 
2179 	lockdep_assert_rq_held(rq);
2180 
2181 	/*
2182 	 * Now that @rq can be unlocked, execute the deferred enqueueing of
2183 	 * tasks directly dispatched to the local DSQs of other CPUs. See
2184 	 * direct_dispatch(). Keep popping from the head instead of using
2185 	 * list_for_each_entry_safe() as dispatch_local_dsq() may unlock @rq
2186 	 * temporarily.
2187 	 */
2188 	while ((p = list_first_entry_or_null(&rq->scx.ddsp_deferred_locals,
2189 				struct task_struct, scx.dsq_list.node))) {
2190 		struct scx_sched *sch = scx_root;
2191 		struct scx_dispatch_q *dsq;
2192 
2193 		list_del_init(&p->scx.dsq_list.node);
2194 
2195 		dsq = find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, p);
2196 		if (!WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL))
2197 			dispatch_to_local_dsq(sch, rq, dsq, p,
2198 					      p->scx.ddsp_enq_flags);
2199 	}
2200 }
2201 
2202 static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first)
2203 {
2204 	struct scx_sched *sch = scx_root;
2205 
2206 	if (p->scx.flags & SCX_TASK_QUEUED) {
2207 		/*
2208 		 * Core-sched might decide to execute @p before it is
2209 		 * dispatched. Call ops_dequeue() to notify the BPF scheduler.
2210 		 */
2211 		ops_dequeue(rq, p, SCX_DEQ_CORE_SCHED_EXEC);
2212 		dispatch_dequeue(rq, p);
2213 	}
2214 
2215 	p->se.exec_start = rq_clock_task(rq);
2216 
2217 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2218 	if (SCX_HAS_OP(sch, running) && (p->scx.flags & SCX_TASK_QUEUED))
2219 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, running, rq, p);
2220 
2221 	clr_task_runnable(p, true);
2222 
2223 	/*
2224 	 * @p is getting newly scheduled or got kicked after someone updated its
2225 	 * slice. Refresh whether tick can be stopped. See scx_can_stop_tick().
2226 	 */
2227 	if ((p->scx.slice == SCX_SLICE_INF) !=
2228 	    (bool)(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) {
2229 		if (p->scx.slice == SCX_SLICE_INF)
2230 			rq->scx.flags |= SCX_RQ_CAN_STOP_TICK;
2231 		else
2232 			rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK;
2233 
2234 		sched_update_tick_dependency(rq);
2235 
2236 		/*
2237 		 * For now, let's refresh the load_avgs just when transitioning
2238 		 * in and out of nohz. In the future, we might want to add a
2239 		 * mechanism which calls the following periodically on
2240 		 * tick-stopped CPUs.
2241 		 */
2242 		update_other_load_avgs(rq);
2243 	}
2244 }
2245 
2246 static enum scx_cpu_preempt_reason
2247 preempt_reason_from_class(const struct sched_class *class)
2248 {
2249 	if (class == &stop_sched_class)
2250 		return SCX_CPU_PREEMPT_STOP;
2251 	if (class == &dl_sched_class)
2252 		return SCX_CPU_PREEMPT_DL;
2253 	if (class == &rt_sched_class)
2254 		return SCX_CPU_PREEMPT_RT;
2255 	return SCX_CPU_PREEMPT_UNKNOWN;
2256 }
2257 
2258 static void switch_class(struct rq *rq, struct task_struct *next)
2259 {
2260 	struct scx_sched *sch = scx_root;
2261 	const struct sched_class *next_class = next->sched_class;
2262 
2263 	/*
2264 	 * Pairs with the smp_load_acquire() issued by a CPU in
2265 	 * kick_cpus_irq_workfn() who is waiting for this CPU to perform a
2266 	 * resched.
2267 	 */
2268 	smp_store_release(&rq->scx.pnt_seq, rq->scx.pnt_seq + 1);
2269 	if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT))
2270 		return;
2271 
2272 	/*
2273 	 * The callback is conceptually meant to convey that the CPU is no
2274 	 * longer under the control of SCX. Therefore, don't invoke the callback
2275 	 * if the next class is below SCX (in which case the BPF scheduler has
2276 	 * actively decided not to schedule any tasks on the CPU).
2277 	 */
2278 	if (sched_class_above(&ext_sched_class, next_class))
2279 		return;
2280 
2281 	/*
2282 	 * At this point we know that SCX was preempted by a higher priority
2283 	 * sched_class, so invoke the ->cpu_release() callback if we have not
2284 	 * done so already. We only send the callback once between SCX being
2285 	 * preempted, and it regaining control of the CPU.
2286 	 *
2287 	 * ->cpu_release() complements ->cpu_acquire(), which is emitted the
2288 	 *  next time that balance_scx() is invoked.
2289 	 */
2290 	if (!rq->scx.cpu_released) {
2291 		if (SCX_HAS_OP(sch, cpu_release)) {
2292 			struct scx_cpu_release_args args = {
2293 				.reason = preempt_reason_from_class(next_class),
2294 				.task = next,
2295 			};
2296 
2297 			SCX_CALL_OP(sch, SCX_KF_CPU_RELEASE, cpu_release, rq,
2298 				    cpu_of(rq), &args);
2299 		}
2300 		rq->scx.cpu_released = true;
2301 	}
2302 }
2303 
2304 static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
2305 			      struct task_struct *next)
2306 {
2307 	struct scx_sched *sch = scx_root;
2308 	update_curr_scx(rq);
2309 
2310 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2311 	if (SCX_HAS_OP(sch, stopping) && (p->scx.flags & SCX_TASK_QUEUED))
2312 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, stopping, rq, p, true);
2313 
2314 	if (p->scx.flags & SCX_TASK_QUEUED) {
2315 		set_task_runnable(rq, p);
2316 
2317 		/*
2318 		 * If @p has slice left and is being put, @p is getting
2319 		 * preempted by a higher priority scheduler class or core-sched
2320 		 * forcing a different task. Leave it at the head of the local
2321 		 * DSQ.
2322 		 */
2323 		if (p->scx.slice && !scx_rq_bypassing(rq)) {
2324 			dispatch_enqueue(sch, &rq->scx.local_dsq, p,
2325 					 SCX_ENQ_HEAD);
2326 			goto switch_class;
2327 		}
2328 
2329 		/*
2330 		 * If @p is runnable but we're about to enter a lower
2331 		 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell
2332 		 * ops.enqueue() that @p is the only one available for this cpu,
2333 		 * which should trigger an explicit follow-up scheduling event.
2334 		 */
2335 		if (sched_class_above(&ext_sched_class, next->sched_class)) {
2336 			WARN_ON_ONCE(!(sch->ops.flags & SCX_OPS_ENQ_LAST));
2337 			do_enqueue_task(rq, p, SCX_ENQ_LAST, -1);
2338 		} else {
2339 			do_enqueue_task(rq, p, 0, -1);
2340 		}
2341 	}
2342 
2343 switch_class:
2344 	if (next && next->sched_class != &ext_sched_class)
2345 		switch_class(rq, next);
2346 }
2347 
2348 static struct task_struct *first_local_task(struct rq *rq)
2349 {
2350 	return list_first_entry_or_null(&rq->scx.local_dsq.list,
2351 					struct task_struct, scx.dsq_list.node);
2352 }
2353 
2354 static struct task_struct *
2355 do_pick_task_scx(struct rq *rq, struct rq_flags *rf, bool force_scx)
2356 {
2357 	struct task_struct *prev = rq->curr;
2358 	bool keep_prev, kick_idle = false;
2359 	struct task_struct *p;
2360 
2361 	rq_modified_clear(rq);
2362 
2363 	rq_unpin_lock(rq, rf);
2364 	balance_one(rq, prev);
2365 	rq_repin_lock(rq, rf);
2366 
2367 	maybe_queue_balance_callback(rq);
2368 
2369 	/*
2370 	 * If any higher-priority sched class enqueued a runnable task on
2371 	 * this rq during balance_one(), abort and return RETRY_TASK, so
2372 	 * that the scheduler loop can restart.
2373 	 *
2374 	 * If @force_scx is true, always try to pick a SCHED_EXT task,
2375 	 * regardless of any higher-priority sched classes activity.
2376 	 */
2377 	if (!force_scx && rq_modified_above(rq, &ext_sched_class))
2378 		return RETRY_TASK;
2379 
2380 	keep_prev = rq->scx.flags & SCX_RQ_BAL_KEEP;
2381 	if (unlikely(keep_prev &&
2382 		     prev->sched_class != &ext_sched_class)) {
2383 		WARN_ON_ONCE(scx_enable_state() == SCX_ENABLED);
2384 		keep_prev = false;
2385 	}
2386 
2387 	/*
2388 	 * If balance_scx() is telling us to keep running @prev, replenish slice
2389 	 * if necessary and keep running @prev. Otherwise, pop the first one
2390 	 * from the local DSQ.
2391 	 */
2392 	if (keep_prev) {
2393 		p = prev;
2394 		if (!p->scx.slice)
2395 			refill_task_slice_dfl(rcu_dereference_sched(scx_root), p);
2396 	} else {
2397 		p = first_local_task(rq);
2398 		if (!p) {
2399 			if (kick_idle)
2400 				scx_kick_cpu(rcu_dereference_sched(scx_root),
2401 					     cpu_of(rq), SCX_KICK_IDLE);
2402 			return NULL;
2403 		}
2404 
2405 		if (unlikely(!p->scx.slice)) {
2406 			struct scx_sched *sch = rcu_dereference_sched(scx_root);
2407 
2408 			if (!scx_rq_bypassing(rq) && !sch->warned_zero_slice) {
2409 				printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in %s()\n",
2410 						p->comm, p->pid, __func__);
2411 				sch->warned_zero_slice = true;
2412 			}
2413 			refill_task_slice_dfl(sch, p);
2414 		}
2415 	}
2416 
2417 	return p;
2418 }
2419 
2420 static struct task_struct *pick_task_scx(struct rq *rq, struct rq_flags *rf)
2421 {
2422 	return do_pick_task_scx(rq, rf, false);
2423 }
2424 
2425 #ifdef CONFIG_SCHED_CORE
2426 /**
2427  * scx_prio_less - Task ordering for core-sched
2428  * @a: task A
2429  * @b: task B
2430  * @in_fi: in forced idle state
2431  *
2432  * Core-sched is implemented as an additional scheduling layer on top of the
2433  * usual sched_class'es and needs to find out the expected task ordering. For
2434  * SCX, core-sched calls this function to interrogate the task ordering.
2435  *
2436  * Unless overridden by ops.core_sched_before(), @p->scx.core_sched_at is used
2437  * to implement the default task ordering. The older the timestamp, the higher
2438  * priority the task - the global FIFO ordering matching the default scheduling
2439  * behavior.
2440  *
2441  * When ops.core_sched_before() is enabled, @p->scx.core_sched_at is used to
2442  * implement FIFO ordering within each local DSQ. See pick_task_scx().
2443  */
2444 bool scx_prio_less(const struct task_struct *a, const struct task_struct *b,
2445 		   bool in_fi)
2446 {
2447 	struct scx_sched *sch = scx_root;
2448 
2449 	/*
2450 	 * The const qualifiers are dropped from task_struct pointers when
2451 	 * calling ops.core_sched_before(). Accesses are controlled by the
2452 	 * verifier.
2453 	 */
2454 	if (SCX_HAS_OP(sch, core_sched_before) &&
2455 	    !scx_rq_bypassing(task_rq(a)))
2456 		return SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, core_sched_before,
2457 					      NULL,
2458 					      (struct task_struct *)a,
2459 					      (struct task_struct *)b);
2460 	else
2461 		return time_after64(a->scx.core_sched_at, b->scx.core_sched_at);
2462 }
2463 #endif	/* CONFIG_SCHED_CORE */
2464 
2465 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags)
2466 {
2467 	struct scx_sched *sch = scx_root;
2468 	bool rq_bypass;
2469 
2470 	/*
2471 	 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it
2472 	 * can be a good migration opportunity with low cache and memory
2473 	 * footprint. Returning a CPU different than @prev_cpu triggers
2474 	 * immediate rq migration. However, for SCX, as the current rq
2475 	 * association doesn't dictate where the task is going to run, this
2476 	 * doesn't fit well. If necessary, we can later add a dedicated method
2477 	 * which can decide to preempt self to force it through the regular
2478 	 * scheduling path.
2479 	 */
2480 	if (unlikely(wake_flags & WF_EXEC))
2481 		return prev_cpu;
2482 
2483 	rq_bypass = scx_rq_bypassing(task_rq(p));
2484 	if (likely(SCX_HAS_OP(sch, select_cpu)) && !rq_bypass) {
2485 		s32 cpu;
2486 		struct task_struct **ddsp_taskp;
2487 
2488 		ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
2489 		WARN_ON_ONCE(*ddsp_taskp);
2490 		*ddsp_taskp = p;
2491 
2492 		cpu = SCX_CALL_OP_TASK_RET(sch,
2493 					   SCX_KF_ENQUEUE | SCX_KF_SELECT_CPU,
2494 					   select_cpu, NULL, p, prev_cpu,
2495 					   wake_flags);
2496 		p->scx.selected_cpu = cpu;
2497 		*ddsp_taskp = NULL;
2498 		if (ops_cpu_valid(sch, cpu, "from ops.select_cpu()"))
2499 			return cpu;
2500 		else
2501 			return prev_cpu;
2502 	} else {
2503 		s32 cpu;
2504 
2505 		cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, NULL, 0);
2506 		if (cpu >= 0) {
2507 			refill_task_slice_dfl(sch, p);
2508 			p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL;
2509 		} else {
2510 			cpu = prev_cpu;
2511 		}
2512 		p->scx.selected_cpu = cpu;
2513 
2514 		if (rq_bypass)
2515 			__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
2516 		return cpu;
2517 	}
2518 }
2519 
2520 static void task_woken_scx(struct rq *rq, struct task_struct *p)
2521 {
2522 	run_deferred(rq);
2523 }
2524 
2525 static void set_cpus_allowed_scx(struct task_struct *p,
2526 				 struct affinity_context *ac)
2527 {
2528 	struct scx_sched *sch = scx_root;
2529 
2530 	set_cpus_allowed_common(p, ac);
2531 
2532 	/*
2533 	 * The effective cpumask is stored in @p->cpus_ptr which may temporarily
2534 	 * differ from the configured one in @p->cpus_mask. Always tell the bpf
2535 	 * scheduler the effective one.
2536 	 *
2537 	 * Fine-grained memory write control is enforced by BPF making the const
2538 	 * designation pointless. Cast it away when calling the operation.
2539 	 */
2540 	if (SCX_HAS_OP(sch, set_cpumask))
2541 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, NULL,
2542 				 p, (struct cpumask *)p->cpus_ptr);
2543 }
2544 
2545 static void handle_hotplug(struct rq *rq, bool online)
2546 {
2547 	struct scx_sched *sch = scx_root;
2548 	int cpu = cpu_of(rq);
2549 
2550 	atomic_long_inc(&scx_hotplug_seq);
2551 
2552 	/*
2553 	 * scx_root updates are protected by cpus_read_lock() and will stay
2554 	 * stable here. Note that we can't depend on scx_enabled() test as the
2555 	 * hotplug ops need to be enabled before __scx_enabled is set.
2556 	 */
2557 	if (unlikely(!sch))
2558 		return;
2559 
2560 	if (scx_enabled())
2561 		scx_idle_update_selcpu_topology(&sch->ops);
2562 
2563 	if (online && SCX_HAS_OP(sch, cpu_online))
2564 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_online, NULL, cpu);
2565 	else if (!online && SCX_HAS_OP(sch, cpu_offline))
2566 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_offline, NULL, cpu);
2567 	else
2568 		scx_exit(sch, SCX_EXIT_UNREG_KERN,
2569 			 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
2570 			 "cpu %d going %s, exiting scheduler", cpu,
2571 			 online ? "online" : "offline");
2572 }
2573 
2574 void scx_rq_activate(struct rq *rq)
2575 {
2576 	handle_hotplug(rq, true);
2577 }
2578 
2579 void scx_rq_deactivate(struct rq *rq)
2580 {
2581 	handle_hotplug(rq, false);
2582 }
2583 
2584 static void rq_online_scx(struct rq *rq)
2585 {
2586 	rq->scx.flags |= SCX_RQ_ONLINE;
2587 }
2588 
2589 static void rq_offline_scx(struct rq *rq)
2590 {
2591 	rq->scx.flags &= ~SCX_RQ_ONLINE;
2592 }
2593 
2594 
2595 static bool check_rq_for_timeouts(struct rq *rq)
2596 {
2597 	struct scx_sched *sch;
2598 	struct task_struct *p;
2599 	struct rq_flags rf;
2600 	bool timed_out = false;
2601 
2602 	rq_lock_irqsave(rq, &rf);
2603 	sch = rcu_dereference_bh(scx_root);
2604 	if (unlikely(!sch))
2605 		goto out_unlock;
2606 
2607 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) {
2608 		unsigned long last_runnable = p->scx.runnable_at;
2609 
2610 		if (unlikely(time_after(jiffies,
2611 					last_runnable + scx_watchdog_timeout))) {
2612 			u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable);
2613 
2614 			scx_exit(sch, SCX_EXIT_ERROR_STALL, 0,
2615 				 "%s[%d] failed to run for %u.%03us",
2616 				 p->comm, p->pid, dur_ms / 1000, dur_ms % 1000);
2617 			timed_out = true;
2618 			break;
2619 		}
2620 	}
2621 out_unlock:
2622 	rq_unlock_irqrestore(rq, &rf);
2623 	return timed_out;
2624 }
2625 
2626 static void scx_watchdog_workfn(struct work_struct *work)
2627 {
2628 	int cpu;
2629 
2630 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
2631 
2632 	for_each_online_cpu(cpu) {
2633 		if (unlikely(check_rq_for_timeouts(cpu_rq(cpu))))
2634 			break;
2635 
2636 		cond_resched();
2637 	}
2638 	queue_delayed_work(system_unbound_wq, to_delayed_work(work),
2639 			   scx_watchdog_timeout / 2);
2640 }
2641 
2642 void scx_tick(struct rq *rq)
2643 {
2644 	struct scx_sched *sch;
2645 	unsigned long last_check;
2646 
2647 	if (!scx_enabled())
2648 		return;
2649 
2650 	sch = rcu_dereference_bh(scx_root);
2651 	if (unlikely(!sch))
2652 		return;
2653 
2654 	last_check = READ_ONCE(scx_watchdog_timestamp);
2655 	if (unlikely(time_after(jiffies,
2656 				last_check + READ_ONCE(scx_watchdog_timeout)))) {
2657 		u32 dur_ms = jiffies_to_msecs(jiffies - last_check);
2658 
2659 		scx_exit(sch, SCX_EXIT_ERROR_STALL, 0,
2660 			 "watchdog failed to check in for %u.%03us",
2661 			 dur_ms / 1000, dur_ms % 1000);
2662 	}
2663 
2664 	update_other_load_avgs(rq);
2665 }
2666 
2667 static void task_tick_scx(struct rq *rq, struct task_struct *curr, int queued)
2668 {
2669 	struct scx_sched *sch = scx_root;
2670 
2671 	update_curr_scx(rq);
2672 
2673 	/*
2674 	 * While disabling, always resched and refresh core-sched timestamp as
2675 	 * we can't trust the slice management or ops.core_sched_before().
2676 	 */
2677 	if (scx_rq_bypassing(rq)) {
2678 		curr->scx.slice = 0;
2679 		touch_core_sched(rq, curr);
2680 	} else if (SCX_HAS_OP(sch, tick)) {
2681 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, tick, rq, curr);
2682 	}
2683 
2684 	if (!curr->scx.slice)
2685 		resched_curr(rq);
2686 }
2687 
2688 #ifdef CONFIG_EXT_GROUP_SCHED
2689 static struct cgroup *tg_cgrp(struct task_group *tg)
2690 {
2691 	/*
2692 	 * If CGROUP_SCHED is disabled, @tg is NULL. If @tg is an autogroup,
2693 	 * @tg->css.cgroup is NULL. In both cases, @tg can be treated as the
2694 	 * root cgroup.
2695 	 */
2696 	if (tg && tg->css.cgroup)
2697 		return tg->css.cgroup;
2698 	else
2699 		return &cgrp_dfl_root.cgrp;
2700 }
2701 
2702 #define SCX_INIT_TASK_ARGS_CGROUP(tg)		.cgroup = tg_cgrp(tg),
2703 
2704 #else	/* CONFIG_EXT_GROUP_SCHED */
2705 
2706 #define SCX_INIT_TASK_ARGS_CGROUP(tg)
2707 
2708 #endif	/* CONFIG_EXT_GROUP_SCHED */
2709 
2710 static enum scx_task_state scx_get_task_state(const struct task_struct *p)
2711 {
2712 	return (p->scx.flags & SCX_TASK_STATE_MASK) >> SCX_TASK_STATE_SHIFT;
2713 }
2714 
2715 static void scx_set_task_state(struct task_struct *p, enum scx_task_state state)
2716 {
2717 	enum scx_task_state prev_state = scx_get_task_state(p);
2718 	bool warn = false;
2719 
2720 	BUILD_BUG_ON(SCX_TASK_NR_STATES > (1 << SCX_TASK_STATE_BITS));
2721 
2722 	switch (state) {
2723 	case SCX_TASK_NONE:
2724 		break;
2725 	case SCX_TASK_INIT:
2726 		warn = prev_state != SCX_TASK_NONE;
2727 		break;
2728 	case SCX_TASK_READY:
2729 		warn = prev_state == SCX_TASK_NONE;
2730 		break;
2731 	case SCX_TASK_ENABLED:
2732 		warn = prev_state != SCX_TASK_READY;
2733 		break;
2734 	default:
2735 		warn = true;
2736 		return;
2737 	}
2738 
2739 	WARN_ONCE(warn, "sched_ext: Invalid task state transition %d -> %d for %s[%d]",
2740 		  prev_state, state, p->comm, p->pid);
2741 
2742 	p->scx.flags &= ~SCX_TASK_STATE_MASK;
2743 	p->scx.flags |= state << SCX_TASK_STATE_SHIFT;
2744 }
2745 
2746 static int scx_init_task(struct task_struct *p, struct task_group *tg, bool fork)
2747 {
2748 	struct scx_sched *sch = scx_root;
2749 	int ret;
2750 
2751 	p->scx.disallow = false;
2752 
2753 	if (SCX_HAS_OP(sch, init_task)) {
2754 		struct scx_init_task_args args = {
2755 			SCX_INIT_TASK_ARGS_CGROUP(tg)
2756 			.fork = fork,
2757 		};
2758 
2759 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init_task, NULL,
2760 				      p, &args);
2761 		if (unlikely(ret)) {
2762 			ret = ops_sanitize_err(sch, "init_task", ret);
2763 			return ret;
2764 		}
2765 	}
2766 
2767 	scx_set_task_state(p, SCX_TASK_INIT);
2768 
2769 	if (p->scx.disallow) {
2770 		if (!fork) {
2771 			struct rq *rq;
2772 			struct rq_flags rf;
2773 
2774 			rq = task_rq_lock(p, &rf);
2775 
2776 			/*
2777 			 * We're in the load path and @p->policy will be applied
2778 			 * right after. Reverting @p->policy here and rejecting
2779 			 * %SCHED_EXT transitions from scx_check_setscheduler()
2780 			 * guarantees that if ops.init_task() sets @p->disallow,
2781 			 * @p can never be in SCX.
2782 			 */
2783 			if (p->policy == SCHED_EXT) {
2784 				p->policy = SCHED_NORMAL;
2785 				atomic_long_inc(&scx_nr_rejected);
2786 			}
2787 
2788 			task_rq_unlock(rq, p, &rf);
2789 		} else if (p->policy == SCHED_EXT) {
2790 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] during fork",
2791 				  p->comm, p->pid);
2792 		}
2793 	}
2794 
2795 	p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
2796 	return 0;
2797 }
2798 
2799 static void scx_enable_task(struct task_struct *p)
2800 {
2801 	struct scx_sched *sch = scx_root;
2802 	struct rq *rq = task_rq(p);
2803 	u32 weight;
2804 
2805 	lockdep_assert_rq_held(rq);
2806 
2807 	/*
2808 	 * Set the weight before calling ops.enable() so that the scheduler
2809 	 * doesn't see a stale value if they inspect the task struct.
2810 	 */
2811 	if (task_has_idle_policy(p))
2812 		weight = WEIGHT_IDLEPRIO;
2813 	else
2814 		weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO];
2815 
2816 	p->scx.weight = sched_weight_to_cgroup(weight);
2817 
2818 	if (SCX_HAS_OP(sch, enable))
2819 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, enable, rq, p);
2820 	scx_set_task_state(p, SCX_TASK_ENABLED);
2821 
2822 	if (SCX_HAS_OP(sch, set_weight))
2823 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq,
2824 				 p, p->scx.weight);
2825 }
2826 
2827 static void scx_disable_task(struct task_struct *p)
2828 {
2829 	struct scx_sched *sch = scx_root;
2830 	struct rq *rq = task_rq(p);
2831 
2832 	lockdep_assert_rq_held(rq);
2833 	WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED);
2834 
2835 	if (SCX_HAS_OP(sch, disable))
2836 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, disable, rq, p);
2837 	scx_set_task_state(p, SCX_TASK_READY);
2838 }
2839 
2840 static void scx_exit_task(struct task_struct *p)
2841 {
2842 	struct scx_sched *sch = scx_root;
2843 	struct scx_exit_task_args args = {
2844 		.cancelled = false,
2845 	};
2846 
2847 	lockdep_assert_rq_held(task_rq(p));
2848 
2849 	switch (scx_get_task_state(p)) {
2850 	case SCX_TASK_NONE:
2851 		return;
2852 	case SCX_TASK_INIT:
2853 		args.cancelled = true;
2854 		break;
2855 	case SCX_TASK_READY:
2856 		break;
2857 	case SCX_TASK_ENABLED:
2858 		scx_disable_task(p);
2859 		break;
2860 	default:
2861 		WARN_ON_ONCE(true);
2862 		return;
2863 	}
2864 
2865 	if (SCX_HAS_OP(sch, exit_task))
2866 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, exit_task, task_rq(p),
2867 				 p, &args);
2868 	scx_set_task_state(p, SCX_TASK_NONE);
2869 }
2870 
2871 void init_scx_entity(struct sched_ext_entity *scx)
2872 {
2873 	memset(scx, 0, sizeof(*scx));
2874 	INIT_LIST_HEAD(&scx->dsq_list.node);
2875 	RB_CLEAR_NODE(&scx->dsq_priq);
2876 	scx->sticky_cpu = -1;
2877 	scx->holding_cpu = -1;
2878 	INIT_LIST_HEAD(&scx->runnable_node);
2879 	scx->runnable_at = jiffies;
2880 	scx->ddsp_dsq_id = SCX_DSQ_INVALID;
2881 	scx->slice = SCX_SLICE_DFL;
2882 }
2883 
2884 void scx_pre_fork(struct task_struct *p)
2885 {
2886 	/*
2887 	 * BPF scheduler enable/disable paths want to be able to iterate and
2888 	 * update all tasks which can become complex when racing forks. As
2889 	 * enable/disable are very cold paths, let's use a percpu_rwsem to
2890 	 * exclude forks.
2891 	 */
2892 	percpu_down_read(&scx_fork_rwsem);
2893 }
2894 
2895 int scx_fork(struct task_struct *p)
2896 {
2897 	percpu_rwsem_assert_held(&scx_fork_rwsem);
2898 
2899 	if (scx_init_task_enabled)
2900 		return scx_init_task(p, task_group(p), true);
2901 	else
2902 		return 0;
2903 }
2904 
2905 void scx_post_fork(struct task_struct *p)
2906 {
2907 	if (scx_init_task_enabled) {
2908 		scx_set_task_state(p, SCX_TASK_READY);
2909 
2910 		/*
2911 		 * Enable the task immediately if it's running on sched_ext.
2912 		 * Otherwise, it'll be enabled in switching_to_scx() if and
2913 		 * when it's ever configured to run with a SCHED_EXT policy.
2914 		 */
2915 		if (p->sched_class == &ext_sched_class) {
2916 			struct rq_flags rf;
2917 			struct rq *rq;
2918 
2919 			rq = task_rq_lock(p, &rf);
2920 			scx_enable_task(p);
2921 			task_rq_unlock(rq, p, &rf);
2922 		}
2923 	}
2924 
2925 	spin_lock_irq(&scx_tasks_lock);
2926 	list_add_tail(&p->scx.tasks_node, &scx_tasks);
2927 	spin_unlock_irq(&scx_tasks_lock);
2928 
2929 	percpu_up_read(&scx_fork_rwsem);
2930 }
2931 
2932 void scx_cancel_fork(struct task_struct *p)
2933 {
2934 	if (scx_enabled()) {
2935 		struct rq *rq;
2936 		struct rq_flags rf;
2937 
2938 		rq = task_rq_lock(p, &rf);
2939 		WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY);
2940 		scx_exit_task(p);
2941 		task_rq_unlock(rq, p, &rf);
2942 	}
2943 
2944 	percpu_up_read(&scx_fork_rwsem);
2945 }
2946 
2947 void sched_ext_free(struct task_struct *p)
2948 {
2949 	unsigned long flags;
2950 
2951 	spin_lock_irqsave(&scx_tasks_lock, flags);
2952 	list_del_init(&p->scx.tasks_node);
2953 	spin_unlock_irqrestore(&scx_tasks_lock, flags);
2954 
2955 	/*
2956 	 * @p is off scx_tasks and wholly ours. scx_enable()'s READY -> ENABLED
2957 	 * transitions can't race us. Disable ops for @p.
2958 	 */
2959 	if (scx_get_task_state(p) != SCX_TASK_NONE) {
2960 		struct rq_flags rf;
2961 		struct rq *rq;
2962 
2963 		rq = task_rq_lock(p, &rf);
2964 		scx_exit_task(p);
2965 		task_rq_unlock(rq, p, &rf);
2966 	}
2967 }
2968 
2969 static void reweight_task_scx(struct rq *rq, struct task_struct *p,
2970 			      const struct load_weight *lw)
2971 {
2972 	struct scx_sched *sch = scx_root;
2973 
2974 	lockdep_assert_rq_held(task_rq(p));
2975 
2976 	p->scx.weight = sched_weight_to_cgroup(scale_load_down(lw->weight));
2977 	if (SCX_HAS_OP(sch, set_weight))
2978 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq,
2979 				 p, p->scx.weight);
2980 }
2981 
2982 static void prio_changed_scx(struct rq *rq, struct task_struct *p, u64 oldprio)
2983 {
2984 }
2985 
2986 static void switching_to_scx(struct rq *rq, struct task_struct *p)
2987 {
2988 	struct scx_sched *sch = scx_root;
2989 
2990 	scx_enable_task(p);
2991 
2992 	/*
2993 	 * set_cpus_allowed_scx() is not called while @p is associated with a
2994 	 * different scheduler class. Keep the BPF scheduler up-to-date.
2995 	 */
2996 	if (SCX_HAS_OP(sch, set_cpumask))
2997 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, rq,
2998 				 p, (struct cpumask *)p->cpus_ptr);
2999 }
3000 
3001 static void switched_from_scx(struct rq *rq, struct task_struct *p)
3002 {
3003 	scx_disable_task(p);
3004 }
3005 
3006 static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p,int wake_flags) {}
3007 static void switched_to_scx(struct rq *rq, struct task_struct *p) {}
3008 
3009 int scx_check_setscheduler(struct task_struct *p, int policy)
3010 {
3011 	lockdep_assert_rq_held(task_rq(p));
3012 
3013 	/* if disallow, reject transitioning into SCX */
3014 	if (scx_enabled() && READ_ONCE(p->scx.disallow) &&
3015 	    p->policy != policy && policy == SCHED_EXT)
3016 		return -EACCES;
3017 
3018 	return 0;
3019 }
3020 
3021 #ifdef CONFIG_NO_HZ_FULL
3022 bool scx_can_stop_tick(struct rq *rq)
3023 {
3024 	struct task_struct *p = rq->curr;
3025 
3026 	if (scx_rq_bypassing(rq))
3027 		return false;
3028 
3029 	if (p->sched_class != &ext_sched_class)
3030 		return true;
3031 
3032 	/*
3033 	 * @rq can dispatch from different DSQs, so we can't tell whether it
3034 	 * needs the tick or not by looking at nr_running. Allow stopping ticks
3035 	 * iff the BPF scheduler indicated so. See set_next_task_scx().
3036 	 */
3037 	return rq->scx.flags & SCX_RQ_CAN_STOP_TICK;
3038 }
3039 #endif
3040 
3041 #ifdef CONFIG_EXT_GROUP_SCHED
3042 
3043 DEFINE_STATIC_PERCPU_RWSEM(scx_cgroup_ops_rwsem);
3044 static bool scx_cgroup_enabled;
3045 
3046 void scx_tg_init(struct task_group *tg)
3047 {
3048 	tg->scx.weight = CGROUP_WEIGHT_DFL;
3049 	tg->scx.bw_period_us = default_bw_period_us();
3050 	tg->scx.bw_quota_us = RUNTIME_INF;
3051 	tg->scx.idle = false;
3052 }
3053 
3054 int scx_tg_online(struct task_group *tg)
3055 {
3056 	struct scx_sched *sch = scx_root;
3057 	int ret = 0;
3058 
3059 	WARN_ON_ONCE(tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED));
3060 
3061 	if (scx_cgroup_enabled) {
3062 		if (SCX_HAS_OP(sch, cgroup_init)) {
3063 			struct scx_cgroup_init_args args =
3064 				{ .weight = tg->scx.weight,
3065 				  .bw_period_us = tg->scx.bw_period_us,
3066 				  .bw_quota_us = tg->scx.bw_quota_us,
3067 				  .bw_burst_us = tg->scx.bw_burst_us };
3068 
3069 			ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init,
3070 					      NULL, tg->css.cgroup, &args);
3071 			if (ret)
3072 				ret = ops_sanitize_err(sch, "cgroup_init", ret);
3073 		}
3074 		if (ret == 0)
3075 			tg->scx.flags |= SCX_TG_ONLINE | SCX_TG_INITED;
3076 	} else {
3077 		tg->scx.flags |= SCX_TG_ONLINE;
3078 	}
3079 
3080 	return ret;
3081 }
3082 
3083 void scx_tg_offline(struct task_group *tg)
3084 {
3085 	struct scx_sched *sch = scx_root;
3086 
3087 	WARN_ON_ONCE(!(tg->scx.flags & SCX_TG_ONLINE));
3088 
3089 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_exit) &&
3090 	    (tg->scx.flags & SCX_TG_INITED))
3091 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL,
3092 			    tg->css.cgroup);
3093 	tg->scx.flags &= ~(SCX_TG_ONLINE | SCX_TG_INITED);
3094 }
3095 
3096 int scx_cgroup_can_attach(struct cgroup_taskset *tset)
3097 {
3098 	struct scx_sched *sch = scx_root;
3099 	struct cgroup_subsys_state *css;
3100 	struct task_struct *p;
3101 	int ret;
3102 
3103 	if (!scx_cgroup_enabled)
3104 		return 0;
3105 
3106 	cgroup_taskset_for_each(p, css, tset) {
3107 		struct cgroup *from = tg_cgrp(task_group(p));
3108 		struct cgroup *to = tg_cgrp(css_tg(css));
3109 
3110 		WARN_ON_ONCE(p->scx.cgrp_moving_from);
3111 
3112 		/*
3113 		 * sched_move_task() omits identity migrations. Let's match the
3114 		 * behavior so that ops.cgroup_prep_move() and ops.cgroup_move()
3115 		 * always match one-to-one.
3116 		 */
3117 		if (from == to)
3118 			continue;
3119 
3120 		if (SCX_HAS_OP(sch, cgroup_prep_move)) {
3121 			ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED,
3122 					      cgroup_prep_move, NULL,
3123 					      p, from, css->cgroup);
3124 			if (ret)
3125 				goto err;
3126 		}
3127 
3128 		p->scx.cgrp_moving_from = from;
3129 	}
3130 
3131 	return 0;
3132 
3133 err:
3134 	cgroup_taskset_for_each(p, css, tset) {
3135 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
3136 		    p->scx.cgrp_moving_from)
3137 			SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL,
3138 				    p, p->scx.cgrp_moving_from, css->cgroup);
3139 		p->scx.cgrp_moving_from = NULL;
3140 	}
3141 
3142 	return ops_sanitize_err(sch, "cgroup_prep_move", ret);
3143 }
3144 
3145 void scx_cgroup_move_task(struct task_struct *p)
3146 {
3147 	struct scx_sched *sch = scx_root;
3148 
3149 	if (!scx_cgroup_enabled)
3150 		return;
3151 
3152 	/*
3153 	 * @p must have ops.cgroup_prep_move() called on it and thus
3154 	 * cgrp_moving_from set.
3155 	 */
3156 	if (SCX_HAS_OP(sch, cgroup_move) &&
3157 	    !WARN_ON_ONCE(!p->scx.cgrp_moving_from))
3158 		SCX_CALL_OP_TASK(sch, SCX_KF_UNLOCKED, cgroup_move, NULL,
3159 				 p, p->scx.cgrp_moving_from,
3160 				 tg_cgrp(task_group(p)));
3161 	p->scx.cgrp_moving_from = NULL;
3162 }
3163 
3164 void scx_cgroup_cancel_attach(struct cgroup_taskset *tset)
3165 {
3166 	struct scx_sched *sch = scx_root;
3167 	struct cgroup_subsys_state *css;
3168 	struct task_struct *p;
3169 
3170 	if (!scx_cgroup_enabled)
3171 		return;
3172 
3173 	cgroup_taskset_for_each(p, css, tset) {
3174 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
3175 		    p->scx.cgrp_moving_from)
3176 			SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL,
3177 				    p, p->scx.cgrp_moving_from, css->cgroup);
3178 		p->scx.cgrp_moving_from = NULL;
3179 	}
3180 }
3181 
3182 void scx_group_set_weight(struct task_group *tg, unsigned long weight)
3183 {
3184 	struct scx_sched *sch = scx_root;
3185 
3186 	percpu_down_read(&scx_cgroup_ops_rwsem);
3187 
3188 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_weight) &&
3189 	    tg->scx.weight != weight)
3190 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_weight, NULL,
3191 			    tg_cgrp(tg), weight);
3192 
3193 	tg->scx.weight = weight;
3194 
3195 	percpu_up_read(&scx_cgroup_ops_rwsem);
3196 }
3197 
3198 void scx_group_set_idle(struct task_group *tg, bool idle)
3199 {
3200 	struct scx_sched *sch = scx_root;
3201 
3202 	percpu_down_read(&scx_cgroup_ops_rwsem);
3203 
3204 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_idle))
3205 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_idle, NULL,
3206 			    tg_cgrp(tg), idle);
3207 
3208 	/* Update the task group's idle state */
3209 	tg->scx.idle = idle;
3210 
3211 	percpu_up_read(&scx_cgroup_ops_rwsem);
3212 }
3213 
3214 void scx_group_set_bandwidth(struct task_group *tg,
3215 			     u64 period_us, u64 quota_us, u64 burst_us)
3216 {
3217 	struct scx_sched *sch = scx_root;
3218 
3219 	percpu_down_read(&scx_cgroup_ops_rwsem);
3220 
3221 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_bandwidth) &&
3222 	    (tg->scx.bw_period_us != period_us ||
3223 	     tg->scx.bw_quota_us != quota_us ||
3224 	     tg->scx.bw_burst_us != burst_us))
3225 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_bandwidth, NULL,
3226 			    tg_cgrp(tg), period_us, quota_us, burst_us);
3227 
3228 	tg->scx.bw_period_us = period_us;
3229 	tg->scx.bw_quota_us = quota_us;
3230 	tg->scx.bw_burst_us = burst_us;
3231 
3232 	percpu_up_read(&scx_cgroup_ops_rwsem);
3233 }
3234 
3235 static void scx_cgroup_lock(void)
3236 {
3237 	percpu_down_write(&scx_cgroup_ops_rwsem);
3238 	cgroup_lock();
3239 }
3240 
3241 static void scx_cgroup_unlock(void)
3242 {
3243 	cgroup_unlock();
3244 	percpu_up_write(&scx_cgroup_ops_rwsem);
3245 }
3246 
3247 #else	/* CONFIG_EXT_GROUP_SCHED */
3248 
3249 static void scx_cgroup_lock(void) {}
3250 static void scx_cgroup_unlock(void) {}
3251 
3252 #endif	/* CONFIG_EXT_GROUP_SCHED */
3253 
3254 /*
3255  * Omitted operations:
3256  *
3257  * - wakeup_preempt: NOOP as it isn't useful in the wakeup path because the task
3258  *   isn't tied to the CPU at that point. Preemption is implemented by resetting
3259  *   the victim task's slice to 0 and triggering reschedule on the target CPU.
3260  *
3261  * - migrate_task_rq: Unnecessary as task to cpu mapping is transient.
3262  *
3263  * - task_fork/dead: We need fork/dead notifications for all tasks regardless of
3264  *   their current sched_class. Call them directly from sched core instead.
3265  */
3266 DEFINE_SCHED_CLASS(ext) = {
3267 	.queue_mask		= 1,
3268 
3269 	.enqueue_task		= enqueue_task_scx,
3270 	.dequeue_task		= dequeue_task_scx,
3271 	.yield_task		= yield_task_scx,
3272 	.yield_to_task		= yield_to_task_scx,
3273 
3274 	.wakeup_preempt		= wakeup_preempt_scx,
3275 
3276 	.pick_task		= pick_task_scx,
3277 
3278 	.put_prev_task		= put_prev_task_scx,
3279 	.set_next_task		= set_next_task_scx,
3280 
3281 	.select_task_rq		= select_task_rq_scx,
3282 	.task_woken		= task_woken_scx,
3283 	.set_cpus_allowed	= set_cpus_allowed_scx,
3284 
3285 	.rq_online		= rq_online_scx,
3286 	.rq_offline		= rq_offline_scx,
3287 
3288 	.task_tick		= task_tick_scx,
3289 
3290 	.switching_to		= switching_to_scx,
3291 	.switched_from		= switched_from_scx,
3292 	.switched_to		= switched_to_scx,
3293 	.reweight_task		= reweight_task_scx,
3294 	.prio_changed		= prio_changed_scx,
3295 
3296 	.update_curr		= update_curr_scx,
3297 
3298 #ifdef CONFIG_UCLAMP_TASK
3299 	.uclamp_enabled		= 1,
3300 #endif
3301 };
3302 
3303 static void init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id)
3304 {
3305 	memset(dsq, 0, sizeof(*dsq));
3306 
3307 	raw_spin_lock_init(&dsq->lock);
3308 	INIT_LIST_HEAD(&dsq->list);
3309 	dsq->id = dsq_id;
3310 }
3311 
3312 static void free_dsq_irq_workfn(struct irq_work *irq_work)
3313 {
3314 	struct llist_node *to_free = llist_del_all(&dsqs_to_free);
3315 	struct scx_dispatch_q *dsq, *tmp_dsq;
3316 
3317 	llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node)
3318 		kfree_rcu(dsq, rcu);
3319 }
3320 
3321 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn);
3322 
3323 static void destroy_dsq(struct scx_sched *sch, u64 dsq_id)
3324 {
3325 	struct scx_dispatch_q *dsq;
3326 	unsigned long flags;
3327 
3328 	rcu_read_lock();
3329 
3330 	dsq = find_user_dsq(sch, dsq_id);
3331 	if (!dsq)
3332 		goto out_unlock_rcu;
3333 
3334 	raw_spin_lock_irqsave(&dsq->lock, flags);
3335 
3336 	if (dsq->nr) {
3337 		scx_error(sch, "attempting to destroy in-use dsq 0x%016llx (nr=%u)",
3338 			  dsq->id, dsq->nr);
3339 		goto out_unlock_dsq;
3340 	}
3341 
3342 	if (rhashtable_remove_fast(&sch->dsq_hash, &dsq->hash_node,
3343 				   dsq_hash_params))
3344 		goto out_unlock_dsq;
3345 
3346 	/*
3347 	 * Mark dead by invalidating ->id to prevent dispatch_enqueue() from
3348 	 * queueing more tasks. As this function can be called from anywhere,
3349 	 * freeing is bounced through an irq work to avoid nesting RCU
3350 	 * operations inside scheduler locks.
3351 	 */
3352 	dsq->id = SCX_DSQ_INVALID;
3353 	llist_add(&dsq->free_node, &dsqs_to_free);
3354 	irq_work_queue(&free_dsq_irq_work);
3355 
3356 out_unlock_dsq:
3357 	raw_spin_unlock_irqrestore(&dsq->lock, flags);
3358 out_unlock_rcu:
3359 	rcu_read_unlock();
3360 }
3361 
3362 #ifdef CONFIG_EXT_GROUP_SCHED
3363 static void scx_cgroup_exit(struct scx_sched *sch)
3364 {
3365 	struct cgroup_subsys_state *css;
3366 
3367 	scx_cgroup_enabled = false;
3368 
3369 	/*
3370 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
3371 	 * cgroups and exit all the inited ones, all online cgroups are exited.
3372 	 */
3373 	css_for_each_descendant_post(css, &root_task_group.css) {
3374 		struct task_group *tg = css_tg(css);
3375 
3376 		if (!(tg->scx.flags & SCX_TG_INITED))
3377 			continue;
3378 		tg->scx.flags &= ~SCX_TG_INITED;
3379 
3380 		if (!sch->ops.cgroup_exit)
3381 			continue;
3382 
3383 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL,
3384 			    css->cgroup);
3385 	}
3386 }
3387 
3388 static int scx_cgroup_init(struct scx_sched *sch)
3389 {
3390 	struct cgroup_subsys_state *css;
3391 	int ret;
3392 
3393 	/*
3394 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
3395 	 * cgroups and init, all online cgroups are initialized.
3396 	 */
3397 	css_for_each_descendant_pre(css, &root_task_group.css) {
3398 		struct task_group *tg = css_tg(css);
3399 		struct scx_cgroup_init_args args = {
3400 			.weight = tg->scx.weight,
3401 			.bw_period_us = tg->scx.bw_period_us,
3402 			.bw_quota_us = tg->scx.bw_quota_us,
3403 			.bw_burst_us = tg->scx.bw_burst_us,
3404 		};
3405 
3406 		if ((tg->scx.flags &
3407 		     (SCX_TG_ONLINE | SCX_TG_INITED)) != SCX_TG_ONLINE)
3408 			continue;
3409 
3410 		if (!sch->ops.cgroup_init) {
3411 			tg->scx.flags |= SCX_TG_INITED;
3412 			continue;
3413 		}
3414 
3415 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init, NULL,
3416 				      css->cgroup, &args);
3417 		if (ret) {
3418 			css_put(css);
3419 			scx_error(sch, "ops.cgroup_init() failed (%d)", ret);
3420 			return ret;
3421 		}
3422 		tg->scx.flags |= SCX_TG_INITED;
3423 	}
3424 
3425 	WARN_ON_ONCE(scx_cgroup_enabled);
3426 	scx_cgroup_enabled = true;
3427 
3428 	return 0;
3429 }
3430 
3431 #else
3432 static void scx_cgroup_exit(struct scx_sched *sch) {}
3433 static int scx_cgroup_init(struct scx_sched *sch) { return 0; }
3434 #endif
3435 
3436 
3437 /********************************************************************************
3438  * Sysfs interface and ops enable/disable.
3439  */
3440 
3441 #define SCX_ATTR(_name)								\
3442 	static struct kobj_attribute scx_attr_##_name = {			\
3443 		.attr = { .name = __stringify(_name), .mode = 0444 },		\
3444 		.show = scx_attr_##_name##_show,				\
3445 	}
3446 
3447 static ssize_t scx_attr_state_show(struct kobject *kobj,
3448 				   struct kobj_attribute *ka, char *buf)
3449 {
3450 	return sysfs_emit(buf, "%s\n", scx_enable_state_str[scx_enable_state()]);
3451 }
3452 SCX_ATTR(state);
3453 
3454 static ssize_t scx_attr_switch_all_show(struct kobject *kobj,
3455 					struct kobj_attribute *ka, char *buf)
3456 {
3457 	return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all));
3458 }
3459 SCX_ATTR(switch_all);
3460 
3461 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj,
3462 					 struct kobj_attribute *ka, char *buf)
3463 {
3464 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected));
3465 }
3466 SCX_ATTR(nr_rejected);
3467 
3468 static ssize_t scx_attr_hotplug_seq_show(struct kobject *kobj,
3469 					 struct kobj_attribute *ka, char *buf)
3470 {
3471 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_hotplug_seq));
3472 }
3473 SCX_ATTR(hotplug_seq);
3474 
3475 static ssize_t scx_attr_enable_seq_show(struct kobject *kobj,
3476 					struct kobj_attribute *ka, char *buf)
3477 {
3478 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_enable_seq));
3479 }
3480 SCX_ATTR(enable_seq);
3481 
3482 static struct attribute *scx_global_attrs[] = {
3483 	&scx_attr_state.attr,
3484 	&scx_attr_switch_all.attr,
3485 	&scx_attr_nr_rejected.attr,
3486 	&scx_attr_hotplug_seq.attr,
3487 	&scx_attr_enable_seq.attr,
3488 	NULL,
3489 };
3490 
3491 static const struct attribute_group scx_global_attr_group = {
3492 	.attrs = scx_global_attrs,
3493 };
3494 
3495 static void free_exit_info(struct scx_exit_info *ei);
3496 
3497 static void scx_sched_free_rcu_work(struct work_struct *work)
3498 {
3499 	struct rcu_work *rcu_work = to_rcu_work(work);
3500 	struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work);
3501 	struct rhashtable_iter rht_iter;
3502 	struct scx_dispatch_q *dsq;
3503 	int node;
3504 
3505 	irq_work_sync(&sch->error_irq_work);
3506 	kthread_stop(sch->helper->task);
3507 
3508 	free_percpu(sch->pcpu);
3509 
3510 	for_each_node_state(node, N_POSSIBLE)
3511 		kfree(sch->global_dsqs[node]);
3512 	kfree(sch->global_dsqs);
3513 
3514 	rhashtable_walk_enter(&sch->dsq_hash, &rht_iter);
3515 	do {
3516 		rhashtable_walk_start(&rht_iter);
3517 
3518 		while ((dsq = rhashtable_walk_next(&rht_iter)) && !IS_ERR(dsq))
3519 			destroy_dsq(sch, dsq->id);
3520 
3521 		rhashtable_walk_stop(&rht_iter);
3522 	} while (dsq == ERR_PTR(-EAGAIN));
3523 	rhashtable_walk_exit(&rht_iter);
3524 
3525 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
3526 	free_exit_info(sch->exit_info);
3527 	kfree(sch);
3528 }
3529 
3530 static void scx_kobj_release(struct kobject *kobj)
3531 {
3532 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
3533 
3534 	INIT_RCU_WORK(&sch->rcu_work, scx_sched_free_rcu_work);
3535 	queue_rcu_work(system_unbound_wq, &sch->rcu_work);
3536 }
3537 
3538 static ssize_t scx_attr_ops_show(struct kobject *kobj,
3539 				 struct kobj_attribute *ka, char *buf)
3540 {
3541 	return sysfs_emit(buf, "%s\n", scx_root->ops.name);
3542 }
3543 SCX_ATTR(ops);
3544 
3545 #define scx_attr_event_show(buf, at, events, kind) ({				\
3546 	sysfs_emit_at(buf, at, "%s %llu\n", #kind, (events)->kind);		\
3547 })
3548 
3549 static ssize_t scx_attr_events_show(struct kobject *kobj,
3550 				    struct kobj_attribute *ka, char *buf)
3551 {
3552 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
3553 	struct scx_event_stats events;
3554 	int at = 0;
3555 
3556 	scx_read_events(sch, &events);
3557 	at += scx_attr_event_show(buf, at, &events, SCX_EV_SELECT_CPU_FALLBACK);
3558 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
3559 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_KEEP_LAST);
3560 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_EXITING);
3561 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
3562 	at += scx_attr_event_show(buf, at, &events, SCX_EV_REFILL_SLICE_DFL);
3563 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DURATION);
3564 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DISPATCH);
3565 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_ACTIVATE);
3566 	return at;
3567 }
3568 SCX_ATTR(events);
3569 
3570 static struct attribute *scx_sched_attrs[] = {
3571 	&scx_attr_ops.attr,
3572 	&scx_attr_events.attr,
3573 	NULL,
3574 };
3575 ATTRIBUTE_GROUPS(scx_sched);
3576 
3577 static const struct kobj_type scx_ktype = {
3578 	.release = scx_kobj_release,
3579 	.sysfs_ops = &kobj_sysfs_ops,
3580 	.default_groups = scx_sched_groups,
3581 };
3582 
3583 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
3584 {
3585 	return add_uevent_var(env, "SCXOPS=%s", scx_root->ops.name);
3586 }
3587 
3588 static const struct kset_uevent_ops scx_uevent_ops = {
3589 	.uevent = scx_uevent,
3590 };
3591 
3592 /*
3593  * Used by sched_fork() and __setscheduler_prio() to pick the matching
3594  * sched_class. dl/rt are already handled.
3595  */
3596 bool task_should_scx(int policy)
3597 {
3598 	if (!scx_enabled() || unlikely(scx_enable_state() == SCX_DISABLING))
3599 		return false;
3600 	if (READ_ONCE(scx_switching_all))
3601 		return true;
3602 	return policy == SCHED_EXT;
3603 }
3604 
3605 bool scx_allow_ttwu_queue(const struct task_struct *p)
3606 {
3607 	struct scx_sched *sch;
3608 
3609 	if (!scx_enabled())
3610 		return true;
3611 
3612 	sch = rcu_dereference_sched(scx_root);
3613 	if (unlikely(!sch))
3614 		return true;
3615 
3616 	if (sch->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP)
3617 		return true;
3618 
3619 	if (unlikely(p->sched_class != &ext_sched_class))
3620 		return true;
3621 
3622 	return false;
3623 }
3624 
3625 /**
3626  * scx_rcu_cpu_stall - sched_ext RCU CPU stall handler
3627  *
3628  * While there are various reasons why RCU CPU stalls can occur on a system
3629  * that may not be caused by the current BPF scheduler, try kicking out the
3630  * current scheduler in an attempt to recover the system to a good state before
3631  * issuing panics.
3632  */
3633 bool scx_rcu_cpu_stall(void)
3634 {
3635 	struct scx_sched *sch;
3636 
3637 	rcu_read_lock();
3638 
3639 	sch = rcu_dereference(scx_root);
3640 	if (unlikely(!sch)) {
3641 		rcu_read_unlock();
3642 		return false;
3643 	}
3644 
3645 	switch (scx_enable_state()) {
3646 	case SCX_ENABLING:
3647 	case SCX_ENABLED:
3648 		break;
3649 	default:
3650 		rcu_read_unlock();
3651 		return false;
3652 	}
3653 
3654 	scx_error(sch, "RCU CPU stall detected!");
3655 	rcu_read_unlock();
3656 
3657 	return true;
3658 }
3659 
3660 /**
3661  * scx_softlockup - sched_ext softlockup handler
3662  * @dur_s: number of seconds of CPU stuck due to soft lockup
3663  *
3664  * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can
3665  * live-lock the system by making many CPUs target the same DSQ to the point
3666  * where soft-lockup detection triggers. This function is called from
3667  * soft-lockup watchdog when the triggering point is close and tries to unjam
3668  * the system by enabling the breather and aborting the BPF scheduler.
3669  */
3670 void scx_softlockup(u32 dur_s)
3671 {
3672 	struct scx_sched *sch;
3673 
3674 	rcu_read_lock();
3675 
3676 	sch = rcu_dereference(scx_root);
3677 	if (unlikely(!sch))
3678 		goto out_unlock;
3679 
3680 	switch (scx_enable_state()) {
3681 	case SCX_ENABLING:
3682 	case SCX_ENABLED:
3683 		break;
3684 	default:
3685 		goto out_unlock;
3686 	}
3687 
3688 	/* allow only one instance, cleared at the end of scx_bypass() */
3689 	if (test_and_set_bit(0, &scx_in_softlockup))
3690 		goto out_unlock;
3691 
3692 	printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU%d stuck for %us, disabling \"%s\"\n",
3693 			smp_processor_id(), dur_s, scx_root->ops.name);
3694 
3695 	/*
3696 	 * Some CPUs may be trapped in the dispatch paths. Enable breather
3697 	 * immediately; otherwise, we might even be able to get to scx_bypass().
3698 	 */
3699 	atomic_inc(&scx_breather_depth);
3700 
3701 	scx_error(sch, "soft lockup - CPU#%d stuck for %us", smp_processor_id(), dur_s);
3702 out_unlock:
3703 	rcu_read_unlock();
3704 }
3705 
3706 static void scx_clear_softlockup(void)
3707 {
3708 	if (test_and_clear_bit(0, &scx_in_softlockup))
3709 		atomic_dec(&scx_breather_depth);
3710 }
3711 
3712 /**
3713  * scx_bypass - [Un]bypass scx_ops and guarantee forward progress
3714  * @bypass: true for bypass, false for unbypass
3715  *
3716  * Bypassing guarantees that all runnable tasks make forward progress without
3717  * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might
3718  * be held by tasks that the BPF scheduler is forgetting to run, which
3719  * unfortunately also excludes toggling the static branches.
3720  *
3721  * Let's work around by overriding a couple ops and modifying behaviors based on
3722  * the DISABLING state and then cycling the queued tasks through dequeue/enqueue
3723  * to force global FIFO scheduling.
3724  *
3725  * - ops.select_cpu() is ignored and the default select_cpu() is used.
3726  *
3727  * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order.
3728  *   %SCX_OPS_ENQ_LAST is also ignored.
3729  *
3730  * - ops.dispatch() is ignored.
3731  *
3732  * - balance_scx() does not set %SCX_RQ_BAL_KEEP on non-zero slice as slice
3733  *   can't be trusted. Whenever a tick triggers, the running task is rotated to
3734  *   the tail of the queue with core_sched_at touched.
3735  *
3736  * - pick_next_task() suppresses zero slice warning.
3737  *
3738  * - scx_kick_cpu() is disabled to avoid irq_work malfunction during PM
3739  *   operations.
3740  *
3741  * - scx_prio_less() reverts to the default core_sched_at order.
3742  */
3743 static void scx_bypass(bool bypass)
3744 {
3745 	static DEFINE_RAW_SPINLOCK(bypass_lock);
3746 	static unsigned long bypass_timestamp;
3747 	struct scx_sched *sch;
3748 	unsigned long flags;
3749 	int cpu;
3750 
3751 	raw_spin_lock_irqsave(&bypass_lock, flags);
3752 	sch = rcu_dereference_bh(scx_root);
3753 
3754 	if (bypass) {
3755 		scx_bypass_depth++;
3756 		WARN_ON_ONCE(scx_bypass_depth <= 0);
3757 		if (scx_bypass_depth != 1)
3758 			goto unlock;
3759 		bypass_timestamp = ktime_get_ns();
3760 		if (sch)
3761 			scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1);
3762 	} else {
3763 		scx_bypass_depth--;
3764 		WARN_ON_ONCE(scx_bypass_depth < 0);
3765 		if (scx_bypass_depth != 0)
3766 			goto unlock;
3767 		if (sch)
3768 			scx_add_event(sch, SCX_EV_BYPASS_DURATION,
3769 				      ktime_get_ns() - bypass_timestamp);
3770 	}
3771 
3772 	atomic_inc(&scx_breather_depth);
3773 
3774 	/*
3775 	 * No task property is changing. We just need to make sure all currently
3776 	 * queued tasks are re-queued according to the new scx_rq_bypassing()
3777 	 * state. As an optimization, walk each rq's runnable_list instead of
3778 	 * the scx_tasks list.
3779 	 *
3780 	 * This function can't trust the scheduler and thus can't use
3781 	 * cpus_read_lock(). Walk all possible CPUs instead of online.
3782 	 */
3783 	for_each_possible_cpu(cpu) {
3784 		struct rq *rq = cpu_rq(cpu);
3785 		struct task_struct *p, *n;
3786 
3787 		raw_spin_rq_lock(rq);
3788 
3789 		if (bypass) {
3790 			WARN_ON_ONCE(rq->scx.flags & SCX_RQ_BYPASSING);
3791 			rq->scx.flags |= SCX_RQ_BYPASSING;
3792 		} else {
3793 			WARN_ON_ONCE(!(rq->scx.flags & SCX_RQ_BYPASSING));
3794 			rq->scx.flags &= ~SCX_RQ_BYPASSING;
3795 		}
3796 
3797 		/*
3798 		 * We need to guarantee that no tasks are on the BPF scheduler
3799 		 * while bypassing. Either we see enabled or the enable path
3800 		 * sees scx_rq_bypassing() before moving tasks to SCX.
3801 		 */
3802 		if (!scx_enabled()) {
3803 			raw_spin_rq_unlock(rq);
3804 			continue;
3805 		}
3806 
3807 		/*
3808 		 * The use of list_for_each_entry_safe_reverse() is required
3809 		 * because each task is going to be removed from and added back
3810 		 * to the runnable_list during iteration. Because they're added
3811 		 * to the tail of the list, safe reverse iteration can still
3812 		 * visit all nodes.
3813 		 */
3814 		list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list,
3815 						 scx.runnable_node) {
3816 			/* cycling deq/enq is enough, see the function comment */
3817 			scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
3818 				/* nothing */ ;
3819 			}
3820 		}
3821 
3822 		/* resched to restore ticks and idle state */
3823 		if (cpu_online(cpu) || cpu == smp_processor_id())
3824 			resched_curr(rq);
3825 
3826 		raw_spin_rq_unlock(rq);
3827 	}
3828 
3829 	atomic_dec(&scx_breather_depth);
3830 unlock:
3831 	raw_spin_unlock_irqrestore(&bypass_lock, flags);
3832 	scx_clear_softlockup();
3833 }
3834 
3835 static void free_exit_info(struct scx_exit_info *ei)
3836 {
3837 	kvfree(ei->dump);
3838 	kfree(ei->msg);
3839 	kfree(ei->bt);
3840 	kfree(ei);
3841 }
3842 
3843 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
3844 {
3845 	struct scx_exit_info *ei;
3846 
3847 	ei = kzalloc(sizeof(*ei), GFP_KERNEL);
3848 	if (!ei)
3849 		return NULL;
3850 
3851 	ei->bt = kcalloc(SCX_EXIT_BT_LEN, sizeof(ei->bt[0]), GFP_KERNEL);
3852 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
3853 	ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL);
3854 
3855 	if (!ei->bt || !ei->msg || !ei->dump) {
3856 		free_exit_info(ei);
3857 		return NULL;
3858 	}
3859 
3860 	return ei;
3861 }
3862 
3863 static const char *scx_exit_reason(enum scx_exit_kind kind)
3864 {
3865 	switch (kind) {
3866 	case SCX_EXIT_UNREG:
3867 		return "unregistered from user space";
3868 	case SCX_EXIT_UNREG_BPF:
3869 		return "unregistered from BPF";
3870 	case SCX_EXIT_UNREG_KERN:
3871 		return "unregistered from the main kernel";
3872 	case SCX_EXIT_SYSRQ:
3873 		return "disabled by sysrq-S";
3874 	case SCX_EXIT_ERROR:
3875 		return "runtime error";
3876 	case SCX_EXIT_ERROR_BPF:
3877 		return "scx_bpf_error";
3878 	case SCX_EXIT_ERROR_STALL:
3879 		return "runnable task stall";
3880 	default:
3881 		return "<UNKNOWN>";
3882 	}
3883 }
3884 
3885 static void free_kick_pseqs_rcu(struct rcu_head *rcu)
3886 {
3887 	struct scx_kick_pseqs *pseqs = container_of(rcu, struct scx_kick_pseqs, rcu);
3888 
3889 	kvfree(pseqs);
3890 }
3891 
3892 static void free_kick_pseqs(void)
3893 {
3894 	int cpu;
3895 
3896 	for_each_possible_cpu(cpu) {
3897 		struct scx_kick_pseqs **pseqs = per_cpu_ptr(&scx_kick_pseqs, cpu);
3898 		struct scx_kick_pseqs *to_free;
3899 
3900 		to_free = rcu_replace_pointer(*pseqs, NULL, true);
3901 		if (to_free)
3902 			call_rcu(&to_free->rcu, free_kick_pseqs_rcu);
3903 	}
3904 }
3905 
3906 static void scx_disable_workfn(struct kthread_work *work)
3907 {
3908 	struct scx_sched *sch = container_of(work, struct scx_sched, disable_work);
3909 	struct scx_exit_info *ei = sch->exit_info;
3910 	struct scx_task_iter sti;
3911 	struct task_struct *p;
3912 	int kind, cpu;
3913 
3914 	kind = atomic_read(&sch->exit_kind);
3915 	while (true) {
3916 		if (kind == SCX_EXIT_DONE)	/* already disabled? */
3917 			return;
3918 		WARN_ON_ONCE(kind == SCX_EXIT_NONE);
3919 		if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE))
3920 			break;
3921 	}
3922 	ei->kind = kind;
3923 	ei->reason = scx_exit_reason(ei->kind);
3924 
3925 	/* guarantee forward progress by bypassing scx_ops */
3926 	scx_bypass(true);
3927 
3928 	switch (scx_set_enable_state(SCX_DISABLING)) {
3929 	case SCX_DISABLING:
3930 		WARN_ONCE(true, "sched_ext: duplicate disabling instance?");
3931 		break;
3932 	case SCX_DISABLED:
3933 		pr_warn("sched_ext: ops error detected without ops (%s)\n",
3934 			sch->exit_info->msg);
3935 		WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
3936 		goto done;
3937 	default:
3938 		break;
3939 	}
3940 
3941 	/*
3942 	 * Here, every runnable task is guaranteed to make forward progress and
3943 	 * we can safely use blocking synchronization constructs. Actually
3944 	 * disable ops.
3945 	 */
3946 	mutex_lock(&scx_enable_mutex);
3947 
3948 	static_branch_disable(&__scx_switched_all);
3949 	WRITE_ONCE(scx_switching_all, false);
3950 
3951 	/*
3952 	 * Shut down cgroup support before tasks so that the cgroup attach path
3953 	 * doesn't race against scx_exit_task().
3954 	 */
3955 	scx_cgroup_lock();
3956 	scx_cgroup_exit(sch);
3957 	scx_cgroup_unlock();
3958 
3959 	/*
3960 	 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones
3961 	 * must be switched out and exited synchronously.
3962 	 */
3963 	percpu_down_write(&scx_fork_rwsem);
3964 
3965 	scx_init_task_enabled = false;
3966 
3967 	scx_task_iter_start(&sti);
3968 	while ((p = scx_task_iter_next_locked(&sti))) {
3969 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
3970 		const struct sched_class *old_class = p->sched_class;
3971 		const struct sched_class *new_class =
3972 			__setscheduler_class(p->policy, p->prio);
3973 
3974 		update_rq_clock(task_rq(p));
3975 
3976 		if (old_class != new_class)
3977 			queue_flags |= DEQUEUE_CLASS;
3978 
3979 		scoped_guard (sched_change, p, queue_flags) {
3980 			p->sched_class = new_class;
3981 		}
3982 
3983 		scx_exit_task(p);
3984 	}
3985 	scx_task_iter_stop(&sti);
3986 	percpu_up_write(&scx_fork_rwsem);
3987 
3988 	/*
3989 	 * Invalidate all the rq clocks to prevent getting outdated
3990 	 * rq clocks from a previous scx scheduler.
3991 	 */
3992 	for_each_possible_cpu(cpu) {
3993 		struct rq *rq = cpu_rq(cpu);
3994 		scx_rq_clock_invalidate(rq);
3995 	}
3996 
3997 	/* no task is on scx, turn off all the switches and flush in-progress calls */
3998 	static_branch_disable(&__scx_enabled);
3999 	bitmap_zero(sch->has_op, SCX_OPI_END);
4000 	scx_idle_disable();
4001 	synchronize_rcu();
4002 
4003 	if (ei->kind >= SCX_EXIT_ERROR) {
4004 		pr_err("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
4005 		       sch->ops.name, ei->reason);
4006 
4007 		if (ei->msg[0] != '\0')
4008 			pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg);
4009 #ifdef CONFIG_STACKTRACE
4010 		stack_trace_print(ei->bt, ei->bt_len, 2);
4011 #endif
4012 	} else {
4013 		pr_info("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
4014 			sch->ops.name, ei->reason);
4015 	}
4016 
4017 	if (sch->ops.exit)
4018 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, exit, NULL, ei);
4019 
4020 	cancel_delayed_work_sync(&scx_watchdog_work);
4021 
4022 	/*
4023 	 * scx_root clearing must be inside cpus_read_lock(). See
4024 	 * handle_hotplug().
4025 	 */
4026 	cpus_read_lock();
4027 	RCU_INIT_POINTER(scx_root, NULL);
4028 	cpus_read_unlock();
4029 
4030 	/*
4031 	 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs
4032 	 * could observe an object of the same name still in the hierarchy when
4033 	 * the next scheduler is loaded.
4034 	 */
4035 	kobject_del(&sch->kobj);
4036 
4037 	free_percpu(scx_dsp_ctx);
4038 	scx_dsp_ctx = NULL;
4039 	scx_dsp_max_batch = 0;
4040 	free_kick_pseqs();
4041 
4042 	mutex_unlock(&scx_enable_mutex);
4043 
4044 	WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
4045 done:
4046 	scx_bypass(false);
4047 }
4048 
4049 static void scx_disable(enum scx_exit_kind kind)
4050 {
4051 	int none = SCX_EXIT_NONE;
4052 	struct scx_sched *sch;
4053 
4054 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
4055 		kind = SCX_EXIT_ERROR;
4056 
4057 	rcu_read_lock();
4058 	sch = rcu_dereference(scx_root);
4059 	if (sch) {
4060 		atomic_try_cmpxchg(&sch->exit_kind, &none, kind);
4061 		kthread_queue_work(sch->helper, &sch->disable_work);
4062 	}
4063 	rcu_read_unlock();
4064 }
4065 
4066 static void dump_newline(struct seq_buf *s)
4067 {
4068 	trace_sched_ext_dump("");
4069 
4070 	/* @s may be zero sized and seq_buf triggers WARN if so */
4071 	if (s->size)
4072 		seq_buf_putc(s, '\n');
4073 }
4074 
4075 static __printf(2, 3) void dump_line(struct seq_buf *s, const char *fmt, ...)
4076 {
4077 	va_list args;
4078 
4079 #ifdef CONFIG_TRACEPOINTS
4080 	if (trace_sched_ext_dump_enabled()) {
4081 		/* protected by scx_dump_state()::dump_lock */
4082 		static char line_buf[SCX_EXIT_MSG_LEN];
4083 
4084 		va_start(args, fmt);
4085 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
4086 		va_end(args);
4087 
4088 		trace_sched_ext_dump(line_buf);
4089 	}
4090 #endif
4091 	/* @s may be zero sized and seq_buf triggers WARN if so */
4092 	if (s->size) {
4093 		va_start(args, fmt);
4094 		seq_buf_vprintf(s, fmt, args);
4095 		va_end(args);
4096 
4097 		seq_buf_putc(s, '\n');
4098 	}
4099 }
4100 
4101 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
4102 			     const unsigned long *bt, unsigned int len)
4103 {
4104 	unsigned int i;
4105 
4106 	for (i = 0; i < len; i++)
4107 		dump_line(s, "%s%pS", prefix, (void *)bt[i]);
4108 }
4109 
4110 static void ops_dump_init(struct seq_buf *s, const char *prefix)
4111 {
4112 	struct scx_dump_data *dd = &scx_dump_data;
4113 
4114 	lockdep_assert_irqs_disabled();
4115 
4116 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
4117 	dd->first = true;
4118 	dd->cursor = 0;
4119 	dd->s = s;
4120 	dd->prefix = prefix;
4121 }
4122 
4123 static void ops_dump_flush(void)
4124 {
4125 	struct scx_dump_data *dd = &scx_dump_data;
4126 	char *line = dd->buf.line;
4127 
4128 	if (!dd->cursor)
4129 		return;
4130 
4131 	/*
4132 	 * There's something to flush and this is the first line. Insert a blank
4133 	 * line to distinguish ops dump.
4134 	 */
4135 	if (dd->first) {
4136 		dump_newline(dd->s);
4137 		dd->first = false;
4138 	}
4139 
4140 	/*
4141 	 * There may be multiple lines in $line. Scan and emit each line
4142 	 * separately.
4143 	 */
4144 	while (true) {
4145 		char *end = line;
4146 		char c;
4147 
4148 		while (*end != '\n' && *end != '\0')
4149 			end++;
4150 
4151 		/*
4152 		 * If $line overflowed, it may not have newline at the end.
4153 		 * Always emit with a newline.
4154 		 */
4155 		c = *end;
4156 		*end = '\0';
4157 		dump_line(dd->s, "%s%s", dd->prefix, line);
4158 		if (c == '\0')
4159 			break;
4160 
4161 		/* move to the next line */
4162 		end++;
4163 		if (*end == '\0')
4164 			break;
4165 		line = end;
4166 	}
4167 
4168 	dd->cursor = 0;
4169 }
4170 
4171 static void ops_dump_exit(void)
4172 {
4173 	ops_dump_flush();
4174 	scx_dump_data.cpu = -1;
4175 }
4176 
4177 static void scx_dump_task(struct seq_buf *s, struct scx_dump_ctx *dctx,
4178 			  struct task_struct *p, char marker)
4179 {
4180 	static unsigned long bt[SCX_EXIT_BT_LEN];
4181 	struct scx_sched *sch = scx_root;
4182 	char dsq_id_buf[19] = "(n/a)";
4183 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
4184 	unsigned int bt_len = 0;
4185 
4186 	if (p->scx.dsq)
4187 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
4188 			  (unsigned long long)p->scx.dsq->id);
4189 
4190 	dump_newline(s);
4191 	dump_line(s, " %c%c %s[%d] %+ldms",
4192 		  marker, task_state_to_char(p), p->comm, p->pid,
4193 		  jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
4194 	dump_line(s, "      scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu",
4195 		  scx_get_task_state(p), p->scx.flags & ~SCX_TASK_STATE_MASK,
4196 		  p->scx.dsq_flags, ops_state & SCX_OPSS_STATE_MASK,
4197 		  ops_state >> SCX_OPSS_QSEQ_SHIFT);
4198 	dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
4199 		  p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
4200 	dump_line(s, "      dsq_vtime=%llu slice=%llu weight=%u",
4201 		  p->scx.dsq_vtime, p->scx.slice, p->scx.weight);
4202 	dump_line(s, "      cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr),
4203 		  p->migration_disabled);
4204 
4205 	if (SCX_HAS_OP(sch, dump_task)) {
4206 		ops_dump_init(s, "    ");
4207 		SCX_CALL_OP(sch, SCX_KF_REST, dump_task, NULL, dctx, p);
4208 		ops_dump_exit();
4209 	}
4210 
4211 #ifdef CONFIG_STACKTRACE
4212 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
4213 #endif
4214 	if (bt_len) {
4215 		dump_newline(s);
4216 		dump_stack_trace(s, "    ", bt, bt_len);
4217 	}
4218 }
4219 
4220 static void scx_dump_state(struct scx_exit_info *ei, size_t dump_len)
4221 {
4222 	static DEFINE_SPINLOCK(dump_lock);
4223 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
4224 	struct scx_sched *sch = scx_root;
4225 	struct scx_dump_ctx dctx = {
4226 		.kind = ei->kind,
4227 		.exit_code = ei->exit_code,
4228 		.reason = ei->reason,
4229 		.at_ns = ktime_get_ns(),
4230 		.at_jiffies = jiffies,
4231 	};
4232 	struct seq_buf s;
4233 	struct scx_event_stats events;
4234 	unsigned long flags;
4235 	char *buf;
4236 	int cpu;
4237 
4238 	spin_lock_irqsave(&dump_lock, flags);
4239 
4240 	seq_buf_init(&s, ei->dump, dump_len);
4241 
4242 	if (ei->kind == SCX_EXIT_NONE) {
4243 		dump_line(&s, "Debug dump triggered by %s", ei->reason);
4244 	} else {
4245 		dump_line(&s, "%s[%d] triggered exit kind %d:",
4246 			  current->comm, current->pid, ei->kind);
4247 		dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
4248 		dump_newline(&s);
4249 		dump_line(&s, "Backtrace:");
4250 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
4251 	}
4252 
4253 	if (SCX_HAS_OP(sch, dump)) {
4254 		ops_dump_init(&s, "");
4255 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, dump, NULL, &dctx);
4256 		ops_dump_exit();
4257 	}
4258 
4259 	dump_newline(&s);
4260 	dump_line(&s, "CPU states");
4261 	dump_line(&s, "----------");
4262 
4263 	for_each_possible_cpu(cpu) {
4264 		struct rq *rq = cpu_rq(cpu);
4265 		struct rq_flags rf;
4266 		struct task_struct *p;
4267 		struct seq_buf ns;
4268 		size_t avail, used;
4269 		bool idle;
4270 
4271 		rq_lock(rq, &rf);
4272 
4273 		idle = list_empty(&rq->scx.runnable_list) &&
4274 			rq->curr->sched_class == &idle_sched_class;
4275 
4276 		if (idle && !SCX_HAS_OP(sch, dump_cpu))
4277 			goto next;
4278 
4279 		/*
4280 		 * We don't yet know whether ops.dump_cpu() will produce output
4281 		 * and we may want to skip the default CPU dump if it doesn't.
4282 		 * Use a nested seq_buf to generate the standard dump so that we
4283 		 * can decide whether to commit later.
4284 		 */
4285 		avail = seq_buf_get_buf(&s, &buf);
4286 		seq_buf_init(&ns, buf, avail);
4287 
4288 		dump_newline(&ns);
4289 		dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu pnt_seq=%lu",
4290 			  cpu, rq->scx.nr_running, rq->scx.flags,
4291 			  rq->scx.cpu_released, rq->scx.ops_qseq,
4292 			  rq->scx.pnt_seq);
4293 		dump_line(&ns, "          curr=%s[%d] class=%ps",
4294 			  rq->curr->comm, rq->curr->pid,
4295 			  rq->curr->sched_class);
4296 		if (!cpumask_empty(rq->scx.cpus_to_kick))
4297 			dump_line(&ns, "  cpus_to_kick   : %*pb",
4298 				  cpumask_pr_args(rq->scx.cpus_to_kick));
4299 		if (!cpumask_empty(rq->scx.cpus_to_kick_if_idle))
4300 			dump_line(&ns, "  idle_to_kick   : %*pb",
4301 				  cpumask_pr_args(rq->scx.cpus_to_kick_if_idle));
4302 		if (!cpumask_empty(rq->scx.cpus_to_preempt))
4303 			dump_line(&ns, "  cpus_to_preempt: %*pb",
4304 				  cpumask_pr_args(rq->scx.cpus_to_preempt));
4305 		if (!cpumask_empty(rq->scx.cpus_to_wait))
4306 			dump_line(&ns, "  cpus_to_wait   : %*pb",
4307 				  cpumask_pr_args(rq->scx.cpus_to_wait));
4308 
4309 		used = seq_buf_used(&ns);
4310 		if (SCX_HAS_OP(sch, dump_cpu)) {
4311 			ops_dump_init(&ns, "  ");
4312 			SCX_CALL_OP(sch, SCX_KF_REST, dump_cpu, NULL,
4313 				    &dctx, cpu, idle);
4314 			ops_dump_exit();
4315 		}
4316 
4317 		/*
4318 		 * If idle && nothing generated by ops.dump_cpu(), there's
4319 		 * nothing interesting. Skip.
4320 		 */
4321 		if (idle && used == seq_buf_used(&ns))
4322 			goto next;
4323 
4324 		/*
4325 		 * $s may already have overflowed when $ns was created. If so,
4326 		 * calling commit on it will trigger BUG.
4327 		 */
4328 		if (avail) {
4329 			seq_buf_commit(&s, seq_buf_used(&ns));
4330 			if (seq_buf_has_overflowed(&ns))
4331 				seq_buf_set_overflow(&s);
4332 		}
4333 
4334 		if (rq->curr->sched_class == &ext_sched_class)
4335 			scx_dump_task(&s, &dctx, rq->curr, '*');
4336 
4337 		list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
4338 			scx_dump_task(&s, &dctx, p, ' ');
4339 	next:
4340 		rq_unlock(rq, &rf);
4341 	}
4342 
4343 	dump_newline(&s);
4344 	dump_line(&s, "Event counters");
4345 	dump_line(&s, "--------------");
4346 
4347 	scx_read_events(sch, &events);
4348 	scx_dump_event(s, &events, SCX_EV_SELECT_CPU_FALLBACK);
4349 	scx_dump_event(s, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
4350 	scx_dump_event(s, &events, SCX_EV_DISPATCH_KEEP_LAST);
4351 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_EXITING);
4352 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
4353 	scx_dump_event(s, &events, SCX_EV_REFILL_SLICE_DFL);
4354 	scx_dump_event(s, &events, SCX_EV_BYPASS_DURATION);
4355 	scx_dump_event(s, &events, SCX_EV_BYPASS_DISPATCH);
4356 	scx_dump_event(s, &events, SCX_EV_BYPASS_ACTIVATE);
4357 
4358 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
4359 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
4360 		       trunc_marker, sizeof(trunc_marker));
4361 
4362 	spin_unlock_irqrestore(&dump_lock, flags);
4363 }
4364 
4365 static void scx_error_irq_workfn(struct irq_work *irq_work)
4366 {
4367 	struct scx_sched *sch = container_of(irq_work, struct scx_sched, error_irq_work);
4368 	struct scx_exit_info *ei = sch->exit_info;
4369 
4370 	if (ei->kind >= SCX_EXIT_ERROR)
4371 		scx_dump_state(ei, sch->ops.exit_dump_len);
4372 
4373 	kthread_queue_work(sch->helper, &sch->disable_work);
4374 }
4375 
4376 static void scx_vexit(struct scx_sched *sch,
4377 		      enum scx_exit_kind kind, s64 exit_code,
4378 		      const char *fmt, va_list args)
4379 {
4380 	struct scx_exit_info *ei = sch->exit_info;
4381 	int none = SCX_EXIT_NONE;
4382 
4383 	if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind))
4384 		return;
4385 
4386 	ei->exit_code = exit_code;
4387 #ifdef CONFIG_STACKTRACE
4388 	if (kind >= SCX_EXIT_ERROR)
4389 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
4390 #endif
4391 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
4392 
4393 	/*
4394 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
4395 	 * in scx_disable_workfn().
4396 	 */
4397 	ei->kind = kind;
4398 	ei->reason = scx_exit_reason(ei->kind);
4399 
4400 	irq_work_queue(&sch->error_irq_work);
4401 }
4402 
4403 static int alloc_kick_pseqs(void)
4404 {
4405 	int cpu;
4406 
4407 	/*
4408 	 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size
4409 	 * can exceed percpu allocator limits on large machines.
4410 	 */
4411 	for_each_possible_cpu(cpu) {
4412 		struct scx_kick_pseqs **pseqs = per_cpu_ptr(&scx_kick_pseqs, cpu);
4413 		struct scx_kick_pseqs *new_pseqs;
4414 
4415 		WARN_ON_ONCE(rcu_access_pointer(*pseqs));
4416 
4417 		new_pseqs = kvzalloc_node(struct_size(new_pseqs, seqs, nr_cpu_ids),
4418 					  GFP_KERNEL, cpu_to_node(cpu));
4419 		if (!new_pseqs) {
4420 			free_kick_pseqs();
4421 			return -ENOMEM;
4422 		}
4423 
4424 		rcu_assign_pointer(*pseqs, new_pseqs);
4425 	}
4426 
4427 	return 0;
4428 }
4429 
4430 static struct scx_sched *scx_alloc_and_add_sched(struct sched_ext_ops *ops)
4431 {
4432 	struct scx_sched *sch;
4433 	int node, ret;
4434 
4435 	sch = kzalloc(sizeof(*sch), GFP_KERNEL);
4436 	if (!sch)
4437 		return ERR_PTR(-ENOMEM);
4438 
4439 	sch->exit_info = alloc_exit_info(ops->exit_dump_len);
4440 	if (!sch->exit_info) {
4441 		ret = -ENOMEM;
4442 		goto err_free_sch;
4443 	}
4444 
4445 	ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params);
4446 	if (ret < 0)
4447 		goto err_free_ei;
4448 
4449 	sch->global_dsqs = kcalloc(nr_node_ids, sizeof(sch->global_dsqs[0]),
4450 				   GFP_KERNEL);
4451 	if (!sch->global_dsqs) {
4452 		ret = -ENOMEM;
4453 		goto err_free_hash;
4454 	}
4455 
4456 	for_each_node_state(node, N_POSSIBLE) {
4457 		struct scx_dispatch_q *dsq;
4458 
4459 		dsq = kzalloc_node(sizeof(*dsq), GFP_KERNEL, node);
4460 		if (!dsq) {
4461 			ret = -ENOMEM;
4462 			goto err_free_gdsqs;
4463 		}
4464 
4465 		init_dsq(dsq, SCX_DSQ_GLOBAL);
4466 		sch->global_dsqs[node] = dsq;
4467 	}
4468 
4469 	sch->pcpu = alloc_percpu(struct scx_sched_pcpu);
4470 	if (!sch->pcpu)
4471 		goto err_free_gdsqs;
4472 
4473 	sch->helper = kthread_run_worker(0, "sched_ext_helper");
4474 	if (!sch->helper)
4475 		goto err_free_pcpu;
4476 	sched_set_fifo(sch->helper->task);
4477 
4478 	atomic_set(&sch->exit_kind, SCX_EXIT_NONE);
4479 	init_irq_work(&sch->error_irq_work, scx_error_irq_workfn);
4480 	kthread_init_work(&sch->disable_work, scx_disable_workfn);
4481 	sch->ops = *ops;
4482 	ops->priv = sch;
4483 
4484 	sch->kobj.kset = scx_kset;
4485 	ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root");
4486 	if (ret < 0)
4487 		goto err_stop_helper;
4488 
4489 	return sch;
4490 
4491 err_stop_helper:
4492 	kthread_stop(sch->helper->task);
4493 err_free_pcpu:
4494 	free_percpu(sch->pcpu);
4495 err_free_gdsqs:
4496 	for_each_node_state(node, N_POSSIBLE)
4497 		kfree(sch->global_dsqs[node]);
4498 	kfree(sch->global_dsqs);
4499 err_free_hash:
4500 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
4501 err_free_ei:
4502 	free_exit_info(sch->exit_info);
4503 err_free_sch:
4504 	kfree(sch);
4505 	return ERR_PTR(ret);
4506 }
4507 
4508 static int check_hotplug_seq(struct scx_sched *sch,
4509 			      const struct sched_ext_ops *ops)
4510 {
4511 	unsigned long long global_hotplug_seq;
4512 
4513 	/*
4514 	 * If a hotplug event has occurred between when a scheduler was
4515 	 * initialized, and when we were able to attach, exit and notify user
4516 	 * space about it.
4517 	 */
4518 	if (ops->hotplug_seq) {
4519 		global_hotplug_seq = atomic_long_read(&scx_hotplug_seq);
4520 		if (ops->hotplug_seq != global_hotplug_seq) {
4521 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
4522 				 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
4523 				 "expected hotplug seq %llu did not match actual %llu",
4524 				 ops->hotplug_seq, global_hotplug_seq);
4525 			return -EBUSY;
4526 		}
4527 	}
4528 
4529 	return 0;
4530 }
4531 
4532 static int validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
4533 {
4534 	/*
4535 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
4536 	 * ops.enqueue() callback isn't implemented.
4537 	 */
4538 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
4539 		scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
4540 		return -EINVAL;
4541 	}
4542 
4543 	/*
4544 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle
4545 	 * selection policy to be enabled.
4546 	 */
4547 	if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) &&
4548 	    (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) {
4549 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled");
4550 		return -EINVAL;
4551 	}
4552 
4553 	if (ops->flags & SCX_OPS_HAS_CGROUP_WEIGHT)
4554 		pr_warn("SCX_OPS_HAS_CGROUP_WEIGHT is deprecated and a noop\n");
4555 
4556 	return 0;
4557 }
4558 
4559 static int scx_enable(struct sched_ext_ops *ops, struct bpf_link *link)
4560 {
4561 	struct scx_sched *sch;
4562 	struct scx_task_iter sti;
4563 	struct task_struct *p;
4564 	unsigned long timeout;
4565 	int i, cpu, ret;
4566 
4567 	if (!cpumask_equal(housekeeping_cpumask(HK_TYPE_DOMAIN),
4568 			   cpu_possible_mask)) {
4569 		pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n");
4570 		return -EINVAL;
4571 	}
4572 
4573 	mutex_lock(&scx_enable_mutex);
4574 
4575 	if (scx_enable_state() != SCX_DISABLED) {
4576 		ret = -EBUSY;
4577 		goto err_unlock;
4578 	}
4579 
4580 	ret = alloc_kick_pseqs();
4581 	if (ret)
4582 		goto err_unlock;
4583 
4584 	sch = scx_alloc_and_add_sched(ops);
4585 	if (IS_ERR(sch)) {
4586 		ret = PTR_ERR(sch);
4587 		goto err_free_pseqs;
4588 	}
4589 
4590 	/*
4591 	 * Transition to ENABLING and clear exit info to arm the disable path.
4592 	 * Failure triggers full disabling from here on.
4593 	 */
4594 	WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED);
4595 	WARN_ON_ONCE(scx_root);
4596 
4597 	atomic_long_set(&scx_nr_rejected, 0);
4598 
4599 	for_each_possible_cpu(cpu)
4600 		cpu_rq(cpu)->scx.cpuperf_target = SCX_CPUPERF_ONE;
4601 
4602 	/*
4603 	 * Keep CPUs stable during enable so that the BPF scheduler can track
4604 	 * online CPUs by watching ->on/offline_cpu() after ->init().
4605 	 */
4606 	cpus_read_lock();
4607 
4608 	/*
4609 	 * Make the scheduler instance visible. Must be inside cpus_read_lock().
4610 	 * See handle_hotplug().
4611 	 */
4612 	rcu_assign_pointer(scx_root, sch);
4613 
4614 	scx_idle_enable(ops);
4615 
4616 	if (sch->ops.init) {
4617 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init, NULL);
4618 		if (ret) {
4619 			ret = ops_sanitize_err(sch, "init", ret);
4620 			cpus_read_unlock();
4621 			scx_error(sch, "ops.init() failed (%d)", ret);
4622 			goto err_disable;
4623 		}
4624 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
4625 	}
4626 
4627 	for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++)
4628 		if (((void (**)(void))ops)[i])
4629 			set_bit(i, sch->has_op);
4630 
4631 	ret = check_hotplug_seq(sch, ops);
4632 	if (ret) {
4633 		cpus_read_unlock();
4634 		goto err_disable;
4635 	}
4636 	scx_idle_update_selcpu_topology(ops);
4637 
4638 	cpus_read_unlock();
4639 
4640 	ret = validate_ops(sch, ops);
4641 	if (ret)
4642 		goto err_disable;
4643 
4644 	WARN_ON_ONCE(scx_dsp_ctx);
4645 	scx_dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
4646 	scx_dsp_ctx = __alloc_percpu(struct_size_t(struct scx_dsp_ctx, buf,
4647 						   scx_dsp_max_batch),
4648 				     __alignof__(struct scx_dsp_ctx));
4649 	if (!scx_dsp_ctx) {
4650 		ret = -ENOMEM;
4651 		goto err_disable;
4652 	}
4653 
4654 	if (ops->timeout_ms)
4655 		timeout = msecs_to_jiffies(ops->timeout_ms);
4656 	else
4657 		timeout = SCX_WATCHDOG_MAX_TIMEOUT;
4658 
4659 	WRITE_ONCE(scx_watchdog_timeout, timeout);
4660 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
4661 	queue_delayed_work(system_unbound_wq, &scx_watchdog_work,
4662 			   scx_watchdog_timeout / 2);
4663 
4664 	/*
4665 	 * Once __scx_enabled is set, %current can be switched to SCX anytime.
4666 	 * This can lead to stalls as some BPF schedulers (e.g. userspace
4667 	 * scheduling) may not function correctly before all tasks are switched.
4668 	 * Init in bypass mode to guarantee forward progress.
4669 	 */
4670 	scx_bypass(true);
4671 
4672 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
4673 		if (((void (**)(void))ops)[i])
4674 			set_bit(i, sch->has_op);
4675 
4676 	if (sch->ops.cpu_acquire || sch->ops.cpu_release)
4677 		sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT;
4678 
4679 	/*
4680 	 * Lock out forks, cgroup on/offlining and moves before opening the
4681 	 * floodgate so that they don't wander into the operations prematurely.
4682 	 */
4683 	percpu_down_write(&scx_fork_rwsem);
4684 
4685 	WARN_ON_ONCE(scx_init_task_enabled);
4686 	scx_init_task_enabled = true;
4687 
4688 	/*
4689 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
4690 	 * preventing new tasks from being added. No need to exclude tasks
4691 	 * leaving as sched_ext_free() can handle both prepped and enabled
4692 	 * tasks. Prep all tasks first and then enable them with preemption
4693 	 * disabled.
4694 	 *
4695 	 * All cgroups should be initialized before scx_init_task() so that the
4696 	 * BPF scheduler can reliably track each task's cgroup membership from
4697 	 * scx_init_task(). Lock out cgroup on/offlining and task migrations
4698 	 * while tasks are being initialized so that scx_cgroup_can_attach()
4699 	 * never sees uninitialized tasks.
4700 	 */
4701 	scx_cgroup_lock();
4702 	ret = scx_cgroup_init(sch);
4703 	if (ret)
4704 		goto err_disable_unlock_all;
4705 
4706 	scx_task_iter_start(&sti);
4707 	while ((p = scx_task_iter_next_locked(&sti))) {
4708 		/*
4709 		 * @p may already be dead, have lost all its usages counts and
4710 		 * be waiting for RCU grace period before being freed. @p can't
4711 		 * be initialized for SCX in such cases and should be ignored.
4712 		 */
4713 		if (!tryget_task_struct(p))
4714 			continue;
4715 
4716 		scx_task_iter_unlock(&sti);
4717 
4718 		ret = scx_init_task(p, task_group(p), false);
4719 		if (ret) {
4720 			put_task_struct(p);
4721 			scx_task_iter_stop(&sti);
4722 			scx_error(sch, "ops.init_task() failed (%d) for %s[%d]",
4723 				  ret, p->comm, p->pid);
4724 			goto err_disable_unlock_all;
4725 		}
4726 
4727 		scx_set_task_state(p, SCX_TASK_READY);
4728 
4729 		put_task_struct(p);
4730 	}
4731 	scx_task_iter_stop(&sti);
4732 	scx_cgroup_unlock();
4733 	percpu_up_write(&scx_fork_rwsem);
4734 
4735 	/*
4736 	 * All tasks are READY. It's safe to turn on scx_enabled() and switch
4737 	 * all eligible tasks.
4738 	 */
4739 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
4740 	static_branch_enable(&__scx_enabled);
4741 
4742 	/*
4743 	 * We're fully committed and can't fail. The task READY -> ENABLED
4744 	 * transitions here are synchronized against sched_ext_free() through
4745 	 * scx_tasks_lock.
4746 	 */
4747 	percpu_down_write(&scx_fork_rwsem);
4748 	scx_task_iter_start(&sti);
4749 	while ((p = scx_task_iter_next_locked(&sti))) {
4750 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
4751 		const struct sched_class *old_class = p->sched_class;
4752 		const struct sched_class *new_class =
4753 			__setscheduler_class(p->policy, p->prio);
4754 
4755 		if (!tryget_task_struct(p))
4756 			continue;
4757 
4758 		if (old_class != new_class)
4759 			queue_flags |= DEQUEUE_CLASS;
4760 
4761 		scoped_guard (sched_change, p, queue_flags) {
4762 			p->scx.slice = SCX_SLICE_DFL;
4763 			p->sched_class = new_class;
4764 		}
4765 
4766 		put_task_struct(p);
4767 	}
4768 	scx_task_iter_stop(&sti);
4769 	percpu_up_write(&scx_fork_rwsem);
4770 
4771 	scx_bypass(false);
4772 
4773 	if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) {
4774 		WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE);
4775 		goto err_disable;
4776 	}
4777 
4778 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
4779 		static_branch_enable(&__scx_switched_all);
4780 
4781 	pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n",
4782 		sch->ops.name, scx_switched_all() ? "" : " (partial)");
4783 	kobject_uevent(&sch->kobj, KOBJ_ADD);
4784 	mutex_unlock(&scx_enable_mutex);
4785 
4786 	atomic_long_inc(&scx_enable_seq);
4787 
4788 	return 0;
4789 
4790 err_free_pseqs:
4791 	free_kick_pseqs();
4792 err_unlock:
4793 	mutex_unlock(&scx_enable_mutex);
4794 	return ret;
4795 
4796 err_disable_unlock_all:
4797 	scx_cgroup_unlock();
4798 	percpu_up_write(&scx_fork_rwsem);
4799 	/* we'll soon enter disable path, keep bypass on */
4800 err_disable:
4801 	mutex_unlock(&scx_enable_mutex);
4802 	/*
4803 	 * Returning an error code here would not pass all the error information
4804 	 * to userspace. Record errno using scx_error() for cases scx_error()
4805 	 * wasn't already invoked and exit indicating success so that the error
4806 	 * is notified through ops.exit() with all the details.
4807 	 *
4808 	 * Flush scx_disable_work to ensure that error is reported before init
4809 	 * completion. sch's base reference will be put by bpf_scx_unreg().
4810 	 */
4811 	scx_error(sch, "scx_enable() failed (%d)", ret);
4812 	kthread_flush_work(&sch->disable_work);
4813 	return 0;
4814 }
4815 
4816 
4817 /********************************************************************************
4818  * bpf_struct_ops plumbing.
4819  */
4820 #include <linux/bpf_verifier.h>
4821 #include <linux/bpf.h>
4822 #include <linux/btf.h>
4823 
4824 static const struct btf_type *task_struct_type;
4825 
4826 static bool bpf_scx_is_valid_access(int off, int size,
4827 				    enum bpf_access_type type,
4828 				    const struct bpf_prog *prog,
4829 				    struct bpf_insn_access_aux *info)
4830 {
4831 	if (type != BPF_READ)
4832 		return false;
4833 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
4834 		return false;
4835 	if (off % size != 0)
4836 		return false;
4837 
4838 	return btf_ctx_access(off, size, type, prog, info);
4839 }
4840 
4841 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
4842 				     const struct bpf_reg_state *reg, int off,
4843 				     int size)
4844 {
4845 	const struct btf_type *t;
4846 
4847 	t = btf_type_by_id(reg->btf, reg->btf_id);
4848 	if (t == task_struct_type) {
4849 		if (off >= offsetof(struct task_struct, scx.slice) &&
4850 		    off + size <= offsetofend(struct task_struct, scx.slice))
4851 			return SCALAR_VALUE;
4852 		if (off >= offsetof(struct task_struct, scx.dsq_vtime) &&
4853 		    off + size <= offsetofend(struct task_struct, scx.dsq_vtime))
4854 			return SCALAR_VALUE;
4855 		if (off >= offsetof(struct task_struct, scx.disallow) &&
4856 		    off + size <= offsetofend(struct task_struct, scx.disallow))
4857 			return SCALAR_VALUE;
4858 	}
4859 
4860 	return -EACCES;
4861 }
4862 
4863 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
4864 	.get_func_proto = bpf_base_func_proto,
4865 	.is_valid_access = bpf_scx_is_valid_access,
4866 	.btf_struct_access = bpf_scx_btf_struct_access,
4867 };
4868 
4869 static int bpf_scx_init_member(const struct btf_type *t,
4870 			       const struct btf_member *member,
4871 			       void *kdata, const void *udata)
4872 {
4873 	const struct sched_ext_ops *uops = udata;
4874 	struct sched_ext_ops *ops = kdata;
4875 	u32 moff = __btf_member_bit_offset(t, member) / 8;
4876 	int ret;
4877 
4878 	switch (moff) {
4879 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
4880 		if (*(u32 *)(udata + moff) > INT_MAX)
4881 			return -E2BIG;
4882 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
4883 		return 1;
4884 	case offsetof(struct sched_ext_ops, flags):
4885 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
4886 			return -EINVAL;
4887 		ops->flags = *(u64 *)(udata + moff);
4888 		return 1;
4889 	case offsetof(struct sched_ext_ops, name):
4890 		ret = bpf_obj_name_cpy(ops->name, uops->name,
4891 				       sizeof(ops->name));
4892 		if (ret < 0)
4893 			return ret;
4894 		if (ret == 0)
4895 			return -EINVAL;
4896 		return 1;
4897 	case offsetof(struct sched_ext_ops, timeout_ms):
4898 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
4899 		    SCX_WATCHDOG_MAX_TIMEOUT)
4900 			return -E2BIG;
4901 		ops->timeout_ms = *(u32 *)(udata + moff);
4902 		return 1;
4903 	case offsetof(struct sched_ext_ops, exit_dump_len):
4904 		ops->exit_dump_len =
4905 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
4906 		return 1;
4907 	case offsetof(struct sched_ext_ops, hotplug_seq):
4908 		ops->hotplug_seq = *(u64 *)(udata + moff);
4909 		return 1;
4910 	}
4911 
4912 	return 0;
4913 }
4914 
4915 static int bpf_scx_check_member(const struct btf_type *t,
4916 				const struct btf_member *member,
4917 				const struct bpf_prog *prog)
4918 {
4919 	u32 moff = __btf_member_bit_offset(t, member) / 8;
4920 
4921 	switch (moff) {
4922 	case offsetof(struct sched_ext_ops, init_task):
4923 #ifdef CONFIG_EXT_GROUP_SCHED
4924 	case offsetof(struct sched_ext_ops, cgroup_init):
4925 	case offsetof(struct sched_ext_ops, cgroup_exit):
4926 	case offsetof(struct sched_ext_ops, cgroup_prep_move):
4927 #endif
4928 	case offsetof(struct sched_ext_ops, cpu_online):
4929 	case offsetof(struct sched_ext_ops, cpu_offline):
4930 	case offsetof(struct sched_ext_ops, init):
4931 	case offsetof(struct sched_ext_ops, exit):
4932 		break;
4933 	default:
4934 		if (prog->sleepable)
4935 			return -EINVAL;
4936 	}
4937 
4938 	return 0;
4939 }
4940 
4941 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
4942 {
4943 	return scx_enable(kdata, link);
4944 }
4945 
4946 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
4947 {
4948 	struct sched_ext_ops *ops = kdata;
4949 	struct scx_sched *sch = ops->priv;
4950 
4951 	scx_disable(SCX_EXIT_UNREG);
4952 	kthread_flush_work(&sch->disable_work);
4953 	kobject_put(&sch->kobj);
4954 }
4955 
4956 static int bpf_scx_init(struct btf *btf)
4957 {
4958 	task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]);
4959 
4960 	return 0;
4961 }
4962 
4963 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
4964 {
4965 	/*
4966 	 * sched_ext does not support updating the actively-loaded BPF
4967 	 * scheduler, as registering a BPF scheduler can always fail if the
4968 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
4969 	 * etc. Similarly, we can always race with unregistration happening
4970 	 * elsewhere, such as with sysrq.
4971 	 */
4972 	return -EOPNOTSUPP;
4973 }
4974 
4975 static int bpf_scx_validate(void *kdata)
4976 {
4977 	return 0;
4978 }
4979 
4980 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
4981 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
4982 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
4983 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {}
4984 static void sched_ext_ops__tick(struct task_struct *p) {}
4985 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {}
4986 static void sched_ext_ops__running(struct task_struct *p) {}
4987 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {}
4988 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {}
4989 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; }
4990 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; }
4991 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {}
4992 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {}
4993 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {}
4994 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {}
4995 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {}
4996 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
4997 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {}
4998 static void sched_ext_ops__enable(struct task_struct *p) {}
4999 static void sched_ext_ops__disable(struct task_struct *p) {}
5000 #ifdef CONFIG_EXT_GROUP_SCHED
5001 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; }
5002 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {}
5003 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; }
5004 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
5005 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
5006 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
5007 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
5008 static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}
5009 #endif
5010 static void sched_ext_ops__cpu_online(s32 cpu) {}
5011 static void sched_ext_ops__cpu_offline(s32 cpu) {}
5012 static s32 sched_ext_ops__init(void) { return -EINVAL; }
5013 static void sched_ext_ops__exit(struct scx_exit_info *info) {}
5014 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {}
5015 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {}
5016 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {}
5017 
5018 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
5019 	.select_cpu		= sched_ext_ops__select_cpu,
5020 	.enqueue		= sched_ext_ops__enqueue,
5021 	.dequeue		= sched_ext_ops__dequeue,
5022 	.dispatch		= sched_ext_ops__dispatch,
5023 	.tick			= sched_ext_ops__tick,
5024 	.runnable		= sched_ext_ops__runnable,
5025 	.running		= sched_ext_ops__running,
5026 	.stopping		= sched_ext_ops__stopping,
5027 	.quiescent		= sched_ext_ops__quiescent,
5028 	.yield			= sched_ext_ops__yield,
5029 	.core_sched_before	= sched_ext_ops__core_sched_before,
5030 	.set_weight		= sched_ext_ops__set_weight,
5031 	.set_cpumask		= sched_ext_ops__set_cpumask,
5032 	.update_idle		= sched_ext_ops__update_idle,
5033 	.cpu_acquire		= sched_ext_ops__cpu_acquire,
5034 	.cpu_release		= sched_ext_ops__cpu_release,
5035 	.init_task		= sched_ext_ops__init_task,
5036 	.exit_task		= sched_ext_ops__exit_task,
5037 	.enable			= sched_ext_ops__enable,
5038 	.disable		= sched_ext_ops__disable,
5039 #ifdef CONFIG_EXT_GROUP_SCHED
5040 	.cgroup_init		= sched_ext_ops__cgroup_init,
5041 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
5042 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
5043 	.cgroup_move		= sched_ext_ops__cgroup_move,
5044 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
5045 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
5046 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
5047 	.cgroup_set_idle	= sched_ext_ops__cgroup_set_idle,
5048 #endif
5049 	.cpu_online		= sched_ext_ops__cpu_online,
5050 	.cpu_offline		= sched_ext_ops__cpu_offline,
5051 	.init			= sched_ext_ops__init,
5052 	.exit			= sched_ext_ops__exit,
5053 	.dump			= sched_ext_ops__dump,
5054 	.dump_cpu		= sched_ext_ops__dump_cpu,
5055 	.dump_task		= sched_ext_ops__dump_task,
5056 };
5057 
5058 static struct bpf_struct_ops bpf_sched_ext_ops = {
5059 	.verifier_ops = &bpf_scx_verifier_ops,
5060 	.reg = bpf_scx_reg,
5061 	.unreg = bpf_scx_unreg,
5062 	.check_member = bpf_scx_check_member,
5063 	.init_member = bpf_scx_init_member,
5064 	.init = bpf_scx_init,
5065 	.update = bpf_scx_update,
5066 	.validate = bpf_scx_validate,
5067 	.name = "sched_ext_ops",
5068 	.owner = THIS_MODULE,
5069 	.cfi_stubs = &__bpf_ops_sched_ext_ops
5070 };
5071 
5072 
5073 /********************************************************************************
5074  * System integration and init.
5075  */
5076 
5077 static void sysrq_handle_sched_ext_reset(u8 key)
5078 {
5079 	scx_disable(SCX_EXIT_SYSRQ);
5080 }
5081 
5082 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
5083 	.handler	= sysrq_handle_sched_ext_reset,
5084 	.help_msg	= "reset-sched-ext(S)",
5085 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
5086 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
5087 };
5088 
5089 static void sysrq_handle_sched_ext_dump(u8 key)
5090 {
5091 	struct scx_exit_info ei = { .kind = SCX_EXIT_NONE, .reason = "SysRq-D" };
5092 
5093 	if (scx_enabled())
5094 		scx_dump_state(&ei, 0);
5095 }
5096 
5097 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
5098 	.handler	= sysrq_handle_sched_ext_dump,
5099 	.help_msg	= "dump-sched-ext(D)",
5100 	.action_msg	= "Trigger sched_ext debug dump",
5101 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
5102 };
5103 
5104 static bool can_skip_idle_kick(struct rq *rq)
5105 {
5106 	lockdep_assert_rq_held(rq);
5107 
5108 	/*
5109 	 * We can skip idle kicking if @rq is going to go through at least one
5110 	 * full SCX scheduling cycle before going idle. Just checking whether
5111 	 * curr is not idle is insufficient because we could be racing
5112 	 * balance_one() trying to pull the next task from a remote rq, which
5113 	 * may fail, and @rq may become idle afterwards.
5114 	 *
5115 	 * The race window is small and we don't and can't guarantee that @rq is
5116 	 * only kicked while idle anyway. Skip only when sure.
5117 	 */
5118 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_BALANCE);
5119 }
5120 
5121 static bool kick_one_cpu(s32 cpu, struct rq *this_rq, unsigned long *pseqs)
5122 {
5123 	struct rq *rq = cpu_rq(cpu);
5124 	struct scx_rq *this_scx = &this_rq->scx;
5125 	bool should_wait = false;
5126 	unsigned long flags;
5127 
5128 	raw_spin_rq_lock_irqsave(rq, flags);
5129 
5130 	/*
5131 	 * During CPU hotplug, a CPU may depend on kicking itself to make
5132 	 * forward progress. Allow kicking self regardless of online state.
5133 	 */
5134 	if (cpu_online(cpu) || cpu == cpu_of(this_rq)) {
5135 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_preempt)) {
5136 			if (rq->curr->sched_class == &ext_sched_class)
5137 				rq->curr->scx.slice = 0;
5138 			cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
5139 		}
5140 
5141 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_wait)) {
5142 			pseqs[cpu] = rq->scx.pnt_seq;
5143 			should_wait = true;
5144 		}
5145 
5146 		resched_curr(rq);
5147 	} else {
5148 		cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
5149 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
5150 	}
5151 
5152 	raw_spin_rq_unlock_irqrestore(rq, flags);
5153 
5154 	return should_wait;
5155 }
5156 
5157 static void kick_one_cpu_if_idle(s32 cpu, struct rq *this_rq)
5158 {
5159 	struct rq *rq = cpu_rq(cpu);
5160 	unsigned long flags;
5161 
5162 	raw_spin_rq_lock_irqsave(rq, flags);
5163 
5164 	if (!can_skip_idle_kick(rq) &&
5165 	    (cpu_online(cpu) || cpu == cpu_of(this_rq)))
5166 		resched_curr(rq);
5167 
5168 	raw_spin_rq_unlock_irqrestore(rq, flags);
5169 }
5170 
5171 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
5172 {
5173 	struct rq *this_rq = this_rq();
5174 	struct scx_rq *this_scx = &this_rq->scx;
5175 	struct scx_kick_pseqs __rcu *pseqs_pcpu = __this_cpu_read(scx_kick_pseqs);
5176 	bool should_wait = false;
5177 	unsigned long *pseqs;
5178 	s32 cpu;
5179 
5180 	if (unlikely(!pseqs_pcpu)) {
5181 		pr_warn_once("kick_cpus_irq_workfn() called with NULL scx_kick_pseqs");
5182 		return;
5183 	}
5184 
5185 	pseqs = rcu_dereference_bh(pseqs_pcpu)->seqs;
5186 
5187 	for_each_cpu(cpu, this_scx->cpus_to_kick) {
5188 		should_wait |= kick_one_cpu(cpu, this_rq, pseqs);
5189 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick);
5190 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
5191 	}
5192 
5193 	for_each_cpu(cpu, this_scx->cpus_to_kick_if_idle) {
5194 		kick_one_cpu_if_idle(cpu, this_rq);
5195 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
5196 	}
5197 
5198 	if (!should_wait)
5199 		return;
5200 
5201 	for_each_cpu(cpu, this_scx->cpus_to_wait) {
5202 		unsigned long *wait_pnt_seq = &cpu_rq(cpu)->scx.pnt_seq;
5203 
5204 		if (cpu != cpu_of(this_rq)) {
5205 			/*
5206 			 * Pairs with smp_store_release() issued by this CPU in
5207 			 * switch_class() on the resched path.
5208 			 *
5209 			 * We busy-wait here to guarantee that no other task can
5210 			 * be scheduled on our core before the target CPU has
5211 			 * entered the resched path.
5212 			 */
5213 			while (smp_load_acquire(wait_pnt_seq) == pseqs[cpu])
5214 				cpu_relax();
5215 		}
5216 
5217 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
5218 	}
5219 }
5220 
5221 /**
5222  * print_scx_info - print out sched_ext scheduler state
5223  * @log_lvl: the log level to use when printing
5224  * @p: target task
5225  *
5226  * If a sched_ext scheduler is enabled, print the name and state of the
5227  * scheduler. If @p is on sched_ext, print further information about the task.
5228  *
5229  * This function can be safely called on any task as long as the task_struct
5230  * itself is accessible. While safe, this function isn't synchronized and may
5231  * print out mixups or garbages of limited length.
5232  */
5233 void print_scx_info(const char *log_lvl, struct task_struct *p)
5234 {
5235 	struct scx_sched *sch = scx_root;
5236 	enum scx_enable_state state = scx_enable_state();
5237 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
5238 	char runnable_at_buf[22] = "?";
5239 	struct sched_class *class;
5240 	unsigned long runnable_at;
5241 
5242 	if (state == SCX_DISABLED)
5243 		return;
5244 
5245 	/*
5246 	 * Carefully check if the task was running on sched_ext, and then
5247 	 * carefully copy the time it's been runnable, and its state.
5248 	 */
5249 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
5250 	    class != &ext_sched_class) {
5251 		printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name,
5252 		       scx_enable_state_str[state], all);
5253 		return;
5254 	}
5255 
5256 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
5257 				      sizeof(runnable_at)))
5258 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
5259 			  jiffies_delta_msecs(runnable_at, jiffies));
5260 
5261 	/* print everything onto one line to conserve console space */
5262 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
5263 	       log_lvl, sch->ops.name, scx_enable_state_str[state], all,
5264 	       runnable_at_buf);
5265 }
5266 
5267 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr)
5268 {
5269 	/*
5270 	 * SCX schedulers often have userspace components which are sometimes
5271 	 * involved in critial scheduling paths. PM operations involve freezing
5272 	 * userspace which can lead to scheduling misbehaviors including stalls.
5273 	 * Let's bypass while PM operations are in progress.
5274 	 */
5275 	switch (event) {
5276 	case PM_HIBERNATION_PREPARE:
5277 	case PM_SUSPEND_PREPARE:
5278 	case PM_RESTORE_PREPARE:
5279 		scx_bypass(true);
5280 		break;
5281 	case PM_POST_HIBERNATION:
5282 	case PM_POST_SUSPEND:
5283 	case PM_POST_RESTORE:
5284 		scx_bypass(false);
5285 		break;
5286 	}
5287 
5288 	return NOTIFY_OK;
5289 }
5290 
5291 static struct notifier_block scx_pm_notifier = {
5292 	.notifier_call = scx_pm_handler,
5293 };
5294 
5295 void __init init_sched_ext_class(void)
5296 {
5297 	s32 cpu, v;
5298 
5299 	/*
5300 	 * The following is to prevent the compiler from optimizing out the enum
5301 	 * definitions so that BPF scheduler implementations can use them
5302 	 * through the generated vmlinux.h.
5303 	 */
5304 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT |
5305 		   SCX_TG_ONLINE);
5306 
5307 	scx_idle_init_masks();
5308 
5309 	for_each_possible_cpu(cpu) {
5310 		struct rq *rq = cpu_rq(cpu);
5311 		int  n = cpu_to_node(cpu);
5312 
5313 		init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL);
5314 		INIT_LIST_HEAD(&rq->scx.runnable_list);
5315 		INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals);
5316 
5317 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick, GFP_KERNEL, n));
5318 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick_if_idle, GFP_KERNEL, n));
5319 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_preempt, GFP_KERNEL, n));
5320 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_wait, GFP_KERNEL, n));
5321 		init_irq_work(&rq->scx.deferred_irq_work, deferred_irq_workfn);
5322 		init_irq_work(&rq->scx.kick_cpus_irq_work, kick_cpus_irq_workfn);
5323 
5324 		if (cpu_online(cpu))
5325 			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
5326 	}
5327 
5328 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
5329 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
5330 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
5331 }
5332 
5333 
5334 /********************************************************************************
5335  * Helpers that can be called from the BPF scheduler.
5336  */
5337 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p,
5338 				    u64 enq_flags)
5339 {
5340 	if (!scx_kf_allowed(sch, SCX_KF_ENQUEUE | SCX_KF_DISPATCH))
5341 		return false;
5342 
5343 	lockdep_assert_irqs_disabled();
5344 
5345 	if (unlikely(!p)) {
5346 		scx_error(sch, "called with NULL task");
5347 		return false;
5348 	}
5349 
5350 	if (unlikely(enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
5351 		scx_error(sch, "invalid enq_flags 0x%llx", enq_flags);
5352 		return false;
5353 	}
5354 
5355 	return true;
5356 }
5357 
5358 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p,
5359 				  u64 dsq_id, u64 enq_flags)
5360 {
5361 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
5362 	struct task_struct *ddsp_task;
5363 
5364 	ddsp_task = __this_cpu_read(direct_dispatch_task);
5365 	if (ddsp_task) {
5366 		mark_direct_dispatch(sch, ddsp_task, p, dsq_id, enq_flags);
5367 		return;
5368 	}
5369 
5370 	if (unlikely(dspc->cursor >= scx_dsp_max_batch)) {
5371 		scx_error(sch, "dispatch buffer overflow");
5372 		return;
5373 	}
5374 
5375 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
5376 		.task = p,
5377 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
5378 		.dsq_id = dsq_id,
5379 		.enq_flags = enq_flags,
5380 	};
5381 }
5382 
5383 __bpf_kfunc_start_defs();
5384 
5385 /**
5386  * scx_bpf_dsq_insert - Insert a task into the FIFO queue of a DSQ
5387  * @p: task_struct to insert
5388  * @dsq_id: DSQ to insert into
5389  * @slice: duration @p can run for in nsecs, 0 to keep the current value
5390  * @enq_flags: SCX_ENQ_*
5391  *
5392  * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to
5393  * call this function spuriously. Can be called from ops.enqueue(),
5394  * ops.select_cpu(), and ops.dispatch().
5395  *
5396  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
5397  * and @p must match the task being enqueued.
5398  *
5399  * When called from ops.select_cpu(), @enq_flags and @dsp_id are stored, and @p
5400  * will be directly inserted into the corresponding dispatch queue after
5401  * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be
5402  * inserted into the local DSQ of the CPU returned by ops.select_cpu().
5403  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
5404  * task is inserted.
5405  *
5406  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
5407  * and this function can be called upto ops.dispatch_max_batch times to insert
5408  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
5409  * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the
5410  * counter.
5411  *
5412  * This function doesn't have any locking restrictions and may be called under
5413  * BPF locks (in the future when BPF introduces more flexible locking).
5414  *
5415  * @p is allowed to run for @slice. The scheduling path is triggered on slice
5416  * exhaustion. If zero, the current residual slice is maintained. If
5417  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
5418  * scx_bpf_kick_cpu() to trigger scheduling.
5419  *
5420  * Returns %true on successful insertion, %false on failure. On the root
5421  * scheduler, %false return triggers scheduler abort and the caller doesn't need
5422  * to check the return value.
5423  */
5424 __bpf_kfunc bool scx_bpf_dsq_insert___v2(struct task_struct *p, u64 dsq_id,
5425 					 u64 slice, u64 enq_flags)
5426 {
5427 	struct scx_sched *sch;
5428 
5429 	guard(rcu)();
5430 	sch = rcu_dereference(scx_root);
5431 	if (unlikely(!sch))
5432 		return false;
5433 
5434 	if (!scx_dsq_insert_preamble(sch, p, enq_flags))
5435 		return false;
5436 
5437 	if (slice)
5438 		p->scx.slice = slice;
5439 	else
5440 		p->scx.slice = p->scx.slice ?: 1;
5441 
5442 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags);
5443 
5444 	return true;
5445 }
5446 
5447 /*
5448  * COMPAT: Will be removed in v6.23 along with the ___v2 suffix.
5449  */
5450 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id,
5451 					     u64 slice, u64 enq_flags)
5452 {
5453 	scx_bpf_dsq_insert___v2(p, dsq_id, slice, enq_flags);
5454 }
5455 
5456 static bool scx_dsq_insert_vtime(struct scx_sched *sch, struct task_struct *p,
5457 				 u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
5458 {
5459 	if (!scx_dsq_insert_preamble(sch, p, enq_flags))
5460 		return false;
5461 
5462 	if (slice)
5463 		p->scx.slice = slice;
5464 	else
5465 		p->scx.slice = p->scx.slice ?: 1;
5466 
5467 	p->scx.dsq_vtime = vtime;
5468 
5469 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
5470 
5471 	return true;
5472 }
5473 
5474 struct scx_bpf_dsq_insert_vtime_args {
5475 	/* @p can't be packed together as KF_RCU is not transitive */
5476 	u64			dsq_id;
5477 	u64			slice;
5478 	u64			vtime;
5479 	u64			enq_flags;
5480 };
5481 
5482 /**
5483  * __scx_bpf_dsq_insert_vtime - Arg-wrapped vtime DSQ insertion
5484  * @p: task_struct to insert
5485  * @args: struct containing the rest of the arguments
5486  *       @args->dsq_id: DSQ to insert into
5487  *       @args->slice: duration @p can run for in nsecs, 0 to keep the current value
5488  *       @args->vtime: @p's ordering inside the vtime-sorted queue of the target DSQ
5489  *       @args->enq_flags: SCX_ENQ_*
5490  *
5491  * Wrapper kfunc that takes arguments via struct to work around BPF's 5 argument
5492  * limit. BPF programs should use scx_bpf_dsq_insert_vtime() which is provided
5493  * as an inline wrapper in common.bpf.h.
5494  *
5495  * Insert @p into the vtime priority queue of the DSQ identified by
5496  * @args->dsq_id. Tasks queued into the priority queue are ordered by
5497  * @args->vtime. All other aspects are identical to scx_bpf_dsq_insert().
5498  *
5499  * @args->vtime ordering is according to time_before64() which considers
5500  * wrapping. A numerically larger vtime may indicate an earlier position in the
5501  * ordering and vice-versa.
5502  *
5503  * A DSQ can only be used as a FIFO or priority queue at any given time and this
5504  * function must not be called on a DSQ which already has one or more FIFO tasks
5505  * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and
5506  * SCX_DSQ_GLOBAL) cannot be used as priority queues.
5507  *
5508  * Returns %true on successful insertion, %false on failure. On the root
5509  * scheduler, %false return triggers scheduler abort and the caller doesn't need
5510  * to check the return value.
5511  */
5512 __bpf_kfunc bool
5513 __scx_bpf_dsq_insert_vtime(struct task_struct *p,
5514 			   struct scx_bpf_dsq_insert_vtime_args *args)
5515 {
5516 	struct scx_sched *sch;
5517 
5518 	guard(rcu)();
5519 
5520 	sch = rcu_dereference(scx_root);
5521 	if (unlikely(!sch))
5522 		return false;
5523 
5524 	return scx_dsq_insert_vtime(sch, p, args->dsq_id, args->slice,
5525 				    args->vtime, args->enq_flags);
5526 }
5527 
5528 /*
5529  * COMPAT: Will be removed in v6.23.
5530  */
5531 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id,
5532 					  u64 slice, u64 vtime, u64 enq_flags)
5533 {
5534 	struct scx_sched *sch;
5535 
5536 	guard(rcu)();
5537 
5538 	sch = rcu_dereference(scx_root);
5539 	if (unlikely(!sch))
5540 		return;
5541 
5542 	scx_dsq_insert_vtime(sch, p, dsq_id, slice, vtime, enq_flags);
5543 }
5544 
5545 __bpf_kfunc_end_defs();
5546 
5547 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
5548 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_RCU)
5549 BTF_ID_FLAGS(func, scx_bpf_dsq_insert___v2, KF_RCU)
5550 BTF_ID_FLAGS(func, __scx_bpf_dsq_insert_vtime, KF_RCU)
5551 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU)
5552 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
5553 
5554 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
5555 	.owner			= THIS_MODULE,
5556 	.set			= &scx_kfunc_ids_enqueue_dispatch,
5557 };
5558 
5559 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit,
5560 			 struct task_struct *p, u64 dsq_id, u64 enq_flags)
5561 {
5562 	struct scx_sched *sch = scx_root;
5563 	struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq;
5564 	struct rq *this_rq, *src_rq, *locked_rq;
5565 	bool dispatched = false;
5566 	bool in_balance;
5567 	unsigned long flags;
5568 
5569 	if (!scx_kf_allowed_if_unlocked() &&
5570 	    !scx_kf_allowed(sch, SCX_KF_DISPATCH))
5571 		return false;
5572 
5573 	/*
5574 	 * Can be called from either ops.dispatch() locking this_rq() or any
5575 	 * context where no rq lock is held. If latter, lock @p's task_rq which
5576 	 * we'll likely need anyway.
5577 	 */
5578 	src_rq = task_rq(p);
5579 
5580 	local_irq_save(flags);
5581 	this_rq = this_rq();
5582 	in_balance = this_rq->scx.flags & SCX_RQ_IN_BALANCE;
5583 
5584 	if (in_balance) {
5585 		if (this_rq != src_rq) {
5586 			raw_spin_rq_unlock(this_rq);
5587 			raw_spin_rq_lock(src_rq);
5588 		}
5589 	} else {
5590 		raw_spin_rq_lock(src_rq);
5591 	}
5592 
5593 	/*
5594 	 * If the BPF scheduler keeps calling this function repeatedly, it can
5595 	 * cause similar live-lock conditions as consume_dispatch_q(). Insert a
5596 	 * breather if necessary.
5597 	 */
5598 	scx_breather(src_rq);
5599 
5600 	locked_rq = src_rq;
5601 	raw_spin_lock(&src_dsq->lock);
5602 
5603 	/*
5604 	 * Did someone else get to it? @p could have already left $src_dsq, got
5605 	 * re-enqueud, or be in the process of being consumed by someone else.
5606 	 */
5607 	if (unlikely(p->scx.dsq != src_dsq ||
5608 		     u32_before(kit->cursor.priv, p->scx.dsq_seq) ||
5609 		     p->scx.holding_cpu >= 0) ||
5610 	    WARN_ON_ONCE(src_rq != task_rq(p))) {
5611 		raw_spin_unlock(&src_dsq->lock);
5612 		goto out;
5613 	}
5614 
5615 	/* @p is still on $src_dsq and stable, determine the destination */
5616 	dst_dsq = find_dsq_for_dispatch(sch, this_rq, dsq_id, p);
5617 
5618 	/*
5619 	 * Apply vtime and slice updates before moving so that the new time is
5620 	 * visible before inserting into $dst_dsq. @p is still on $src_dsq but
5621 	 * this is safe as we're locking it.
5622 	 */
5623 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME)
5624 		p->scx.dsq_vtime = kit->vtime;
5625 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE)
5626 		p->scx.slice = kit->slice;
5627 
5628 	/* execute move */
5629 	locked_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq);
5630 	dispatched = true;
5631 out:
5632 	if (in_balance) {
5633 		if (this_rq != locked_rq) {
5634 			raw_spin_rq_unlock(locked_rq);
5635 			raw_spin_rq_lock(this_rq);
5636 		}
5637 	} else {
5638 		raw_spin_rq_unlock_irqrestore(locked_rq, flags);
5639 	}
5640 
5641 	kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE |
5642 			       __SCX_DSQ_ITER_HAS_VTIME);
5643 	return dispatched;
5644 }
5645 
5646 __bpf_kfunc_start_defs();
5647 
5648 /**
5649  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
5650  *
5651  * Can only be called from ops.dispatch().
5652  */
5653 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(void)
5654 {
5655 	struct scx_sched *sch;
5656 
5657 	guard(rcu)();
5658 
5659 	sch = rcu_dereference(scx_root);
5660 	if (unlikely(!sch))
5661 		return 0;
5662 
5663 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
5664 		return 0;
5665 
5666 	return scx_dsp_max_batch - __this_cpu_read(scx_dsp_ctx->cursor);
5667 }
5668 
5669 /**
5670  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
5671  *
5672  * Cancel the latest dispatch. Can be called multiple times to cancel further
5673  * dispatches. Can only be called from ops.dispatch().
5674  */
5675 __bpf_kfunc void scx_bpf_dispatch_cancel(void)
5676 {
5677 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
5678 	struct scx_sched *sch;
5679 
5680 	guard(rcu)();
5681 
5682 	sch = rcu_dereference(scx_root);
5683 	if (unlikely(!sch))
5684 		return;
5685 
5686 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
5687 		return;
5688 
5689 	if (dspc->cursor > 0)
5690 		dspc->cursor--;
5691 	else
5692 		scx_error(sch, "dispatch buffer underflow");
5693 }
5694 
5695 /**
5696  * scx_bpf_dsq_move_to_local - move a task from a DSQ to the current CPU's local DSQ
5697  * @dsq_id: DSQ to move task from
5698  *
5699  * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's
5700  * local DSQ for execution. Can only be called from ops.dispatch().
5701  *
5702  * This function flushes the in-flight dispatches from scx_bpf_dsq_insert()
5703  * before trying to move from the specified DSQ. It may also grab rq locks and
5704  * thus can't be called under any BPF locks.
5705  *
5706  * Returns %true if a task has been moved, %false if there isn't any task to
5707  * move.
5708  */
5709 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id)
5710 {
5711 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
5712 	struct scx_dispatch_q *dsq;
5713 	struct scx_sched *sch;
5714 
5715 	guard(rcu)();
5716 
5717 	sch = rcu_dereference(scx_root);
5718 	if (unlikely(!sch))
5719 		return false;
5720 
5721 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
5722 		return false;
5723 
5724 	flush_dispatch_buf(sch, dspc->rq);
5725 
5726 	dsq = find_user_dsq(sch, dsq_id);
5727 	if (unlikely(!dsq)) {
5728 		scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id);
5729 		return false;
5730 	}
5731 
5732 	if (consume_dispatch_q(sch, dspc->rq, dsq)) {
5733 		/*
5734 		 * A successfully consumed task can be dequeued before it starts
5735 		 * running while the CPU is trying to migrate other dispatched
5736 		 * tasks. Bump nr_tasks to tell balance_scx() to retry on empty
5737 		 * local DSQ.
5738 		 */
5739 		dspc->nr_tasks++;
5740 		return true;
5741 	} else {
5742 		return false;
5743 	}
5744 }
5745 
5746 /**
5747  * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs
5748  * @it__iter: DSQ iterator in progress
5749  * @slice: duration the moved task can run for in nsecs
5750  *
5751  * Override the slice of the next task that will be moved from @it__iter using
5752  * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous
5753  * slice duration is kept.
5754  */
5755 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter,
5756 					    u64 slice)
5757 {
5758 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
5759 
5760 	kit->slice = slice;
5761 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE;
5762 }
5763 
5764 /**
5765  * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs
5766  * @it__iter: DSQ iterator in progress
5767  * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ
5768  *
5769  * Override the vtime of the next task that will be moved from @it__iter using
5770  * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice
5771  * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the
5772  * override is ignored and cleared.
5773  */
5774 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter,
5775 					    u64 vtime)
5776 {
5777 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
5778 
5779 	kit->vtime = vtime;
5780 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME;
5781 }
5782 
5783 /**
5784  * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ
5785  * @it__iter: DSQ iterator in progress
5786  * @p: task to transfer
5787  * @dsq_id: DSQ to move @p to
5788  * @enq_flags: SCX_ENQ_*
5789  *
5790  * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ
5791  * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can
5792  * be the destination.
5793  *
5794  * For the transfer to be successful, @p must still be on the DSQ and have been
5795  * queued before the DSQ iteration started. This function doesn't care whether
5796  * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have
5797  * been queued before the iteration started.
5798  *
5799  * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update.
5800  *
5801  * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq
5802  * lock (e.g. BPF timers or SYSCALL programs).
5803  *
5804  * Returns %true if @p has been consumed, %false if @p had already been
5805  * consumed, dequeued, or, for sub-scheds, @dsq_id points to a disallowed local
5806  * DSQ.
5807  */
5808 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter,
5809 				  struct task_struct *p, u64 dsq_id,
5810 				  u64 enq_flags)
5811 {
5812 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
5813 			    p, dsq_id, enq_flags);
5814 }
5815 
5816 /**
5817  * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ
5818  * @it__iter: DSQ iterator in progress
5819  * @p: task to transfer
5820  * @dsq_id: DSQ to move @p to
5821  * @enq_flags: SCX_ENQ_*
5822  *
5823  * Transfer @p which is on the DSQ currently iterated by @it__iter to the
5824  * priority queue of the DSQ specified by @dsq_id. The destination must be a
5825  * user DSQ as only user DSQs support priority queue.
5826  *
5827  * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice()
5828  * and scx_bpf_dsq_move_set_vtime() to update.
5829  *
5830  * All other aspects are identical to scx_bpf_dsq_move(). See
5831  * scx_bpf_dsq_insert_vtime() for more information on @vtime.
5832  */
5833 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter,
5834 					struct task_struct *p, u64 dsq_id,
5835 					u64 enq_flags)
5836 {
5837 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
5838 			    p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
5839 }
5840 
5841 __bpf_kfunc_end_defs();
5842 
5843 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
5844 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots)
5845 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel)
5846 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local)
5847 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
5848 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
5849 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
5850 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
5851 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
5852 
5853 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
5854 	.owner			= THIS_MODULE,
5855 	.set			= &scx_kfunc_ids_dispatch,
5856 };
5857 
5858 __bpf_kfunc_start_defs();
5859 
5860 /**
5861  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
5862  *
5863  * Iterate over all of the tasks currently enqueued on the local DSQ of the
5864  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
5865  * processed tasks. Can only be called from ops.cpu_release().
5866  */
5867 __bpf_kfunc u32 scx_bpf_reenqueue_local(void)
5868 {
5869 	struct scx_sched *sch;
5870 	LIST_HEAD(tasks);
5871 	u32 nr_enqueued = 0;
5872 	struct rq *rq;
5873 	struct task_struct *p, *n;
5874 
5875 	guard(rcu)();
5876 	sch = rcu_dereference(scx_root);
5877 	if (unlikely(!sch))
5878 		return 0;
5879 
5880 	if (!scx_kf_allowed(sch, SCX_KF_CPU_RELEASE))
5881 		return 0;
5882 
5883 	rq = cpu_rq(smp_processor_id());
5884 	lockdep_assert_rq_held(rq);
5885 
5886 	/*
5887 	 * The BPF scheduler may choose to dispatch tasks back to
5888 	 * @rq->scx.local_dsq. Move all candidate tasks off to a private list
5889 	 * first to avoid processing the same tasks repeatedly.
5890 	 */
5891 	list_for_each_entry_safe(p, n, &rq->scx.local_dsq.list,
5892 				 scx.dsq_list.node) {
5893 		/*
5894 		 * If @p is being migrated, @p's current CPU may not agree with
5895 		 * its allowed CPUs and the migration_cpu_stop is about to
5896 		 * deactivate and re-activate @p anyway. Skip re-enqueueing.
5897 		 *
5898 		 * While racing sched property changes may also dequeue and
5899 		 * re-enqueue a migrating task while its current CPU and allowed
5900 		 * CPUs disagree, they use %ENQUEUE_RESTORE which is bypassed to
5901 		 * the current local DSQ for running tasks and thus are not
5902 		 * visible to the BPF scheduler.
5903 		 */
5904 		if (p->migration_pending)
5905 			continue;
5906 
5907 		dispatch_dequeue(rq, p);
5908 		list_add_tail(&p->scx.dsq_list.node, &tasks);
5909 	}
5910 
5911 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
5912 		list_del_init(&p->scx.dsq_list.node);
5913 		do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
5914 		nr_enqueued++;
5915 	}
5916 
5917 	return nr_enqueued;
5918 }
5919 
5920 __bpf_kfunc_end_defs();
5921 
5922 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
5923 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local)
5924 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
5925 
5926 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
5927 	.owner			= THIS_MODULE,
5928 	.set			= &scx_kfunc_ids_cpu_release,
5929 };
5930 
5931 __bpf_kfunc_start_defs();
5932 
5933 /**
5934  * scx_bpf_create_dsq - Create a custom DSQ
5935  * @dsq_id: DSQ to create
5936  * @node: NUMA node to allocate from
5937  *
5938  * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable
5939  * scx callback, and any BPF_PROG_TYPE_SYSCALL prog.
5940  */
5941 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node)
5942 {
5943 	struct scx_dispatch_q *dsq;
5944 	struct scx_sched *sch;
5945 	s32 ret;
5946 
5947 	if (unlikely(node >= (int)nr_node_ids ||
5948 		     (node < 0 && node != NUMA_NO_NODE)))
5949 		return -EINVAL;
5950 
5951 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN))
5952 		return -EINVAL;
5953 
5954 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
5955 	if (!dsq)
5956 		return -ENOMEM;
5957 
5958 	init_dsq(dsq, dsq_id);
5959 
5960 	rcu_read_lock();
5961 
5962 	sch = rcu_dereference(scx_root);
5963 	if (sch)
5964 		ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node,
5965 						    dsq_hash_params);
5966 	else
5967 		ret = -ENODEV;
5968 
5969 	rcu_read_unlock();
5970 	if (ret)
5971 		kfree(dsq);
5972 	return ret;
5973 }
5974 
5975 __bpf_kfunc_end_defs();
5976 
5977 BTF_KFUNCS_START(scx_kfunc_ids_unlocked)
5978 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_SLEEPABLE)
5979 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
5980 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
5981 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
5982 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
5983 BTF_KFUNCS_END(scx_kfunc_ids_unlocked)
5984 
5985 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = {
5986 	.owner			= THIS_MODULE,
5987 	.set			= &scx_kfunc_ids_unlocked,
5988 };
5989 
5990 __bpf_kfunc_start_defs();
5991 
5992 /**
5993  * scx_bpf_task_set_slice - Set task's time slice
5994  * @p: task of interest
5995  * @slice: time slice to set in nsecs
5996  *
5997  * Set @p's time slice to @slice. Returns %true on success, %false if the
5998  * calling scheduler doesn't have authority over @p.
5999  */
6000 __bpf_kfunc bool scx_bpf_task_set_slice(struct task_struct *p, u64 slice)
6001 {
6002 	p->scx.slice = slice;
6003 	return true;
6004 }
6005 
6006 /**
6007  * scx_bpf_task_set_dsq_vtime - Set task's virtual time for DSQ ordering
6008  * @p: task of interest
6009  * @vtime: virtual time to set
6010  *
6011  * Set @p's virtual time to @vtime. Returns %true on success, %false if the
6012  * calling scheduler doesn't have authority over @p.
6013  */
6014 __bpf_kfunc bool scx_bpf_task_set_dsq_vtime(struct task_struct *p, u64 vtime)
6015 {
6016 	p->scx.dsq_vtime = vtime;
6017 	return true;
6018 }
6019 
6020 static void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags)
6021 {
6022 	struct rq *this_rq;
6023 	unsigned long irq_flags;
6024 
6025 	if (!ops_cpu_valid(sch, cpu, NULL))
6026 		return;
6027 
6028 	local_irq_save(irq_flags);
6029 
6030 	this_rq = this_rq();
6031 
6032 	/*
6033 	 * While bypassing for PM ops, IRQ handling may not be online which can
6034 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
6035 	 * IRQ status update. Suppress kicking.
6036 	 */
6037 	if (scx_rq_bypassing(this_rq))
6038 		goto out;
6039 
6040 	/*
6041 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
6042 	 * rq locks. We can probably be smarter and avoid bouncing if called
6043 	 * from ops which don't hold a rq lock.
6044 	 */
6045 	if (flags & SCX_KICK_IDLE) {
6046 		struct rq *target_rq = cpu_rq(cpu);
6047 
6048 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT)))
6049 			scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
6050 
6051 		if (raw_spin_rq_trylock(target_rq)) {
6052 			if (can_skip_idle_kick(target_rq)) {
6053 				raw_spin_rq_unlock(target_rq);
6054 				goto out;
6055 			}
6056 			raw_spin_rq_unlock(target_rq);
6057 		}
6058 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick_if_idle);
6059 	} else {
6060 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick);
6061 
6062 		if (flags & SCX_KICK_PREEMPT)
6063 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_preempt);
6064 		if (flags & SCX_KICK_WAIT)
6065 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_wait);
6066 	}
6067 
6068 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
6069 out:
6070 	local_irq_restore(irq_flags);
6071 }
6072 
6073 /**
6074  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
6075  * @cpu: cpu to kick
6076  * @flags: %SCX_KICK_* flags
6077  *
6078  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
6079  * trigger rescheduling on a busy CPU. This can be called from any online
6080  * scx_ops operation and the actual kicking is performed asynchronously through
6081  * an irq work.
6082  */
6083 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags)
6084 {
6085 	struct scx_sched *sch;
6086 
6087 	guard(rcu)();
6088 	sch = rcu_dereference(scx_root);
6089 	if (likely(sch))
6090 		scx_kick_cpu(sch, cpu, flags);
6091 }
6092 
6093 /**
6094  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
6095  * @dsq_id: id of the DSQ
6096  *
6097  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
6098  * -%ENOENT is returned.
6099  */
6100 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id)
6101 {
6102 	struct scx_sched *sch;
6103 	struct scx_dispatch_q *dsq;
6104 	s32 ret;
6105 
6106 	preempt_disable();
6107 
6108 	sch = rcu_dereference_sched(scx_root);
6109 	if (unlikely(!sch)) {
6110 		ret = -ENODEV;
6111 		goto out;
6112 	}
6113 
6114 	if (dsq_id == SCX_DSQ_LOCAL) {
6115 		ret = READ_ONCE(this_rq()->scx.local_dsq.nr);
6116 		goto out;
6117 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
6118 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
6119 
6120 		if (ops_cpu_valid(sch, cpu, NULL)) {
6121 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
6122 			goto out;
6123 		}
6124 	} else {
6125 		dsq = find_user_dsq(sch, dsq_id);
6126 		if (dsq) {
6127 			ret = READ_ONCE(dsq->nr);
6128 			goto out;
6129 		}
6130 	}
6131 	ret = -ENOENT;
6132 out:
6133 	preempt_enable();
6134 	return ret;
6135 }
6136 
6137 /**
6138  * scx_bpf_destroy_dsq - Destroy a custom DSQ
6139  * @dsq_id: DSQ to destroy
6140  *
6141  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
6142  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
6143  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
6144  * which doesn't exist. Can be called from any online scx_ops operations.
6145  */
6146 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id)
6147 {
6148 	struct scx_sched *sch;
6149 
6150 	rcu_read_lock();
6151 	sch = rcu_dereference(scx_root);
6152 	if (sch)
6153 		destroy_dsq(sch, dsq_id);
6154 	rcu_read_unlock();
6155 }
6156 
6157 /**
6158  * bpf_iter_scx_dsq_new - Create a DSQ iterator
6159  * @it: iterator to initialize
6160  * @dsq_id: DSQ to iterate
6161  * @flags: %SCX_DSQ_ITER_*
6162  *
6163  * Initialize BPF iterator @it which can be used with bpf_for_each() to walk
6164  * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes
6165  * tasks which are already queued when this function is invoked.
6166  */
6167 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id,
6168 				     u64 flags)
6169 {
6170 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
6171 	struct scx_sched *sch;
6172 
6173 	BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) >
6174 		     sizeof(struct bpf_iter_scx_dsq));
6175 	BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) !=
6176 		     __alignof__(struct bpf_iter_scx_dsq));
6177 
6178 	/*
6179 	 * next() and destroy() will be called regardless of the return value.
6180 	 * Always clear $kit->dsq.
6181 	 */
6182 	kit->dsq = NULL;
6183 
6184 	sch = rcu_dereference_check(scx_root, rcu_read_lock_bh_held());
6185 	if (unlikely(!sch))
6186 		return -ENODEV;
6187 
6188 	if (flags & ~__SCX_DSQ_ITER_USER_FLAGS)
6189 		return -EINVAL;
6190 
6191 	kit->dsq = find_user_dsq(sch, dsq_id);
6192 	if (!kit->dsq)
6193 		return -ENOENT;
6194 
6195 	INIT_LIST_HEAD(&kit->cursor.node);
6196 	kit->cursor.flags = SCX_DSQ_LNODE_ITER_CURSOR | flags;
6197 	kit->cursor.priv = READ_ONCE(kit->dsq->seq);
6198 
6199 	return 0;
6200 }
6201 
6202 /**
6203  * bpf_iter_scx_dsq_next - Progress a DSQ iterator
6204  * @it: iterator to progress
6205  *
6206  * Return the next task. See bpf_iter_scx_dsq_new().
6207  */
6208 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it)
6209 {
6210 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
6211 	bool rev = kit->cursor.flags & SCX_DSQ_ITER_REV;
6212 	struct task_struct *p;
6213 	unsigned long flags;
6214 
6215 	if (!kit->dsq)
6216 		return NULL;
6217 
6218 	raw_spin_lock_irqsave(&kit->dsq->lock, flags);
6219 
6220 	if (list_empty(&kit->cursor.node))
6221 		p = NULL;
6222 	else
6223 		p = container_of(&kit->cursor, struct task_struct, scx.dsq_list);
6224 
6225 	/*
6226 	 * Only tasks which were queued before the iteration started are
6227 	 * visible. This bounds BPF iterations and guarantees that vtime never
6228 	 * jumps in the other direction while iterating.
6229 	 */
6230 	do {
6231 		p = nldsq_next_task(kit->dsq, p, rev);
6232 	} while (p && unlikely(u32_before(kit->cursor.priv, p->scx.dsq_seq)));
6233 
6234 	if (p) {
6235 		if (rev)
6236 			list_move_tail(&kit->cursor.node, &p->scx.dsq_list.node);
6237 		else
6238 			list_move(&kit->cursor.node, &p->scx.dsq_list.node);
6239 	} else {
6240 		list_del_init(&kit->cursor.node);
6241 	}
6242 
6243 	raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
6244 
6245 	return p;
6246 }
6247 
6248 /**
6249  * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator
6250  * @it: iterator to destroy
6251  *
6252  * Undo scx_iter_scx_dsq_new().
6253  */
6254 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it)
6255 {
6256 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
6257 
6258 	if (!kit->dsq)
6259 		return;
6260 
6261 	if (!list_empty(&kit->cursor.node)) {
6262 		unsigned long flags;
6263 
6264 		raw_spin_lock_irqsave(&kit->dsq->lock, flags);
6265 		list_del_init(&kit->cursor.node);
6266 		raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
6267 	}
6268 	kit->dsq = NULL;
6269 }
6270 
6271 /**
6272  * scx_bpf_dsq_peek - Lockless peek at the first element.
6273  * @dsq_id: DSQ to examine.
6274  *
6275  * Read the first element in the DSQ. This is semantically equivalent to using
6276  * the DSQ iterator, but is lockfree. Of course, like any lockless operation,
6277  * this provides only a point-in-time snapshot, and the contents may change
6278  * by the time any subsequent locking operation reads the queue.
6279  *
6280  * Returns the pointer, or NULL indicates an empty queue OR internal error.
6281  */
6282 __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id)
6283 {
6284 	struct scx_sched *sch;
6285 	struct scx_dispatch_q *dsq;
6286 
6287 	sch = rcu_dereference(scx_root);
6288 	if (unlikely(!sch))
6289 		return NULL;
6290 
6291 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) {
6292 		scx_error(sch, "peek disallowed on builtin DSQ 0x%llx", dsq_id);
6293 		return NULL;
6294 	}
6295 
6296 	dsq = find_user_dsq(sch, dsq_id);
6297 	if (unlikely(!dsq)) {
6298 		scx_error(sch, "peek on non-existent DSQ 0x%llx", dsq_id);
6299 		return NULL;
6300 	}
6301 
6302 	return rcu_dereference(dsq->first_task);
6303 }
6304 
6305 __bpf_kfunc_end_defs();
6306 
6307 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
6308 			 size_t line_size, char *fmt, unsigned long long *data,
6309 			 u32 data__sz)
6310 {
6311 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
6312 	s32 ret;
6313 
6314 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
6315 	    (data__sz && !data)) {
6316 		scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz);
6317 		return -EINVAL;
6318 	}
6319 
6320 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
6321 	if (ret < 0) {
6322 		scx_error(sch, "failed to read data fields (%d)", ret);
6323 		return ret;
6324 	}
6325 
6326 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
6327 				  &bprintf_data);
6328 	if (ret < 0) {
6329 		scx_error(sch, "format preparation failed (%d)", ret);
6330 		return ret;
6331 	}
6332 
6333 	ret = bstr_printf(line_buf, line_size, fmt,
6334 			  bprintf_data.bin_args);
6335 	bpf_bprintf_cleanup(&bprintf_data);
6336 	if (ret < 0) {
6337 		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
6338 		return ret;
6339 	}
6340 
6341 	return ret;
6342 }
6343 
6344 static s32 bstr_format(struct scx_sched *sch, struct scx_bstr_buf *buf,
6345 		       char *fmt, unsigned long long *data, u32 data__sz)
6346 {
6347 	return __bstr_format(sch, buf->data, buf->line, sizeof(buf->line),
6348 			     fmt, data, data__sz);
6349 }
6350 
6351 __bpf_kfunc_start_defs();
6352 
6353 /**
6354  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
6355  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
6356  * @fmt: error message format string
6357  * @data: format string parameters packaged using ___bpf_fill() macro
6358  * @data__sz: @data len, must end in '__sz' for the verifier
6359  *
6360  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
6361  * disabling.
6362  */
6363 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
6364 				   unsigned long long *data, u32 data__sz)
6365 {
6366 	struct scx_sched *sch;
6367 	unsigned long flags;
6368 
6369 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
6370 	sch = rcu_dereference_bh(scx_root);
6371 	if (likely(sch) &&
6372 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
6373 		scx_exit(sch, SCX_EXIT_UNREG_BPF, exit_code, "%s", scx_exit_bstr_buf.line);
6374 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
6375 }
6376 
6377 /**
6378  * scx_bpf_error_bstr - Indicate fatal error
6379  * @fmt: error message format string
6380  * @data: format string parameters packaged using ___bpf_fill() macro
6381  * @data__sz: @data len, must end in '__sz' for the verifier
6382  *
6383  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
6384  * disabling.
6385  */
6386 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
6387 				    u32 data__sz)
6388 {
6389 	struct scx_sched *sch;
6390 	unsigned long flags;
6391 
6392 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
6393 	sch = rcu_dereference_bh(scx_root);
6394 	if (likely(sch) &&
6395 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
6396 		scx_exit(sch, SCX_EXIT_ERROR_BPF, 0, "%s", scx_exit_bstr_buf.line);
6397 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
6398 }
6399 
6400 /**
6401  * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler
6402  * @fmt: format string
6403  * @data: format string parameters packaged using ___bpf_fill() macro
6404  * @data__sz: @data len, must end in '__sz' for the verifier
6405  *
6406  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
6407  * dump_task() to generate extra debug dump specific to the BPF scheduler.
6408  *
6409  * The extra dump may be multiple lines. A single line may be split over
6410  * multiple calls. The last line is automatically terminated.
6411  */
6412 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
6413 				   u32 data__sz)
6414 {
6415 	struct scx_sched *sch;
6416 	struct scx_dump_data *dd = &scx_dump_data;
6417 	struct scx_bstr_buf *buf = &dd->buf;
6418 	s32 ret;
6419 
6420 	guard(rcu)();
6421 
6422 	sch = rcu_dereference(scx_root);
6423 	if (unlikely(!sch))
6424 		return;
6425 
6426 	if (raw_smp_processor_id() != dd->cpu) {
6427 		scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends");
6428 		return;
6429 	}
6430 
6431 	/* append the formatted string to the line buf */
6432 	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
6433 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
6434 	if (ret < 0) {
6435 		dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
6436 			  dd->prefix, fmt, data, data__sz, ret);
6437 		return;
6438 	}
6439 
6440 	dd->cursor += ret;
6441 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
6442 
6443 	if (!dd->cursor)
6444 		return;
6445 
6446 	/*
6447 	 * If the line buf overflowed or ends in a newline, flush it into the
6448 	 * dump. This is to allow the caller to generate a single line over
6449 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
6450 	 * the line buf, the only case which can lead to an unexpected
6451 	 * truncation is when the caller keeps generating newlines in the middle
6452 	 * instead of the end consecutively. Don't do that.
6453 	 */
6454 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
6455 		ops_dump_flush();
6456 }
6457 
6458 /**
6459  * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU
6460  * @cpu: CPU of interest
6461  *
6462  * Return the maximum relative capacity of @cpu in relation to the most
6463  * performant CPU in the system. The return value is in the range [1,
6464  * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur().
6465  */
6466 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu)
6467 {
6468 	struct scx_sched *sch;
6469 
6470 	guard(rcu)();
6471 
6472 	sch = rcu_dereference(scx_root);
6473 	if (likely(sch) && ops_cpu_valid(sch, cpu, NULL))
6474 		return arch_scale_cpu_capacity(cpu);
6475 	else
6476 		return SCX_CPUPERF_ONE;
6477 }
6478 
6479 /**
6480  * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU
6481  * @cpu: CPU of interest
6482  *
6483  * Return the current relative performance of @cpu in relation to its maximum.
6484  * The return value is in the range [1, %SCX_CPUPERF_ONE].
6485  *
6486  * The current performance level of a CPU in relation to the maximum performance
6487  * available in the system can be calculated as follows:
6488  *
6489  *   scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE
6490  *
6491  * The result is in the range [1, %SCX_CPUPERF_ONE].
6492  */
6493 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu)
6494 {
6495 	struct scx_sched *sch;
6496 
6497 	guard(rcu)();
6498 
6499 	sch = rcu_dereference(scx_root);
6500 	if (likely(sch) && ops_cpu_valid(sch, cpu, NULL))
6501 		return arch_scale_freq_capacity(cpu);
6502 	else
6503 		return SCX_CPUPERF_ONE;
6504 }
6505 
6506 /**
6507  * scx_bpf_cpuperf_set - Set the relative performance target of a CPU
6508  * @cpu: CPU of interest
6509  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
6510  *
6511  * Set the target performance level of @cpu to @perf. @perf is in linear
6512  * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the
6513  * schedutil cpufreq governor chooses the target frequency.
6514  *
6515  * The actual performance level chosen, CPU grouping, and the overhead and
6516  * latency of the operations are dependent on the hardware and cpufreq driver in
6517  * use. Consult hardware and cpufreq documentation for more information. The
6518  * current performance level can be monitored using scx_bpf_cpuperf_cur().
6519  */
6520 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf)
6521 {
6522 	struct scx_sched *sch;
6523 
6524 	guard(rcu)();
6525 
6526 	sch = rcu_dereference(sch);
6527 	if (unlikely(!sch))
6528 		return;
6529 
6530 	if (unlikely(perf > SCX_CPUPERF_ONE)) {
6531 		scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu);
6532 		return;
6533 	}
6534 
6535 	if (ops_cpu_valid(sch, cpu, NULL)) {
6536 		struct rq *rq = cpu_rq(cpu), *locked_rq = scx_locked_rq();
6537 		struct rq_flags rf;
6538 
6539 		/*
6540 		 * When called with an rq lock held, restrict the operation
6541 		 * to the corresponding CPU to prevent ABBA deadlocks.
6542 		 */
6543 		if (locked_rq && rq != locked_rq) {
6544 			scx_error(sch, "Invalid target CPU %d", cpu);
6545 			return;
6546 		}
6547 
6548 		/*
6549 		 * If no rq lock is held, allow to operate on any CPU by
6550 		 * acquiring the corresponding rq lock.
6551 		 */
6552 		if (!locked_rq) {
6553 			rq_lock_irqsave(rq, &rf);
6554 			update_rq_clock(rq);
6555 		}
6556 
6557 		rq->scx.cpuperf_target = perf;
6558 		cpufreq_update_util(rq, 0);
6559 
6560 		if (!locked_rq)
6561 			rq_unlock_irqrestore(rq, &rf);
6562 	}
6563 }
6564 
6565 /**
6566  * scx_bpf_nr_node_ids - Return the number of possible node IDs
6567  *
6568  * All valid node IDs in the system are smaller than the returned value.
6569  */
6570 __bpf_kfunc u32 scx_bpf_nr_node_ids(void)
6571 {
6572 	return nr_node_ids;
6573 }
6574 
6575 /**
6576  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
6577  *
6578  * All valid CPU IDs in the system are smaller than the returned value.
6579  */
6580 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
6581 {
6582 	return nr_cpu_ids;
6583 }
6584 
6585 /**
6586  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
6587  */
6588 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
6589 {
6590 	return cpu_possible_mask;
6591 }
6592 
6593 /**
6594  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
6595  */
6596 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
6597 {
6598 	return cpu_online_mask;
6599 }
6600 
6601 /**
6602  * scx_bpf_put_cpumask - Release a possible/online cpumask
6603  * @cpumask: cpumask to release
6604  */
6605 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
6606 {
6607 	/*
6608 	 * Empty function body because we aren't actually acquiring or releasing
6609 	 * a reference to a global cpumask, which is read-only in the caller and
6610 	 * is never released. The acquire / release semantics here are just used
6611 	 * to make the cpumask is a trusted pointer in the caller.
6612 	 */
6613 }
6614 
6615 /**
6616  * scx_bpf_task_running - Is task currently running?
6617  * @p: task of interest
6618  */
6619 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
6620 {
6621 	return task_rq(p)->curr == p;
6622 }
6623 
6624 /**
6625  * scx_bpf_task_cpu - CPU a task is currently associated with
6626  * @p: task of interest
6627  */
6628 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
6629 {
6630 	return task_cpu(p);
6631 }
6632 
6633 /**
6634  * scx_bpf_cpu_rq - Fetch the rq of a CPU
6635  * @cpu: CPU of the rq
6636  */
6637 __bpf_kfunc struct rq *scx_bpf_cpu_rq(s32 cpu)
6638 {
6639 	struct scx_sched *sch;
6640 
6641 	guard(rcu)();
6642 
6643 	sch = rcu_dereference(scx_root);
6644 	if (unlikely(!sch))
6645 		return NULL;
6646 
6647 	if (!ops_cpu_valid(sch, cpu, NULL))
6648 		return NULL;
6649 
6650 	if (!sch->warned_deprecated_rq) {
6651 		printk_deferred(KERN_WARNING "sched_ext: %s() is deprecated; "
6652 				"use scx_bpf_locked_rq() when holding rq lock "
6653 				"or scx_bpf_cpu_curr() to read remote curr safely.\n", __func__);
6654 		sch->warned_deprecated_rq = true;
6655 	}
6656 
6657 	return cpu_rq(cpu);
6658 }
6659 
6660 /**
6661  * scx_bpf_locked_rq - Return the rq currently locked by SCX
6662  *
6663  * Returns the rq if a rq lock is currently held by SCX.
6664  * Otherwise emits an error and returns NULL.
6665  */
6666 __bpf_kfunc struct rq *scx_bpf_locked_rq(void)
6667 {
6668 	struct scx_sched *sch;
6669 	struct rq *rq;
6670 
6671 	guard(preempt)();
6672 
6673 	sch = rcu_dereference_sched(scx_root);
6674 	if (unlikely(!sch))
6675 		return NULL;
6676 
6677 	rq = scx_locked_rq();
6678 	if (!rq) {
6679 		scx_error(sch, "accessing rq without holding rq lock");
6680 		return NULL;
6681 	}
6682 
6683 	return rq;
6684 }
6685 
6686 /**
6687  * scx_bpf_cpu_curr - Return remote CPU's curr task
6688  * @cpu: CPU of interest
6689  *
6690  * Callers must hold RCU read lock (KF_RCU).
6691  */
6692 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu)
6693 {
6694 	struct scx_sched *sch;
6695 
6696 	guard(rcu)();
6697 
6698 	sch = rcu_dereference(scx_root);
6699 	if (unlikely(!sch))
6700 		return NULL;
6701 
6702 	if (!ops_cpu_valid(sch, cpu, NULL))
6703 		return NULL;
6704 
6705 	return rcu_dereference(cpu_rq(cpu)->curr);
6706 }
6707 
6708 /**
6709  * scx_bpf_task_cgroup - Return the sched cgroup of a task
6710  * @p: task of interest
6711  *
6712  * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with
6713  * from the scheduler's POV. SCX operations should use this function to
6714  * determine @p's current cgroup as, unlike following @p->cgroups,
6715  * @p->sched_task_group is protected by @p's rq lock and thus atomic w.r.t. all
6716  * rq-locked operations. Can be called on the parameter tasks of rq-locked
6717  * operations. The restriction guarantees that @p's rq is locked by the caller.
6718  */
6719 #ifdef CONFIG_CGROUP_SCHED
6720 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p)
6721 {
6722 	struct task_group *tg = p->sched_task_group;
6723 	struct cgroup *cgrp = &cgrp_dfl_root.cgrp;
6724 	struct scx_sched *sch;
6725 
6726 	guard(rcu)();
6727 
6728 	sch = rcu_dereference(scx_root);
6729 	if (unlikely(!sch))
6730 		goto out;
6731 
6732 	if (!scx_kf_allowed_on_arg_tasks(sch, __SCX_KF_RQ_LOCKED, p))
6733 		goto out;
6734 
6735 	cgrp = tg_cgrp(tg);
6736 
6737 out:
6738 	cgroup_get(cgrp);
6739 	return cgrp;
6740 }
6741 #endif
6742 
6743 /**
6744  * scx_bpf_now - Returns a high-performance monotonically non-decreasing
6745  * clock for the current CPU. The clock returned is in nanoseconds.
6746  *
6747  * It provides the following properties:
6748  *
6749  * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently
6750  *  to account for execution time and track tasks' runtime properties.
6751  *  Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which
6752  *  eventually reads a hardware timestamp counter -- is neither performant nor
6753  *  scalable. scx_bpf_now() aims to provide a high-performance clock by
6754  *  using the rq clock in the scheduler core whenever possible.
6755  *
6756  * 2) High enough resolution for the BPF scheduler use cases: In most BPF
6757  *  scheduler use cases, the required clock resolution is lower than the most
6758  *  accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically
6759  *  uses the rq clock in the scheduler core whenever it is valid. It considers
6760  *  that the rq clock is valid from the time the rq clock is updated
6761  *  (update_rq_clock) until the rq is unlocked (rq_unpin_lock).
6762  *
6763  * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now()
6764  *  guarantees the clock never goes backward when comparing them in the same
6765  *  CPU. On the other hand, when comparing clocks in different CPUs, there
6766  *  is no such guarantee -- the clock can go backward. It provides a
6767  *  monotonically *non-decreasing* clock so that it would provide the same
6768  *  clock values in two different scx_bpf_now() calls in the same CPU
6769  *  during the same period of when the rq clock is valid.
6770  */
6771 __bpf_kfunc u64 scx_bpf_now(void)
6772 {
6773 	struct rq *rq;
6774 	u64 clock;
6775 
6776 	preempt_disable();
6777 
6778 	rq = this_rq();
6779 	if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) {
6780 		/*
6781 		 * If the rq clock is valid, use the cached rq clock.
6782 		 *
6783 		 * Note that scx_bpf_now() is re-entrant between a process
6784 		 * context and an interrupt context (e.g., timer interrupt).
6785 		 * However, we don't need to consider the race between them
6786 		 * because such race is not observable from a caller.
6787 		 */
6788 		clock = READ_ONCE(rq->scx.clock);
6789 	} else {
6790 		/*
6791 		 * Otherwise, return a fresh rq clock.
6792 		 *
6793 		 * The rq clock is updated outside of the rq lock.
6794 		 * In this case, keep the updated rq clock invalid so the next
6795 		 * kfunc call outside the rq lock gets a fresh rq clock.
6796 		 */
6797 		clock = sched_clock_cpu(cpu_of(rq));
6798 	}
6799 
6800 	preempt_enable();
6801 
6802 	return clock;
6803 }
6804 
6805 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events)
6806 {
6807 	struct scx_event_stats *e_cpu;
6808 	int cpu;
6809 
6810 	/* Aggregate per-CPU event counters into @events. */
6811 	memset(events, 0, sizeof(*events));
6812 	for_each_possible_cpu(cpu) {
6813 		e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats;
6814 		scx_agg_event(events, e_cpu, SCX_EV_SELECT_CPU_FALLBACK);
6815 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
6816 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_KEEP_LAST);
6817 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_EXITING);
6818 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
6819 		scx_agg_event(events, e_cpu, SCX_EV_REFILL_SLICE_DFL);
6820 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DURATION);
6821 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DISPATCH);
6822 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_ACTIVATE);
6823 	}
6824 }
6825 
6826 /*
6827  * scx_bpf_events - Get a system-wide event counter to
6828  * @events: output buffer from a BPF program
6829  * @events__sz: @events len, must end in '__sz'' for the verifier
6830  */
6831 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events,
6832 				size_t events__sz)
6833 {
6834 	struct scx_sched *sch;
6835 	struct scx_event_stats e_sys;
6836 
6837 	rcu_read_lock();
6838 	sch = rcu_dereference(scx_root);
6839 	if (sch)
6840 		scx_read_events(sch, &e_sys);
6841 	else
6842 		memset(&e_sys, 0, sizeof(e_sys));
6843 	rcu_read_unlock();
6844 
6845 	/*
6846 	 * We cannot entirely trust a BPF-provided size since a BPF program
6847 	 * might be compiled against a different vmlinux.h, of which
6848 	 * scx_event_stats would be larger (a newer vmlinux.h) or smaller
6849 	 * (an older vmlinux.h). Hence, we use the smaller size to avoid
6850 	 * memory corruption.
6851 	 */
6852 	events__sz = min(events__sz, sizeof(*events));
6853 	memcpy(events, &e_sys, events__sz);
6854 }
6855 
6856 __bpf_kfunc_end_defs();
6857 
6858 BTF_KFUNCS_START(scx_kfunc_ids_any)
6859 BTF_ID_FLAGS(func, scx_bpf_task_set_slice, KF_RCU);
6860 BTF_ID_FLAGS(func, scx_bpf_task_set_dsq_vtime, KF_RCU);
6861 BTF_ID_FLAGS(func, scx_bpf_kick_cpu)
6862 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued)
6863 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq)
6864 BTF_ID_FLAGS(func, scx_bpf_dsq_peek, KF_RCU_PROTECTED | KF_RET_NULL)
6865 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_ITER_NEW | KF_RCU_PROTECTED)
6866 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
6867 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
6868 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_TRUSTED_ARGS)
6869 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_TRUSTED_ARGS)
6870 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_TRUSTED_ARGS)
6871 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap)
6872 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur)
6873 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set)
6874 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
6875 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
6876 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
6877 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
6878 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
6879 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
6880 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
6881 BTF_ID_FLAGS(func, scx_bpf_cpu_rq)
6882 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_RET_NULL)
6883 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_RET_NULL | KF_RCU_PROTECTED)
6884 #ifdef CONFIG_CGROUP_SCHED
6885 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_RCU | KF_ACQUIRE)
6886 #endif
6887 BTF_ID_FLAGS(func, scx_bpf_now)
6888 BTF_ID_FLAGS(func, scx_bpf_events, KF_TRUSTED_ARGS)
6889 BTF_KFUNCS_END(scx_kfunc_ids_any)
6890 
6891 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
6892 	.owner			= THIS_MODULE,
6893 	.set			= &scx_kfunc_ids_any,
6894 };
6895 
6896 static int __init scx_init(void)
6897 {
6898 	int ret;
6899 
6900 	/*
6901 	 * kfunc registration can't be done from init_sched_ext_class() as
6902 	 * register_btf_kfunc_id_set() needs most of the system to be up.
6903 	 *
6904 	 * Some kfuncs are context-sensitive and can only be called from
6905 	 * specific SCX ops. They are grouped into BTF sets accordingly.
6906 	 * Unfortunately, BPF currently doesn't have a way of enforcing such
6907 	 * restrictions. Eventually, the verifier should be able to enforce
6908 	 * them. For now, register them the same and make each kfunc explicitly
6909 	 * check using scx_kf_allowed().
6910 	 */
6911 	if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6912 					     &scx_kfunc_set_enqueue_dispatch)) ||
6913 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6914 					     &scx_kfunc_set_dispatch)) ||
6915 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6916 					     &scx_kfunc_set_cpu_release)) ||
6917 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6918 					     &scx_kfunc_set_unlocked)) ||
6919 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
6920 					     &scx_kfunc_set_unlocked)) ||
6921 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6922 					     &scx_kfunc_set_any)) ||
6923 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
6924 					     &scx_kfunc_set_any)) ||
6925 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
6926 					     &scx_kfunc_set_any))) {
6927 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
6928 		return ret;
6929 	}
6930 
6931 	ret = scx_idle_init();
6932 	if (ret) {
6933 		pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret);
6934 		return ret;
6935 	}
6936 
6937 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops);
6938 	if (ret) {
6939 		pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret);
6940 		return ret;
6941 	}
6942 
6943 	ret = register_pm_notifier(&scx_pm_notifier);
6944 	if (ret) {
6945 		pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret);
6946 		return ret;
6947 	}
6948 
6949 	scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj);
6950 	if (!scx_kset) {
6951 		pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n");
6952 		return -ENOMEM;
6953 	}
6954 
6955 	ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group);
6956 	if (ret < 0) {
6957 		pr_err("sched_ext: Failed to add global attributes\n");
6958 		return ret;
6959 	}
6960 
6961 	return 0;
6962 }
6963 __initcall(scx_init);
6964